PackageManagerService.java revision e68b127525c23e8e0cbe1e9dee75534d99e2833d
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; 21import static android.Manifest.permission.WRITE_MEDIA_STORAGE; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 27import static android.content.pm.PackageManager.DELETE_KEEP_DATA; 28import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 29import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED; 30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 31import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 32import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 34import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET; 35import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 36import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 37import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 38import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 40import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 41import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 42import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 43import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 44import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 45import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 46import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 47import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 48import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 49import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 50import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 51import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 52import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 53import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 54import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 55import static android.content.pm.PackageManager.INSTALL_INTERNAL; 56import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK; 59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 62import static android.content.pm.PackageManager.MATCH_ALL; 63import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 64import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE; 65import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE; 66import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS; 67import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY; 68import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY; 69import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 70import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN; 71import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 72import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 73import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 74import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 75import static android.content.pm.PackageManager.PERMISSION_DENIED; 76import static android.content.pm.PackageManager.PERMISSION_GRANTED; 77import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED; 78import static android.content.pm.PackageParser.isApkFile; 79import static android.os.Process.FIRST_APPLICATION_UID; 80import static android.os.Process.PACKAGE_INFO_GID; 81import static android.os.Process.SYSTEM_UID; 82import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 83import static android.system.OsConstants.O_CREAT; 84import static android.system.OsConstants.O_RDWR; 85 86import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 87import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 88import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 89import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 90import static com.android.internal.util.ArrayUtils.appendInt; 91import static com.android.server.pm.Installer.DEXOPT_PUBLIC; 92import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 93import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 94import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 95import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 96import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 97import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason; 98import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter; 99import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 100import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 101import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 102 103import android.Manifest; 104import android.annotation.NonNull; 105import android.annotation.Nullable; 106import android.app.ActivityManager; 107import android.app.ActivityManagerNative; 108import android.app.IActivityManager; 109import android.app.admin.DevicePolicyManagerInternal; 110import android.app.admin.IDevicePolicyManager; 111import android.app.admin.SecurityLog; 112import android.app.backup.IBackupManager; 113import android.app.usage.UsageStatsManager; 114import android.content.BroadcastReceiver; 115import android.content.ComponentName; 116import android.content.Context; 117import android.content.IIntentReceiver; 118import android.content.Intent; 119import android.content.IntentFilter; 120import android.content.IntentFilter.AuthorityEntry; 121import android.content.IntentSender; 122import android.content.IntentSender.SendIntentException; 123import android.content.ServiceConnection; 124import android.content.pm.ActivityInfo; 125import android.content.pm.ApplicationInfo; 126import android.content.pm.AppsQueryHelper; 127import android.content.pm.ComponentInfo; 128import android.content.pm.EphemeralApplicationInfo; 129import android.content.pm.EphemeralResolveInfo; 130import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo; 131import android.content.pm.FeatureInfo; 132import android.content.pm.IOnPermissionsChangeListener; 133import android.content.pm.IPackageDataObserver; 134import android.content.pm.IPackageDeleteObserver; 135import android.content.pm.IPackageDeleteObserver2; 136import android.content.pm.IPackageInstallObserver2; 137import android.content.pm.IPackageInstaller; 138import android.content.pm.IPackageManager; 139import android.content.pm.IPackageMoveObserver; 140import android.content.pm.IPackageStatsObserver; 141import android.content.pm.InstrumentationInfo; 142import android.content.pm.IntentFilterVerificationInfo; 143import android.content.pm.KeySet; 144import android.content.pm.PackageCleanItem; 145import android.content.pm.PackageInfo; 146import android.content.pm.PackageInfoLite; 147import android.content.pm.PackageInstaller; 148import android.content.pm.PackageManager; 149import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 150import android.content.pm.PackageManagerInternal; 151import android.content.pm.PackageParser; 152import android.content.pm.PackageParser.ActivityIntentInfo; 153import android.content.pm.PackageParser.IntentInfo; 154import android.content.pm.PackageParser.PackageLite; 155import android.content.pm.PackageParser.PackageParserException; 156import android.content.pm.PackageStats; 157import android.content.pm.PackageUserState; 158import android.content.pm.ParceledListSlice; 159import android.content.pm.PermissionGroupInfo; 160import android.content.pm.PermissionInfo; 161import android.content.pm.ProviderInfo; 162import android.content.pm.ResolveInfo; 163import android.content.pm.ServiceInfo; 164import android.content.pm.Signature; 165import android.content.pm.UserInfo; 166import android.content.pm.VerifierDeviceIdentity; 167import android.content.pm.VerifierInfo; 168import android.content.res.Resources; 169import android.graphics.Bitmap; 170import android.hardware.display.DisplayManager; 171import android.net.Uri; 172import android.os.Binder; 173import android.os.Build; 174import android.os.Bundle; 175import android.os.Debug; 176import android.os.Environment; 177import android.os.Environment.UserEnvironment; 178import android.os.FileUtils; 179import android.os.Handler; 180import android.os.IBinder; 181import android.os.Looper; 182import android.os.Message; 183import android.os.Parcel; 184import android.os.ParcelFileDescriptor; 185import android.os.Process; 186import android.os.RemoteCallbackList; 187import android.os.RemoteException; 188import android.os.ResultReceiver; 189import android.os.SELinux; 190import android.os.ServiceManager; 191import android.os.SystemClock; 192import android.os.SystemProperties; 193import android.os.Trace; 194import android.os.UserHandle; 195import android.os.UserManager; 196import android.os.storage.IMountService; 197import android.os.storage.MountServiceInternal; 198import android.os.storage.StorageEventListener; 199import android.os.storage.StorageManager; 200import android.os.storage.VolumeInfo; 201import android.os.storage.VolumeRecord; 202import android.security.KeyStore; 203import android.security.SystemKeyStore; 204import android.system.ErrnoException; 205import android.system.Os; 206import android.text.TextUtils; 207import android.text.format.DateUtils; 208import android.util.ArrayMap; 209import android.util.ArraySet; 210import android.util.AtomicFile; 211import android.util.DisplayMetrics; 212import android.util.EventLog; 213import android.util.ExceptionUtils; 214import android.util.Log; 215import android.util.LogPrinter; 216import android.util.MathUtils; 217import android.util.PrintStreamPrinter; 218import android.util.Slog; 219import android.util.SparseArray; 220import android.util.SparseBooleanArray; 221import android.util.SparseIntArray; 222import android.util.Xml; 223import android.view.Display; 224 225import com.android.internal.R; 226import com.android.internal.annotations.GuardedBy; 227import com.android.internal.app.IMediaContainerService; 228import com.android.internal.app.ResolverActivity; 229import com.android.internal.content.NativeLibraryHelper; 230import com.android.internal.content.PackageHelper; 231import com.android.internal.os.IParcelFileDescriptorFactory; 232import com.android.internal.os.InstallerConnection.InstallerException; 233import com.android.internal.os.SomeArgs; 234import com.android.internal.os.Zygote; 235import com.android.internal.telephony.CarrierAppUtils; 236import com.android.internal.util.ArrayUtils; 237import com.android.internal.util.FastPrintWriter; 238import com.android.internal.util.FastXmlSerializer; 239import com.android.internal.util.IndentingPrintWriter; 240import com.android.internal.util.Preconditions; 241import com.android.internal.util.XmlUtils; 242import com.android.server.EventLogTags; 243import com.android.server.FgThread; 244import com.android.server.IntentResolver; 245import com.android.server.LocalServices; 246import com.android.server.ServiceThread; 247import com.android.server.SystemConfig; 248import com.android.server.Watchdog; 249import com.android.server.pm.PermissionsState.PermissionState; 250import com.android.server.pm.Settings.DatabaseVersion; 251import com.android.server.pm.Settings.VersionInfo; 252import com.android.server.storage.DeviceStorageMonitorInternal; 253 254import dalvik.system.DexFile; 255import dalvik.system.VMRuntime; 256 257import libcore.io.IoUtils; 258import libcore.util.EmptyArray; 259 260import org.xmlpull.v1.XmlPullParser; 261import org.xmlpull.v1.XmlPullParserException; 262import org.xmlpull.v1.XmlSerializer; 263 264import java.io.BufferedInputStream; 265import java.io.BufferedOutputStream; 266import java.io.BufferedReader; 267import java.io.ByteArrayInputStream; 268import java.io.ByteArrayOutputStream; 269import java.io.File; 270import java.io.FileDescriptor; 271import java.io.FileNotFoundException; 272import java.io.FileOutputStream; 273import java.io.FileReader; 274import java.io.FilenameFilter; 275import java.io.IOException; 276import java.io.InputStream; 277import java.io.PrintWriter; 278import java.nio.charset.StandardCharsets; 279import java.security.MessageDigest; 280import java.security.NoSuchAlgorithmException; 281import java.security.PublicKey; 282import java.security.cert.Certificate; 283import java.security.cert.CertificateEncodingException; 284import java.security.cert.CertificateException; 285import java.text.SimpleDateFormat; 286import java.util.ArrayList; 287import java.util.Arrays; 288import java.util.Collection; 289import java.util.Collections; 290import java.util.Comparator; 291import java.util.Date; 292import java.util.HashSet; 293import java.util.Iterator; 294import java.util.List; 295import java.util.Map; 296import java.util.Objects; 297import java.util.Set; 298import java.util.concurrent.CountDownLatch; 299import java.util.concurrent.TimeUnit; 300import java.util.concurrent.atomic.AtomicBoolean; 301import java.util.concurrent.atomic.AtomicInteger; 302import java.util.concurrent.atomic.AtomicLong; 303 304/** 305 * Keep track of all those .apks everywhere. 306 * 307 * This is very central to the platform's security; please run the unit 308 * tests whenever making modifications here: 309 * 310runtest -c android.content.pm.PackageManagerTests frameworks-core 311 * 312 * {@hide} 313 */ 314public class PackageManagerService extends IPackageManager.Stub { 315 static final String TAG = "PackageManager"; 316 static final boolean DEBUG_SETTINGS = false; 317 static final boolean DEBUG_PREFERRED = false; 318 static final boolean DEBUG_UPGRADE = false; 319 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 320 private static final boolean DEBUG_BACKUP = false; 321 private static final boolean DEBUG_INSTALL = false; 322 private static final boolean DEBUG_REMOVE = false; 323 private static final boolean DEBUG_BROADCASTS = false; 324 private static final boolean DEBUG_SHOW_INFO = false; 325 private static final boolean DEBUG_PACKAGE_INFO = false; 326 private static final boolean DEBUG_INTENT_MATCHING = false; 327 private static final boolean DEBUG_PACKAGE_SCANNING = false; 328 private static final boolean DEBUG_VERIFY = false; 329 private static final boolean DEBUG_FILTERS = false; 330 331 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 332 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 333 // user, but by default initialize to this. 334 static final boolean DEBUG_DEXOPT = false; 335 336 private static final boolean DEBUG_ABI_SELECTION = false; 337 private static final boolean DEBUG_EPHEMERAL = false; 338 private static final boolean DEBUG_TRIAGED_MISSING = false; 339 private static final boolean DEBUG_APP_DATA = false; 340 341 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 342 343 private static final boolean DISABLE_EPHEMERAL_APPS = true; 344 345 private static final int RADIO_UID = Process.PHONE_UID; 346 private static final int LOG_UID = Process.LOG_UID; 347 private static final int NFC_UID = Process.NFC_UID; 348 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 349 private static final int SHELL_UID = Process.SHELL_UID; 350 351 // Cap the size of permission trees that 3rd party apps can define 352 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 353 354 // Suffix used during package installation when copying/moving 355 // package apks to install directory. 356 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 357 358 static final int SCAN_NO_DEX = 1<<1; 359 static final int SCAN_FORCE_DEX = 1<<2; 360 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 361 static final int SCAN_NEW_INSTALL = 1<<4; 362 static final int SCAN_NO_PATHS = 1<<5; 363 static final int SCAN_UPDATE_TIME = 1<<6; 364 static final int SCAN_DEFER_DEX = 1<<7; 365 static final int SCAN_BOOTING = 1<<8; 366 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 367 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 368 static final int SCAN_REPLACING = 1<<11; 369 static final int SCAN_REQUIRE_KNOWN = 1<<12; 370 static final int SCAN_MOVE = 1<<13; 371 static final int SCAN_INITIAL = 1<<14; 372 static final int SCAN_CHECK_ONLY = 1<<15; 373 static final int SCAN_DONT_KILL_APP = 1<<17; 374 375 static final int REMOVE_CHATTY = 1<<16; 376 377 private static final int[] EMPTY_INT_ARRAY = new int[0]; 378 379 /** 380 * Timeout (in milliseconds) after which the watchdog should declare that 381 * our handler thread is wedged. The usual default for such things is one 382 * minute but we sometimes do very lengthy I/O operations on this thread, 383 * such as installing multi-gigabyte applications, so ours needs to be longer. 384 */ 385 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 386 387 /** 388 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 389 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 390 * settings entry if available, otherwise we use the hardcoded default. If it's been 391 * more than this long since the last fstrim, we force one during the boot sequence. 392 * 393 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 394 * one gets run at the next available charging+idle time. This final mandatory 395 * no-fstrim check kicks in only of the other scheduling criteria is never met. 396 */ 397 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 398 399 /** 400 * Whether verification is enabled by default. 401 */ 402 private static final boolean DEFAULT_VERIFY_ENABLE = true; 403 404 /** 405 * The default maximum time to wait for the verification agent to return in 406 * milliseconds. 407 */ 408 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 409 410 /** 411 * The default response for package verification timeout. 412 * 413 * This can be either PackageManager.VERIFICATION_ALLOW or 414 * PackageManager.VERIFICATION_REJECT. 415 */ 416 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 417 418 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 419 420 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 421 DEFAULT_CONTAINER_PACKAGE, 422 "com.android.defcontainer.DefaultContainerService"); 423 424 private static final String KILL_APP_REASON_GIDS_CHANGED = 425 "permission grant or revoke changed gids"; 426 427 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 428 "permissions revoked"; 429 430 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 431 432 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 433 434 /** Permission grant: not grant the permission. */ 435 private static final int GRANT_DENIED = 1; 436 437 /** Permission grant: grant the permission as an install permission. */ 438 private static final int GRANT_INSTALL = 2; 439 440 /** Permission grant: grant the permission as a runtime one. */ 441 private static final int GRANT_RUNTIME = 3; 442 443 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 444 private static final int GRANT_UPGRADE = 4; 445 446 /** Canonical intent used to identify what counts as a "web browser" app */ 447 private static final Intent sBrowserIntent; 448 static { 449 sBrowserIntent = new Intent(); 450 sBrowserIntent.setAction(Intent.ACTION_VIEW); 451 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 452 sBrowserIntent.setData(Uri.parse("http:")); 453 } 454 455 /** 456 * The set of all protected actions [i.e. those actions for which a high priority 457 * intent filter is disallowed]. 458 */ 459 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 460 static { 461 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 462 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 463 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 464 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 465 } 466 467 // Compilation reasons. 468 public static final int REASON_FIRST_BOOT = 0; 469 public static final int REASON_BOOT = 1; 470 public static final int REASON_INSTALL = 2; 471 public static final int REASON_BACKGROUND_DEXOPT = 3; 472 public static final int REASON_AB_OTA = 4; 473 public static final int REASON_NON_SYSTEM_LIBRARY = 5; 474 public static final int REASON_SHARED_APK = 6; 475 public static final int REASON_FORCED_DEXOPT = 7; 476 477 public static final int REASON_LAST = REASON_FORCED_DEXOPT; 478 479 final ServiceThread mHandlerThread; 480 481 final PackageHandler mHandler; 482 483 private final ProcessLoggingHandler mProcessLoggingHandler; 484 485 /** 486 * Messages for {@link #mHandler} that need to wait for system ready before 487 * being dispatched. 488 */ 489 private ArrayList<Message> mPostSystemReadyMessages; 490 491 final int mSdkVersion = Build.VERSION.SDK_INT; 492 493 final Context mContext; 494 final boolean mFactoryTest; 495 final boolean mOnlyCore; 496 final DisplayMetrics mMetrics; 497 final int mDefParseFlags; 498 final String[] mSeparateProcesses; 499 final boolean mIsUpgrade; 500 final boolean mIsPreNUpgrade; 501 502 /** The location for ASEC container files on internal storage. */ 503 final String mAsecInternalPath; 504 505 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 506 // LOCK HELD. Can be called with mInstallLock held. 507 @GuardedBy("mInstallLock") 508 final Installer mInstaller; 509 510 /** Directory where installed third-party apps stored */ 511 final File mAppInstallDir; 512 final File mEphemeralInstallDir; 513 514 /** 515 * Directory to which applications installed internally have their 516 * 32 bit native libraries copied. 517 */ 518 private File mAppLib32InstallDir; 519 520 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 521 // apps. 522 final File mDrmAppPrivateInstallDir; 523 524 // ---------------------------------------------------------------- 525 526 // Lock for state used when installing and doing other long running 527 // operations. Methods that must be called with this lock held have 528 // the suffix "LI". 529 final Object mInstallLock = new Object(); 530 531 // ---------------------------------------------------------------- 532 533 // Keys are String (package name), values are Package. This also serves 534 // as the lock for the global state. Methods that must be called with 535 // this lock held have the prefix "LP". 536 @GuardedBy("mPackages") 537 final ArrayMap<String, PackageParser.Package> mPackages = 538 new ArrayMap<String, PackageParser.Package>(); 539 540 final ArrayMap<String, Set<String>> mKnownCodebase = 541 new ArrayMap<String, Set<String>>(); 542 543 // Tracks available target package names -> overlay package paths. 544 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 545 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 546 547 /** 548 * Tracks new system packages [received in an OTA] that we expect to 549 * find updated user-installed versions. Keys are package name, values 550 * are package location. 551 */ 552 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 553 /** 554 * Tracks high priority intent filters for protected actions. During boot, certain 555 * filter actions are protected and should never be allowed to have a high priority 556 * intent filter for them. However, there is one, and only one exception -- the 557 * setup wizard. It must be able to define a high priority intent filter for these 558 * actions to ensure there are no escapes from the wizard. We need to delay processing 559 * of these during boot as we need to look at all of the system packages in order 560 * to know which component is the setup wizard. 561 */ 562 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 563 /** 564 * Whether or not processing protected filters should be deferred. 565 */ 566 private boolean mDeferProtectedFilters = true; 567 568 /** 569 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 570 */ 571 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 572 /** 573 * Whether or not system app permissions should be promoted from install to runtime. 574 */ 575 boolean mPromoteSystemApps; 576 577 final Settings mSettings; 578 boolean mRestoredSettings; 579 580 // System configuration read by SystemConfig. 581 final int[] mGlobalGids; 582 final SparseArray<ArraySet<String>> mSystemPermissions; 583 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 584 585 // If mac_permissions.xml was found for seinfo labeling. 586 boolean mFoundPolicyFile; 587 588 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 589 590 public static final class SharedLibraryEntry { 591 public final String path; 592 public final String apk; 593 594 SharedLibraryEntry(String _path, String _apk) { 595 path = _path; 596 apk = _apk; 597 } 598 } 599 600 // Currently known shared libraries. 601 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 602 new ArrayMap<String, SharedLibraryEntry>(); 603 604 // All available activities, for your resolving pleasure. 605 final ActivityIntentResolver mActivities = 606 new ActivityIntentResolver(); 607 608 // All available receivers, for your resolving pleasure. 609 final ActivityIntentResolver mReceivers = 610 new ActivityIntentResolver(); 611 612 // All available services, for your resolving pleasure. 613 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 614 615 // All available providers, for your resolving pleasure. 616 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 617 618 // Mapping from provider base names (first directory in content URI codePath) 619 // to the provider information. 620 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 621 new ArrayMap<String, PackageParser.Provider>(); 622 623 // Mapping from instrumentation class names to info about them. 624 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 625 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 626 627 // Mapping from permission names to info about them. 628 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 629 new ArrayMap<String, PackageParser.PermissionGroup>(); 630 631 // Packages whose data we have transfered into another package, thus 632 // should no longer exist. 633 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 634 635 // Broadcast actions that are only available to the system. 636 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 637 638 /** List of packages waiting for verification. */ 639 final SparseArray<PackageVerificationState> mPendingVerification 640 = new SparseArray<PackageVerificationState>(); 641 642 /** Set of packages associated with each app op permission. */ 643 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 644 645 final PackageInstallerService mInstallerService; 646 647 private final PackageDexOptimizer mPackageDexOptimizer; 648 649 private AtomicInteger mNextMoveId = new AtomicInteger(); 650 private final MoveCallbacks mMoveCallbacks; 651 652 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 653 654 // Cache of users who need badging. 655 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 656 657 /** Token for keys in mPendingVerification. */ 658 private int mPendingVerificationToken = 0; 659 660 volatile boolean mSystemReady; 661 volatile boolean mSafeMode; 662 volatile boolean mHasSystemUidErrors; 663 664 ApplicationInfo mAndroidApplication; 665 final ActivityInfo mResolveActivity = new ActivityInfo(); 666 final ResolveInfo mResolveInfo = new ResolveInfo(); 667 ComponentName mResolveComponentName; 668 PackageParser.Package mPlatformPackage; 669 ComponentName mCustomResolverComponentName; 670 671 boolean mResolverReplaced = false; 672 673 private final @Nullable ComponentName mIntentFilterVerifierComponent; 674 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 675 676 private int mIntentFilterVerificationToken = 0; 677 678 /** Component that knows whether or not an ephemeral application exists */ 679 final ComponentName mEphemeralResolverComponent; 680 /** The service connection to the ephemeral resolver */ 681 final EphemeralResolverConnection mEphemeralResolverConnection; 682 683 /** Component used to install ephemeral applications */ 684 final ComponentName mEphemeralInstallerComponent; 685 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 686 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 687 688 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 689 = new SparseArray<IntentFilterVerificationState>(); 690 691 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 692 new DefaultPermissionGrantPolicy(this); 693 694 // List of packages names to keep cached, even if they are uninstalled for all users 695 private List<String> mKeepUninstalledPackages; 696 697 private static class IFVerificationParams { 698 PackageParser.Package pkg; 699 boolean replacing; 700 int userId; 701 int verifierUid; 702 703 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 704 int _userId, int _verifierUid) { 705 pkg = _pkg; 706 replacing = _replacing; 707 userId = _userId; 708 replacing = _replacing; 709 verifierUid = _verifierUid; 710 } 711 } 712 713 private interface IntentFilterVerifier<T extends IntentFilter> { 714 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 715 T filter, String packageName); 716 void startVerifications(int userId); 717 void receiveVerificationResponse(int verificationId); 718 } 719 720 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 721 private Context mContext; 722 private ComponentName mIntentFilterVerifierComponent; 723 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 724 725 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 726 mContext = context; 727 mIntentFilterVerifierComponent = verifierComponent; 728 } 729 730 private String getDefaultScheme() { 731 return IntentFilter.SCHEME_HTTPS; 732 } 733 734 @Override 735 public void startVerifications(int userId) { 736 // Launch verifications requests 737 int count = mCurrentIntentFilterVerifications.size(); 738 for (int n=0; n<count; n++) { 739 int verificationId = mCurrentIntentFilterVerifications.get(n); 740 final IntentFilterVerificationState ivs = 741 mIntentFilterVerificationStates.get(verificationId); 742 743 String packageName = ivs.getPackageName(); 744 745 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 746 final int filterCount = filters.size(); 747 ArraySet<String> domainsSet = new ArraySet<>(); 748 for (int m=0; m<filterCount; m++) { 749 PackageParser.ActivityIntentInfo filter = filters.get(m); 750 domainsSet.addAll(filter.getHostsList()); 751 } 752 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 753 synchronized (mPackages) { 754 if (mSettings.createIntentFilterVerificationIfNeededLPw( 755 packageName, domainsList) != null) { 756 scheduleWriteSettingsLocked(); 757 } 758 } 759 sendVerificationRequest(userId, verificationId, ivs); 760 } 761 mCurrentIntentFilterVerifications.clear(); 762 } 763 764 private void sendVerificationRequest(int userId, int verificationId, 765 IntentFilterVerificationState ivs) { 766 767 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 768 verificationIntent.putExtra( 769 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 770 verificationId); 771 verificationIntent.putExtra( 772 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 773 getDefaultScheme()); 774 verificationIntent.putExtra( 775 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 776 ivs.getHostsString()); 777 verificationIntent.putExtra( 778 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 779 ivs.getPackageName()); 780 verificationIntent.setComponent(mIntentFilterVerifierComponent); 781 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 782 783 UserHandle user = new UserHandle(userId); 784 mContext.sendBroadcastAsUser(verificationIntent, user); 785 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 786 "Sending IntentFilter verification broadcast"); 787 } 788 789 public void receiveVerificationResponse(int verificationId) { 790 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 791 792 final boolean verified = ivs.isVerified(); 793 794 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 795 final int count = filters.size(); 796 if (DEBUG_DOMAIN_VERIFICATION) { 797 Slog.i(TAG, "Received verification response " + verificationId 798 + " for " + count + " filters, verified=" + verified); 799 } 800 for (int n=0; n<count; n++) { 801 PackageParser.ActivityIntentInfo filter = filters.get(n); 802 filter.setVerified(verified); 803 804 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 805 + " verified with result:" + verified + " and hosts:" 806 + ivs.getHostsString()); 807 } 808 809 mIntentFilterVerificationStates.remove(verificationId); 810 811 final String packageName = ivs.getPackageName(); 812 IntentFilterVerificationInfo ivi = null; 813 814 synchronized (mPackages) { 815 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 816 } 817 if (ivi == null) { 818 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 819 + verificationId + " packageName:" + packageName); 820 return; 821 } 822 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 823 "Updating IntentFilterVerificationInfo for package " + packageName 824 +" verificationId:" + verificationId); 825 826 synchronized (mPackages) { 827 if (verified) { 828 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 829 } else { 830 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 831 } 832 scheduleWriteSettingsLocked(); 833 834 final int userId = ivs.getUserId(); 835 if (userId != UserHandle.USER_ALL) { 836 final int userStatus = 837 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 838 839 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 840 boolean needUpdate = false; 841 842 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 843 // already been set by the User thru the Disambiguation dialog 844 switch (userStatus) { 845 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 846 if (verified) { 847 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 848 } else { 849 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 850 } 851 needUpdate = true; 852 break; 853 854 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 855 if (verified) { 856 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 857 needUpdate = true; 858 } 859 break; 860 861 default: 862 // Nothing to do 863 } 864 865 if (needUpdate) { 866 mSettings.updateIntentFilterVerificationStatusLPw( 867 packageName, updatedStatus, userId); 868 scheduleWritePackageRestrictionsLocked(userId); 869 } 870 } 871 } 872 } 873 874 @Override 875 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 876 ActivityIntentInfo filter, String packageName) { 877 if (!hasValidDomains(filter)) { 878 return false; 879 } 880 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 881 if (ivs == null) { 882 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 883 packageName); 884 } 885 if (DEBUG_DOMAIN_VERIFICATION) { 886 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 887 } 888 ivs.addFilter(filter); 889 return true; 890 } 891 892 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 893 int userId, int verificationId, String packageName) { 894 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 895 verifierUid, userId, packageName); 896 ivs.setPendingState(); 897 synchronized (mPackages) { 898 mIntentFilterVerificationStates.append(verificationId, ivs); 899 mCurrentIntentFilterVerifications.add(verificationId); 900 } 901 return ivs; 902 } 903 } 904 905 private static boolean hasValidDomains(ActivityIntentInfo filter) { 906 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 907 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 908 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 909 } 910 911 // Set of pending broadcasts for aggregating enable/disable of components. 912 static class PendingPackageBroadcasts { 913 // for each user id, a map of <package name -> components within that package> 914 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 915 916 public PendingPackageBroadcasts() { 917 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 918 } 919 920 public ArrayList<String> get(int userId, String packageName) { 921 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 922 return packages.get(packageName); 923 } 924 925 public void put(int userId, String packageName, ArrayList<String> components) { 926 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 927 packages.put(packageName, components); 928 } 929 930 public void remove(int userId, String packageName) { 931 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 932 if (packages != null) { 933 packages.remove(packageName); 934 } 935 } 936 937 public void remove(int userId) { 938 mUidMap.remove(userId); 939 } 940 941 public int userIdCount() { 942 return mUidMap.size(); 943 } 944 945 public int userIdAt(int n) { 946 return mUidMap.keyAt(n); 947 } 948 949 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 950 return mUidMap.get(userId); 951 } 952 953 public int size() { 954 // total number of pending broadcast entries across all userIds 955 int num = 0; 956 for (int i = 0; i< mUidMap.size(); i++) { 957 num += mUidMap.valueAt(i).size(); 958 } 959 return num; 960 } 961 962 public void clear() { 963 mUidMap.clear(); 964 } 965 966 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 967 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 968 if (map == null) { 969 map = new ArrayMap<String, ArrayList<String>>(); 970 mUidMap.put(userId, map); 971 } 972 return map; 973 } 974 } 975 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 976 977 // Service Connection to remote media container service to copy 978 // package uri's from external media onto secure containers 979 // or internal storage. 980 private IMediaContainerService mContainerService = null; 981 982 static final int SEND_PENDING_BROADCAST = 1; 983 static final int MCS_BOUND = 3; 984 static final int END_COPY = 4; 985 static final int INIT_COPY = 5; 986 static final int MCS_UNBIND = 6; 987 static final int START_CLEANING_PACKAGE = 7; 988 static final int FIND_INSTALL_LOC = 8; 989 static final int POST_INSTALL = 9; 990 static final int MCS_RECONNECT = 10; 991 static final int MCS_GIVE_UP = 11; 992 static final int UPDATED_MEDIA_STATUS = 12; 993 static final int WRITE_SETTINGS = 13; 994 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 995 static final int PACKAGE_VERIFIED = 15; 996 static final int CHECK_PENDING_VERIFICATION = 16; 997 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 998 static final int INTENT_FILTER_VERIFIED = 18; 999 1000 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1001 1002 // Delay time in millisecs 1003 static final int BROADCAST_DELAY = 10 * 1000; 1004 1005 static UserManagerService sUserManager; 1006 1007 // Stores a list of users whose package restrictions file needs to be updated 1008 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1009 1010 final private DefaultContainerConnection mDefContainerConn = 1011 new DefaultContainerConnection(); 1012 class DefaultContainerConnection implements ServiceConnection { 1013 public void onServiceConnected(ComponentName name, IBinder service) { 1014 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1015 IMediaContainerService imcs = 1016 IMediaContainerService.Stub.asInterface(service); 1017 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1018 } 1019 1020 public void onServiceDisconnected(ComponentName name) { 1021 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1022 } 1023 } 1024 1025 // Recordkeeping of restore-after-install operations that are currently in flight 1026 // between the Package Manager and the Backup Manager 1027 static class PostInstallData { 1028 public InstallArgs args; 1029 public PackageInstalledInfo res; 1030 1031 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1032 args = _a; 1033 res = _r; 1034 } 1035 } 1036 1037 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1038 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1039 1040 // XML tags for backup/restore of various bits of state 1041 private static final String TAG_PREFERRED_BACKUP = "pa"; 1042 private static final String TAG_DEFAULT_APPS = "da"; 1043 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1044 1045 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1046 private static final String TAG_ALL_GRANTS = "rt-grants"; 1047 private static final String TAG_GRANT = "grant"; 1048 private static final String ATTR_PACKAGE_NAME = "pkg"; 1049 1050 private static final String TAG_PERMISSION = "perm"; 1051 private static final String ATTR_PERMISSION_NAME = "name"; 1052 private static final String ATTR_IS_GRANTED = "g"; 1053 private static final String ATTR_USER_SET = "set"; 1054 private static final String ATTR_USER_FIXED = "fixed"; 1055 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1056 1057 // System/policy permission grants are not backed up 1058 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1059 FLAG_PERMISSION_POLICY_FIXED 1060 | FLAG_PERMISSION_SYSTEM_FIXED 1061 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1062 1063 // And we back up these user-adjusted states 1064 private static final int USER_RUNTIME_GRANT_MASK = 1065 FLAG_PERMISSION_USER_SET 1066 | FLAG_PERMISSION_USER_FIXED 1067 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1068 1069 final @Nullable String mRequiredVerifierPackage; 1070 final @Nullable String mRequiredInstallerPackage; 1071 final @Nullable String mSetupWizardPackage; 1072 1073 private final PackageUsage mPackageUsage = new PackageUsage(); 1074 1075 private class PackageUsage { 1076 private static final int WRITE_INTERVAL 1077 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 1078 1079 private final Object mFileLock = new Object(); 1080 private final AtomicLong mLastWritten = new AtomicLong(0); 1081 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 1082 1083 private boolean mIsHistoricalPackageUsageAvailable = true; 1084 1085 boolean isHistoricalPackageUsageAvailable() { 1086 return mIsHistoricalPackageUsageAvailable; 1087 } 1088 1089 void write(boolean force) { 1090 if (force) { 1091 writeInternal(); 1092 return; 1093 } 1094 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 1095 && !DEBUG_DEXOPT) { 1096 return; 1097 } 1098 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 1099 new Thread("PackageUsage_DiskWriter") { 1100 @Override 1101 public void run() { 1102 try { 1103 writeInternal(); 1104 } finally { 1105 mBackgroundWriteRunning.set(false); 1106 } 1107 } 1108 }.start(); 1109 } 1110 } 1111 1112 private void writeInternal() { 1113 synchronized (mPackages) { 1114 synchronized (mFileLock) { 1115 AtomicFile file = getFile(); 1116 FileOutputStream f = null; 1117 try { 1118 f = file.startWrite(); 1119 BufferedOutputStream out = new BufferedOutputStream(f); 1120 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1121 StringBuilder sb = new StringBuilder(); 1122 for (PackageParser.Package pkg : mPackages.values()) { 1123 if (pkg.mLastPackageUsageTimeInMills == 0) { 1124 continue; 1125 } 1126 sb.setLength(0); 1127 sb.append(pkg.packageName); 1128 sb.append(' '); 1129 sb.append((long)pkg.mLastPackageUsageTimeInMills); 1130 sb.append('\n'); 1131 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1132 } 1133 out.flush(); 1134 file.finishWrite(f); 1135 } catch (IOException e) { 1136 if (f != null) { 1137 file.failWrite(f); 1138 } 1139 Log.e(TAG, "Failed to write package usage times", e); 1140 } 1141 } 1142 } 1143 mLastWritten.set(SystemClock.elapsedRealtime()); 1144 } 1145 1146 void readLP() { 1147 synchronized (mFileLock) { 1148 AtomicFile file = getFile(); 1149 BufferedInputStream in = null; 1150 try { 1151 in = new BufferedInputStream(file.openRead()); 1152 StringBuffer sb = new StringBuffer(); 1153 while (true) { 1154 String packageName = readToken(in, sb, ' '); 1155 if (packageName == null) { 1156 break; 1157 } 1158 String timeInMillisString = readToken(in, sb, '\n'); 1159 if (timeInMillisString == null) { 1160 throw new IOException("Failed to find last usage time for package " 1161 + packageName); 1162 } 1163 PackageParser.Package pkg = mPackages.get(packageName); 1164 if (pkg == null) { 1165 continue; 1166 } 1167 long timeInMillis; 1168 try { 1169 timeInMillis = Long.parseLong(timeInMillisString); 1170 } catch (NumberFormatException e) { 1171 throw new IOException("Failed to parse " + timeInMillisString 1172 + " as a long.", e); 1173 } 1174 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1175 } 1176 } catch (FileNotFoundException expected) { 1177 mIsHistoricalPackageUsageAvailable = false; 1178 } catch (IOException e) { 1179 Log.w(TAG, "Failed to read package usage times", e); 1180 } finally { 1181 IoUtils.closeQuietly(in); 1182 } 1183 } 1184 mLastWritten.set(SystemClock.elapsedRealtime()); 1185 } 1186 1187 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1188 throws IOException { 1189 sb.setLength(0); 1190 while (true) { 1191 int ch = in.read(); 1192 if (ch == -1) { 1193 if (sb.length() == 0) { 1194 return null; 1195 } 1196 throw new IOException("Unexpected EOF"); 1197 } 1198 if (ch == endOfToken) { 1199 return sb.toString(); 1200 } 1201 sb.append((char)ch); 1202 } 1203 } 1204 1205 private AtomicFile getFile() { 1206 File dataDir = Environment.getDataDirectory(); 1207 File systemDir = new File(dataDir, "system"); 1208 File fname = new File(systemDir, "package-usage.list"); 1209 return new AtomicFile(fname); 1210 } 1211 } 1212 1213 class PackageHandler extends Handler { 1214 private boolean mBound = false; 1215 final ArrayList<HandlerParams> mPendingInstalls = 1216 new ArrayList<HandlerParams>(); 1217 1218 private boolean connectToService() { 1219 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1220 " DefaultContainerService"); 1221 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1222 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1223 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1224 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1225 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1226 mBound = true; 1227 return true; 1228 } 1229 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1230 return false; 1231 } 1232 1233 private void disconnectService() { 1234 mContainerService = null; 1235 mBound = false; 1236 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1237 mContext.unbindService(mDefContainerConn); 1238 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1239 } 1240 1241 PackageHandler(Looper looper) { 1242 super(looper); 1243 } 1244 1245 public void handleMessage(Message msg) { 1246 try { 1247 doHandleMessage(msg); 1248 } finally { 1249 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1250 } 1251 } 1252 1253 void doHandleMessage(Message msg) { 1254 switch (msg.what) { 1255 case INIT_COPY: { 1256 HandlerParams params = (HandlerParams) msg.obj; 1257 int idx = mPendingInstalls.size(); 1258 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1259 // If a bind was already initiated we dont really 1260 // need to do anything. The pending install 1261 // will be processed later on. 1262 if (!mBound) { 1263 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1264 System.identityHashCode(mHandler)); 1265 // If this is the only one pending we might 1266 // have to bind to the service again. 1267 if (!connectToService()) { 1268 Slog.e(TAG, "Failed to bind to media container service"); 1269 params.serviceError(); 1270 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1271 System.identityHashCode(mHandler)); 1272 if (params.traceMethod != null) { 1273 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1274 params.traceCookie); 1275 } 1276 return; 1277 } else { 1278 // Once we bind to the service, the first 1279 // pending request will be processed. 1280 mPendingInstalls.add(idx, params); 1281 } 1282 } else { 1283 mPendingInstalls.add(idx, params); 1284 // Already bound to the service. Just make 1285 // sure we trigger off processing the first request. 1286 if (idx == 0) { 1287 mHandler.sendEmptyMessage(MCS_BOUND); 1288 } 1289 } 1290 break; 1291 } 1292 case MCS_BOUND: { 1293 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1294 if (msg.obj != null) { 1295 mContainerService = (IMediaContainerService) msg.obj; 1296 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1297 System.identityHashCode(mHandler)); 1298 } 1299 if (mContainerService == null) { 1300 if (!mBound) { 1301 // Something seriously wrong since we are not bound and we are not 1302 // waiting for connection. Bail out. 1303 Slog.e(TAG, "Cannot bind to media container service"); 1304 for (HandlerParams params : mPendingInstalls) { 1305 // Indicate service bind error 1306 params.serviceError(); 1307 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1308 System.identityHashCode(params)); 1309 if (params.traceMethod != null) { 1310 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1311 params.traceMethod, params.traceCookie); 1312 } 1313 return; 1314 } 1315 mPendingInstalls.clear(); 1316 } else { 1317 Slog.w(TAG, "Waiting to connect to media container service"); 1318 } 1319 } else if (mPendingInstalls.size() > 0) { 1320 HandlerParams params = mPendingInstalls.get(0); 1321 if (params != null) { 1322 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1323 System.identityHashCode(params)); 1324 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1325 if (params.startCopy()) { 1326 // We are done... look for more work or to 1327 // go idle. 1328 if (DEBUG_SD_INSTALL) Log.i(TAG, 1329 "Checking for more work or unbind..."); 1330 // Delete pending install 1331 if (mPendingInstalls.size() > 0) { 1332 mPendingInstalls.remove(0); 1333 } 1334 if (mPendingInstalls.size() == 0) { 1335 if (mBound) { 1336 if (DEBUG_SD_INSTALL) Log.i(TAG, 1337 "Posting delayed MCS_UNBIND"); 1338 removeMessages(MCS_UNBIND); 1339 Message ubmsg = obtainMessage(MCS_UNBIND); 1340 // Unbind after a little delay, to avoid 1341 // continual thrashing. 1342 sendMessageDelayed(ubmsg, 10000); 1343 } 1344 } else { 1345 // There are more pending requests in queue. 1346 // Just post MCS_BOUND message to trigger processing 1347 // of next pending install. 1348 if (DEBUG_SD_INSTALL) Log.i(TAG, 1349 "Posting MCS_BOUND for next work"); 1350 mHandler.sendEmptyMessage(MCS_BOUND); 1351 } 1352 } 1353 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1354 } 1355 } else { 1356 // Should never happen ideally. 1357 Slog.w(TAG, "Empty queue"); 1358 } 1359 break; 1360 } 1361 case MCS_RECONNECT: { 1362 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1363 if (mPendingInstalls.size() > 0) { 1364 if (mBound) { 1365 disconnectService(); 1366 } 1367 if (!connectToService()) { 1368 Slog.e(TAG, "Failed to bind to media container service"); 1369 for (HandlerParams params : mPendingInstalls) { 1370 // Indicate service bind error 1371 params.serviceError(); 1372 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1373 System.identityHashCode(params)); 1374 } 1375 mPendingInstalls.clear(); 1376 } 1377 } 1378 break; 1379 } 1380 case MCS_UNBIND: { 1381 // If there is no actual work left, then time to unbind. 1382 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1383 1384 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1385 if (mBound) { 1386 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1387 1388 disconnectService(); 1389 } 1390 } else if (mPendingInstalls.size() > 0) { 1391 // There are more pending requests in queue. 1392 // Just post MCS_BOUND message to trigger processing 1393 // of next pending install. 1394 mHandler.sendEmptyMessage(MCS_BOUND); 1395 } 1396 1397 break; 1398 } 1399 case MCS_GIVE_UP: { 1400 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1401 HandlerParams params = mPendingInstalls.remove(0); 1402 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1403 System.identityHashCode(params)); 1404 break; 1405 } 1406 case SEND_PENDING_BROADCAST: { 1407 String packages[]; 1408 ArrayList<String> components[]; 1409 int size = 0; 1410 int uids[]; 1411 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1412 synchronized (mPackages) { 1413 if (mPendingBroadcasts == null) { 1414 return; 1415 } 1416 size = mPendingBroadcasts.size(); 1417 if (size <= 0) { 1418 // Nothing to be done. Just return 1419 return; 1420 } 1421 packages = new String[size]; 1422 components = new ArrayList[size]; 1423 uids = new int[size]; 1424 int i = 0; // filling out the above arrays 1425 1426 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1427 int packageUserId = mPendingBroadcasts.userIdAt(n); 1428 Iterator<Map.Entry<String, ArrayList<String>>> it 1429 = mPendingBroadcasts.packagesForUserId(packageUserId) 1430 .entrySet().iterator(); 1431 while (it.hasNext() && i < size) { 1432 Map.Entry<String, ArrayList<String>> ent = it.next(); 1433 packages[i] = ent.getKey(); 1434 components[i] = ent.getValue(); 1435 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1436 uids[i] = (ps != null) 1437 ? UserHandle.getUid(packageUserId, ps.appId) 1438 : -1; 1439 i++; 1440 } 1441 } 1442 size = i; 1443 mPendingBroadcasts.clear(); 1444 } 1445 // Send broadcasts 1446 for (int i = 0; i < size; i++) { 1447 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1448 } 1449 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1450 break; 1451 } 1452 case START_CLEANING_PACKAGE: { 1453 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1454 final String packageName = (String)msg.obj; 1455 final int userId = msg.arg1; 1456 final boolean andCode = msg.arg2 != 0; 1457 synchronized (mPackages) { 1458 if (userId == UserHandle.USER_ALL) { 1459 int[] users = sUserManager.getUserIds(); 1460 for (int user : users) { 1461 mSettings.addPackageToCleanLPw( 1462 new PackageCleanItem(user, packageName, andCode)); 1463 } 1464 } else { 1465 mSettings.addPackageToCleanLPw( 1466 new PackageCleanItem(userId, packageName, andCode)); 1467 } 1468 } 1469 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1470 startCleaningPackages(); 1471 } break; 1472 case POST_INSTALL: { 1473 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1474 1475 PostInstallData data = mRunningInstalls.get(msg.arg1); 1476 mRunningInstalls.delete(msg.arg1); 1477 1478 if (data != null) { 1479 InstallArgs args = data.args; 1480 PackageInstalledInfo parentRes = data.res; 1481 1482 final boolean grantPermissions = (args.installFlags 1483 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1484 final boolean killApp = (args.installFlags 1485 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1486 final String[] grantedPermissions = args.installGrantPermissions; 1487 1488 // Handle the parent package 1489 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1490 grantedPermissions, args.observer); 1491 1492 // Handle the child packages 1493 final int childCount = (parentRes.addedChildPackages != null) 1494 ? parentRes.addedChildPackages.size() : 0; 1495 for (int i = 0; i < childCount; i++) { 1496 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1497 handlePackagePostInstall(childRes, grantPermissions, killApp, 1498 grantedPermissions, args.observer); 1499 } 1500 1501 // Log tracing if needed 1502 if (args.traceMethod != null) { 1503 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1504 args.traceCookie); 1505 } 1506 } else { 1507 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1508 } 1509 1510 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1511 } break; 1512 case UPDATED_MEDIA_STATUS: { 1513 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1514 boolean reportStatus = msg.arg1 == 1; 1515 boolean doGc = msg.arg2 == 1; 1516 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1517 if (doGc) { 1518 // Force a gc to clear up stale containers. 1519 Runtime.getRuntime().gc(); 1520 } 1521 if (msg.obj != null) { 1522 @SuppressWarnings("unchecked") 1523 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1524 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1525 // Unload containers 1526 unloadAllContainers(args); 1527 } 1528 if (reportStatus) { 1529 try { 1530 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1531 PackageHelper.getMountService().finishMediaUpdate(); 1532 } catch (RemoteException e) { 1533 Log.e(TAG, "MountService not running?"); 1534 } 1535 } 1536 } break; 1537 case WRITE_SETTINGS: { 1538 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1539 synchronized (mPackages) { 1540 removeMessages(WRITE_SETTINGS); 1541 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1542 mSettings.writeLPr(); 1543 mDirtyUsers.clear(); 1544 } 1545 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1546 } break; 1547 case WRITE_PACKAGE_RESTRICTIONS: { 1548 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1549 synchronized (mPackages) { 1550 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1551 for (int userId : mDirtyUsers) { 1552 mSettings.writePackageRestrictionsLPr(userId); 1553 } 1554 mDirtyUsers.clear(); 1555 } 1556 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1557 } break; 1558 case CHECK_PENDING_VERIFICATION: { 1559 final int verificationId = msg.arg1; 1560 final PackageVerificationState state = mPendingVerification.get(verificationId); 1561 1562 if ((state != null) && !state.timeoutExtended()) { 1563 final InstallArgs args = state.getInstallArgs(); 1564 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1565 1566 Slog.i(TAG, "Verification timed out for " + originUri); 1567 mPendingVerification.remove(verificationId); 1568 1569 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1570 1571 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1572 Slog.i(TAG, "Continuing with installation of " + originUri); 1573 state.setVerifierResponse(Binder.getCallingUid(), 1574 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1575 broadcastPackageVerified(verificationId, originUri, 1576 PackageManager.VERIFICATION_ALLOW, 1577 state.getInstallArgs().getUser()); 1578 try { 1579 ret = args.copyApk(mContainerService, true); 1580 } catch (RemoteException e) { 1581 Slog.e(TAG, "Could not contact the ContainerService"); 1582 } 1583 } else { 1584 broadcastPackageVerified(verificationId, originUri, 1585 PackageManager.VERIFICATION_REJECT, 1586 state.getInstallArgs().getUser()); 1587 } 1588 1589 Trace.asyncTraceEnd( 1590 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1591 1592 processPendingInstall(args, ret); 1593 mHandler.sendEmptyMessage(MCS_UNBIND); 1594 } 1595 break; 1596 } 1597 case PACKAGE_VERIFIED: { 1598 final int verificationId = msg.arg1; 1599 1600 final PackageVerificationState state = mPendingVerification.get(verificationId); 1601 if (state == null) { 1602 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1603 break; 1604 } 1605 1606 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1607 1608 state.setVerifierResponse(response.callerUid, response.code); 1609 1610 if (state.isVerificationComplete()) { 1611 mPendingVerification.remove(verificationId); 1612 1613 final InstallArgs args = state.getInstallArgs(); 1614 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1615 1616 int ret; 1617 if (state.isInstallAllowed()) { 1618 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1619 broadcastPackageVerified(verificationId, originUri, 1620 response.code, state.getInstallArgs().getUser()); 1621 try { 1622 ret = args.copyApk(mContainerService, true); 1623 } catch (RemoteException e) { 1624 Slog.e(TAG, "Could not contact the ContainerService"); 1625 } 1626 } else { 1627 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1628 } 1629 1630 Trace.asyncTraceEnd( 1631 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1632 1633 processPendingInstall(args, ret); 1634 mHandler.sendEmptyMessage(MCS_UNBIND); 1635 } 1636 1637 break; 1638 } 1639 case START_INTENT_FILTER_VERIFICATIONS: { 1640 IFVerificationParams params = (IFVerificationParams) msg.obj; 1641 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1642 params.replacing, params.pkg); 1643 break; 1644 } 1645 case INTENT_FILTER_VERIFIED: { 1646 final int verificationId = msg.arg1; 1647 1648 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1649 verificationId); 1650 if (state == null) { 1651 Slog.w(TAG, "Invalid IntentFilter verification token " 1652 + verificationId + " received"); 1653 break; 1654 } 1655 1656 final int userId = state.getUserId(); 1657 1658 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1659 "Processing IntentFilter verification with token:" 1660 + verificationId + " and userId:" + userId); 1661 1662 final IntentFilterVerificationResponse response = 1663 (IntentFilterVerificationResponse) msg.obj; 1664 1665 state.setVerifierResponse(response.callerUid, response.code); 1666 1667 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1668 "IntentFilter verification with token:" + verificationId 1669 + " and userId:" + userId 1670 + " is settings verifier response with response code:" 1671 + response.code); 1672 1673 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1674 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1675 + response.getFailedDomainsString()); 1676 } 1677 1678 if (state.isVerificationComplete()) { 1679 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1680 } else { 1681 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1682 "IntentFilter verification with token:" + verificationId 1683 + " was not said to be complete"); 1684 } 1685 1686 break; 1687 } 1688 } 1689 } 1690 } 1691 1692 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1693 boolean killApp, String[] grantedPermissions, 1694 IPackageInstallObserver2 installObserver) { 1695 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1696 // Send the removed broadcasts 1697 if (res.removedInfo != null) { 1698 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1699 } 1700 1701 // Now that we successfully installed the package, grant runtime 1702 // permissions if requested before broadcasting the install. 1703 if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion 1704 >= Build.VERSION_CODES.M) { 1705 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1706 } 1707 1708 final boolean update = res.removedInfo != null 1709 && res.removedInfo.removedPackage != null; 1710 1711 // If this is the first time we have child packages for a disabled privileged 1712 // app that had no children, we grant requested runtime permissions to the new 1713 // children if the parent on the system image had them already granted. 1714 if (res.pkg.parentPackage != null) { 1715 synchronized (mPackages) { 1716 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1717 } 1718 } 1719 1720 synchronized (mPackages) { 1721 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1722 } 1723 1724 final String packageName = res.pkg.applicationInfo.packageName; 1725 Bundle extras = new Bundle(1); 1726 extras.putInt(Intent.EXTRA_UID, res.uid); 1727 1728 // Determine the set of users who are adding this package for 1729 // the first time vs. those who are seeing an update. 1730 int[] firstUsers = EMPTY_INT_ARRAY; 1731 int[] updateUsers = EMPTY_INT_ARRAY; 1732 if (res.origUsers == null || res.origUsers.length == 0) { 1733 firstUsers = res.newUsers; 1734 } else { 1735 for (int newUser : res.newUsers) { 1736 boolean isNew = true; 1737 for (int origUser : res.origUsers) { 1738 if (origUser == newUser) { 1739 isNew = false; 1740 break; 1741 } 1742 } 1743 if (isNew) { 1744 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1745 } else { 1746 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1747 } 1748 } 1749 } 1750 1751 // Send installed broadcasts if the install/update is not ephemeral 1752 if (!isEphemeral(res.pkg)) { 1753 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1754 1755 // Send added for users that see the package for the first time 1756 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1757 extras, 0 /*flags*/, null /*targetPackage*/, 1758 null /*finishedReceiver*/, firstUsers); 1759 1760 // Send added for users that don't see the package for the first time 1761 if (update) { 1762 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1763 } 1764 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1765 extras, 0 /*flags*/, null /*targetPackage*/, 1766 null /*finishedReceiver*/, updateUsers); 1767 1768 // Send replaced for users that don't see the package for the first time 1769 if (update) { 1770 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1771 packageName, extras, 0 /*flags*/, 1772 null /*targetPackage*/, null /*finishedReceiver*/, 1773 updateUsers); 1774 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1775 null /*package*/, null /*extras*/, 0 /*flags*/, 1776 packageName /*targetPackage*/, 1777 null /*finishedReceiver*/, updateUsers); 1778 } 1779 1780 // Send broadcast package appeared if forward locked/external for all users 1781 // treat asec-hosted packages like removable media on upgrade 1782 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1783 if (DEBUG_INSTALL) { 1784 Slog.i(TAG, "upgrading pkg " + res.pkg 1785 + " is ASEC-hosted -> AVAILABLE"); 1786 } 1787 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1788 ArrayList<String> pkgList = new ArrayList<>(1); 1789 pkgList.add(packageName); 1790 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1791 } 1792 } 1793 1794 // Work that needs to happen on first install within each user 1795 if (firstUsers != null && firstUsers.length > 0) { 1796 synchronized (mPackages) { 1797 for (int userId : firstUsers) { 1798 // If this app is a browser and it's newly-installed for some 1799 // users, clear any default-browser state in those users. The 1800 // app's nature doesn't depend on the user, so we can just check 1801 // its browser nature in any user and generalize. 1802 if (packageIsBrowser(packageName, userId)) { 1803 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1804 } 1805 1806 // We may also need to apply pending (restored) runtime 1807 // permission grants within these users. 1808 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1809 } 1810 } 1811 } 1812 1813 // Log current value of "unknown sources" setting 1814 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1815 getUnknownSourcesSettings()); 1816 1817 // Force a gc to clear up things 1818 Runtime.getRuntime().gc(); 1819 1820 // Remove the replaced package's older resources safely now 1821 // We delete after a gc for applications on sdcard. 1822 if (res.removedInfo != null && res.removedInfo.args != null) { 1823 synchronized (mInstallLock) { 1824 res.removedInfo.args.doPostDeleteLI(true); 1825 } 1826 } 1827 } 1828 1829 // If someone is watching installs - notify them 1830 if (installObserver != null) { 1831 try { 1832 Bundle extras = extrasForInstallResult(res); 1833 installObserver.onPackageInstalled(res.name, res.returnCode, 1834 res.returnMsg, extras); 1835 } catch (RemoteException e) { 1836 Slog.i(TAG, "Observer no longer exists."); 1837 } 1838 } 1839 } 1840 1841 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1842 PackageParser.Package pkg) { 1843 if (pkg.parentPackage == null) { 1844 return; 1845 } 1846 if (pkg.requestedPermissions == null) { 1847 return; 1848 } 1849 final PackageSetting disabledSysParentPs = mSettings 1850 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1851 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1852 || !disabledSysParentPs.isPrivileged() 1853 || (disabledSysParentPs.childPackageNames != null 1854 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1855 return; 1856 } 1857 final int[] allUserIds = sUserManager.getUserIds(); 1858 final int permCount = pkg.requestedPermissions.size(); 1859 for (int i = 0; i < permCount; i++) { 1860 String permission = pkg.requestedPermissions.get(i); 1861 BasePermission bp = mSettings.mPermissions.get(permission); 1862 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1863 continue; 1864 } 1865 for (int userId : allUserIds) { 1866 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1867 permission, userId)) { 1868 grantRuntimePermission(pkg.packageName, permission, userId); 1869 } 1870 } 1871 } 1872 } 1873 1874 private StorageEventListener mStorageListener = new StorageEventListener() { 1875 @Override 1876 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1877 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1878 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1879 final String volumeUuid = vol.getFsUuid(); 1880 1881 // Clean up any users or apps that were removed or recreated 1882 // while this volume was missing 1883 reconcileUsers(volumeUuid); 1884 reconcileApps(volumeUuid); 1885 1886 // Clean up any install sessions that expired or were 1887 // cancelled while this volume was missing 1888 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1889 1890 loadPrivatePackages(vol); 1891 1892 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1893 unloadPrivatePackages(vol); 1894 } 1895 } 1896 1897 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1898 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1899 updateExternalMediaStatus(true, false); 1900 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1901 updateExternalMediaStatus(false, false); 1902 } 1903 } 1904 } 1905 1906 @Override 1907 public void onVolumeForgotten(String fsUuid) { 1908 if (TextUtils.isEmpty(fsUuid)) { 1909 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1910 return; 1911 } 1912 1913 // Remove any apps installed on the forgotten volume 1914 synchronized (mPackages) { 1915 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1916 for (PackageSetting ps : packages) { 1917 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1918 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1919 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 1920 } 1921 1922 mSettings.onVolumeForgotten(fsUuid); 1923 mSettings.writeLPr(); 1924 } 1925 } 1926 }; 1927 1928 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 1929 String[] grantedPermissions) { 1930 for (int userId : userIds) { 1931 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1932 } 1933 1934 // We could have touched GID membership, so flush out packages.list 1935 synchronized (mPackages) { 1936 mSettings.writePackageListLPr(); 1937 } 1938 } 1939 1940 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1941 String[] grantedPermissions) { 1942 SettingBase sb = (SettingBase) pkg.mExtras; 1943 if (sb == null) { 1944 return; 1945 } 1946 1947 PermissionsState permissionsState = sb.getPermissionsState(); 1948 1949 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 1950 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 1951 1952 synchronized (mPackages) { 1953 for (String permission : pkg.requestedPermissions) { 1954 BasePermission bp = mSettings.mPermissions.get(permission); 1955 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 1956 && (grantedPermissions == null 1957 || ArrayUtils.contains(grantedPermissions, permission))) { 1958 final int flags = permissionsState.getPermissionFlags(permission, userId); 1959 // Installer cannot change immutable permissions. 1960 if ((flags & immutableFlags) == 0) { 1961 grantRuntimePermission(pkg.packageName, permission, userId); 1962 } 1963 } 1964 } 1965 } 1966 } 1967 1968 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1969 Bundle extras = null; 1970 switch (res.returnCode) { 1971 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1972 extras = new Bundle(); 1973 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1974 res.origPermission); 1975 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1976 res.origPackage); 1977 break; 1978 } 1979 case PackageManager.INSTALL_SUCCEEDED: { 1980 extras = new Bundle(); 1981 extras.putBoolean(Intent.EXTRA_REPLACING, 1982 res.removedInfo != null && res.removedInfo.removedPackage != null); 1983 break; 1984 } 1985 } 1986 return extras; 1987 } 1988 1989 void scheduleWriteSettingsLocked() { 1990 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1991 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1992 } 1993 } 1994 1995 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 1996 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 1997 scheduleWritePackageRestrictionsLocked(userId); 1998 } 1999 2000 void scheduleWritePackageRestrictionsLocked(int userId) { 2001 final int[] userIds = (userId == UserHandle.USER_ALL) 2002 ? sUserManager.getUserIds() : new int[]{userId}; 2003 for (int nextUserId : userIds) { 2004 if (!sUserManager.exists(nextUserId)) return; 2005 mDirtyUsers.add(nextUserId); 2006 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2007 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2008 } 2009 } 2010 } 2011 2012 public static PackageManagerService main(Context context, Installer installer, 2013 boolean factoryTest, boolean onlyCore) { 2014 // Self-check for initial settings. 2015 PackageManagerServiceCompilerMapping.checkProperties(); 2016 2017 PackageManagerService m = new PackageManagerService(context, installer, 2018 factoryTest, onlyCore); 2019 m.enableSystemUserPackages(); 2020 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 2021 // disabled after already being started. 2022 CarrierAppUtils.disableCarrierAppsUntilPrivileged(context.getOpPackageName(), m, 2023 UserHandle.USER_SYSTEM); 2024 ServiceManager.addService("package", m); 2025 return m; 2026 } 2027 2028 private void enableSystemUserPackages() { 2029 if (!UserManager.isSplitSystemUser()) { 2030 return; 2031 } 2032 // For system user, enable apps based on the following conditions: 2033 // - app is whitelisted or belong to one of these groups: 2034 // -- system app which has no launcher icons 2035 // -- system app which has INTERACT_ACROSS_USERS permission 2036 // -- system IME app 2037 // - app is not in the blacklist 2038 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2039 Set<String> enableApps = new ArraySet<>(); 2040 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2041 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2042 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2043 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2044 enableApps.addAll(wlApps); 2045 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2046 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2047 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2048 enableApps.removeAll(blApps); 2049 Log.i(TAG, "Applications installed for system user: " + enableApps); 2050 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2051 UserHandle.SYSTEM); 2052 final int allAppsSize = allAps.size(); 2053 synchronized (mPackages) { 2054 for (int i = 0; i < allAppsSize; i++) { 2055 String pName = allAps.get(i); 2056 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2057 // Should not happen, but we shouldn't be failing if it does 2058 if (pkgSetting == null) { 2059 continue; 2060 } 2061 boolean install = enableApps.contains(pName); 2062 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2063 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2064 + " for system user"); 2065 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2066 } 2067 } 2068 } 2069 } 2070 2071 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2072 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2073 Context.DISPLAY_SERVICE); 2074 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2075 } 2076 2077 public PackageManagerService(Context context, Installer installer, 2078 boolean factoryTest, boolean onlyCore) { 2079 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2080 SystemClock.uptimeMillis()); 2081 2082 if (mSdkVersion <= 0) { 2083 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2084 } 2085 2086 mContext = context; 2087 mFactoryTest = factoryTest; 2088 mOnlyCore = onlyCore; 2089 mMetrics = new DisplayMetrics(); 2090 mSettings = new Settings(mPackages); 2091 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2092 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2093 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2094 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2095 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2096 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2097 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2098 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2099 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2100 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2101 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2102 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2103 2104 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2105 if (separateProcesses != null && separateProcesses.length() > 0) { 2106 if ("*".equals(separateProcesses)) { 2107 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2108 mSeparateProcesses = null; 2109 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2110 } else { 2111 mDefParseFlags = 0; 2112 mSeparateProcesses = separateProcesses.split(","); 2113 Slog.w(TAG, "Running with debug.separate_processes: " 2114 + separateProcesses); 2115 } 2116 } else { 2117 mDefParseFlags = 0; 2118 mSeparateProcesses = null; 2119 } 2120 2121 mInstaller = installer; 2122 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2123 "*dexopt*"); 2124 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2125 2126 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2127 FgThread.get().getLooper()); 2128 2129 getDefaultDisplayMetrics(context, mMetrics); 2130 2131 SystemConfig systemConfig = SystemConfig.getInstance(); 2132 mGlobalGids = systemConfig.getGlobalGids(); 2133 mSystemPermissions = systemConfig.getSystemPermissions(); 2134 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2135 2136 synchronized (mInstallLock) { 2137 // writer 2138 synchronized (mPackages) { 2139 mHandlerThread = new ServiceThread(TAG, 2140 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2141 mHandlerThread.start(); 2142 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2143 mProcessLoggingHandler = new ProcessLoggingHandler(); 2144 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2145 2146 File dataDir = Environment.getDataDirectory(); 2147 mAppInstallDir = new File(dataDir, "app"); 2148 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2149 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2150 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2151 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2152 2153 sUserManager = new UserManagerService(context, this, mPackages); 2154 2155 // Propagate permission configuration in to package manager. 2156 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2157 = systemConfig.getPermissions(); 2158 for (int i=0; i<permConfig.size(); i++) { 2159 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2160 BasePermission bp = mSettings.mPermissions.get(perm.name); 2161 if (bp == null) { 2162 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2163 mSettings.mPermissions.put(perm.name, bp); 2164 } 2165 if (perm.gids != null) { 2166 bp.setGids(perm.gids, perm.perUser); 2167 } 2168 } 2169 2170 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2171 for (int i=0; i<libConfig.size(); i++) { 2172 mSharedLibraries.put(libConfig.keyAt(i), 2173 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2174 } 2175 2176 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2177 2178 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 2179 2180 String customResolverActivity = Resources.getSystem().getString( 2181 R.string.config_customResolverActivity); 2182 if (TextUtils.isEmpty(customResolverActivity)) { 2183 customResolverActivity = null; 2184 } else { 2185 mCustomResolverComponentName = ComponentName.unflattenFromString( 2186 customResolverActivity); 2187 } 2188 2189 long startTime = SystemClock.uptimeMillis(); 2190 2191 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2192 startTime); 2193 2194 // Set flag to monitor and not change apk file paths when 2195 // scanning install directories. 2196 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2197 2198 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2199 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2200 2201 if (bootClassPath == null) { 2202 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2203 } 2204 2205 if (systemServerClassPath == null) { 2206 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2207 } 2208 2209 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2210 final String[] dexCodeInstructionSets = 2211 getDexCodeInstructionSets( 2212 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2213 2214 /** 2215 * Ensure all external libraries have had dexopt run on them. 2216 */ 2217 if (mSharedLibraries.size() > 0) { 2218 // NOTE: For now, we're compiling these system "shared libraries" 2219 // (and framework jars) into all available architectures. It's possible 2220 // to compile them only when we come across an app that uses them (there's 2221 // already logic for that in scanPackageLI) but that adds some complexity. 2222 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2223 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2224 final String lib = libEntry.path; 2225 if (lib == null) { 2226 continue; 2227 } 2228 2229 try { 2230 // Shared libraries do not have profiles so we perform a full 2231 // AOT compilation (if needed). 2232 int dexoptNeeded = DexFile.getDexOptNeeded( 2233 lib, dexCodeInstructionSet, 2234 getCompilerFilterForReason(REASON_SHARED_APK), 2235 false /* newProfile */); 2236 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2237 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2238 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/, 2239 getCompilerFilterForReason(REASON_SHARED_APK), 2240 StorageManager.UUID_PRIVATE_INTERNAL); 2241 } 2242 } catch (FileNotFoundException e) { 2243 Slog.w(TAG, "Library not found: " + lib); 2244 } catch (IOException | InstallerException e) { 2245 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2246 + e.getMessage()); 2247 } 2248 } 2249 } 2250 } 2251 2252 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2253 2254 final VersionInfo ver = mSettings.getInternalVersion(); 2255 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2256 2257 // when upgrading from pre-M, promote system app permissions from install to runtime 2258 mPromoteSystemApps = 2259 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2260 2261 // save off the names of pre-existing system packages prior to scanning; we don't 2262 // want to automatically grant runtime permissions for new system apps 2263 if (mPromoteSystemApps) { 2264 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2265 while (pkgSettingIter.hasNext()) { 2266 PackageSetting ps = pkgSettingIter.next(); 2267 if (isSystemApp(ps)) { 2268 mExistingSystemPackages.add(ps.name); 2269 } 2270 } 2271 } 2272 2273 // When upgrading from pre-N, we need to handle package extraction like first boot, 2274 // as there is no profiling data available. 2275 mIsPreNUpgrade = !mSettings.isNWorkDone(); 2276 mSettings.setNWorkDone(); 2277 2278 // Collect vendor overlay packages. 2279 // (Do this before scanning any apps.) 2280 // For security and version matching reason, only consider 2281 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2282 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2283 scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 2284 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2285 2286 // Find base frameworks (resource packages without code). 2287 scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 2288 | PackageParser.PARSE_IS_SYSTEM_DIR 2289 | PackageParser.PARSE_IS_PRIVILEGED, 2290 scanFlags | SCAN_NO_DEX, 0); 2291 2292 // Collected privileged system packages. 2293 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2294 scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 2295 | PackageParser.PARSE_IS_SYSTEM_DIR 2296 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2297 2298 // Collect ordinary system packages. 2299 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2300 scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2301 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2302 2303 // Collect all vendor packages. 2304 File vendorAppDir = new File("/vendor/app"); 2305 try { 2306 vendorAppDir = vendorAppDir.getCanonicalFile(); 2307 } catch (IOException e) { 2308 // failed to look up canonical path, continue with original one 2309 } 2310 scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2311 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2312 2313 // Collect all OEM packages. 2314 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2315 scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2316 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2317 2318 // Prune any system packages that no longer exist. 2319 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2320 if (!mOnlyCore) { 2321 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2322 while (psit.hasNext()) { 2323 PackageSetting ps = psit.next(); 2324 2325 /* 2326 * If this is not a system app, it can't be a 2327 * disable system app. 2328 */ 2329 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2330 continue; 2331 } 2332 2333 /* 2334 * If the package is scanned, it's not erased. 2335 */ 2336 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2337 if (scannedPkg != null) { 2338 /* 2339 * If the system app is both scanned and in the 2340 * disabled packages list, then it must have been 2341 * added via OTA. Remove it from the currently 2342 * scanned package so the previously user-installed 2343 * application can be scanned. 2344 */ 2345 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2346 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2347 + ps.name + "; removing system app. Last known codePath=" 2348 + ps.codePathString + ", installStatus=" + ps.installStatus 2349 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2350 + scannedPkg.mVersionCode); 2351 removePackageLI(scannedPkg, true); 2352 mExpectingBetter.put(ps.name, ps.codePath); 2353 } 2354 2355 continue; 2356 } 2357 2358 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2359 psit.remove(); 2360 logCriticalInfo(Log.WARN, "System package " + ps.name 2361 + " no longer exists; wiping its data"); 2362 removeDataDirsLI(null, ps.name); 2363 } else { 2364 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2365 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2366 possiblyDeletedUpdatedSystemApps.add(ps.name); 2367 } 2368 } 2369 } 2370 } 2371 2372 //look for any incomplete package installations 2373 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2374 //clean up list 2375 for(int i = 0; i < deletePkgsList.size(); i++) { 2376 //clean up here 2377 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2378 } 2379 //delete tmp files 2380 deleteTempPackageFiles(); 2381 2382 // Remove any shared userIDs that have no associated packages 2383 mSettings.pruneSharedUsersLPw(); 2384 2385 if (!mOnlyCore) { 2386 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2387 SystemClock.uptimeMillis()); 2388 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2389 2390 scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2391 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2392 2393 scanDirLI(mEphemeralInstallDir, PackageParser.PARSE_IS_EPHEMERAL, 2394 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2395 2396 /** 2397 * Remove disable package settings for any updated system 2398 * apps that were removed via an OTA. If they're not a 2399 * previously-updated app, remove them completely. 2400 * Otherwise, just revoke their system-level permissions. 2401 */ 2402 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2403 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2404 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2405 2406 String msg; 2407 if (deletedPkg == null) { 2408 msg = "Updated system package " + deletedAppName 2409 + " no longer exists; wiping its data"; 2410 removeDataDirsLI(null, deletedAppName); 2411 } else { 2412 msg = "Updated system app + " + deletedAppName 2413 + " no longer present; removing system privileges for " 2414 + deletedAppName; 2415 2416 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2417 2418 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2419 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2420 } 2421 logCriticalInfo(Log.WARN, msg); 2422 } 2423 2424 /** 2425 * Make sure all system apps that we expected to appear on 2426 * the userdata partition actually showed up. If they never 2427 * appeared, crawl back and revive the system version. 2428 */ 2429 for (int i = 0; i < mExpectingBetter.size(); i++) { 2430 final String packageName = mExpectingBetter.keyAt(i); 2431 if (!mPackages.containsKey(packageName)) { 2432 final File scanFile = mExpectingBetter.valueAt(i); 2433 2434 logCriticalInfo(Log.WARN, "Expected better " + packageName 2435 + " but never showed up; reverting to system"); 2436 2437 final int reparseFlags; 2438 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2439 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2440 | PackageParser.PARSE_IS_SYSTEM_DIR 2441 | PackageParser.PARSE_IS_PRIVILEGED; 2442 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2443 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2444 | PackageParser.PARSE_IS_SYSTEM_DIR; 2445 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2446 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2447 | PackageParser.PARSE_IS_SYSTEM_DIR; 2448 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2449 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2450 | PackageParser.PARSE_IS_SYSTEM_DIR; 2451 } else { 2452 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2453 continue; 2454 } 2455 2456 mSettings.enableSystemPackageLPw(packageName); 2457 2458 try { 2459 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2460 } catch (PackageManagerException e) { 2461 Slog.e(TAG, "Failed to parse original system package: " 2462 + e.getMessage()); 2463 } 2464 } 2465 } 2466 } 2467 mExpectingBetter.clear(); 2468 2469 // Resolve protected action filters. Only the setup wizard is allowed to 2470 // have a high priority filter for these actions. 2471 mSetupWizardPackage = getSetupWizardPackageName(); 2472 if (mProtectedFilters.size() > 0) { 2473 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2474 Slog.i(TAG, "No setup wizard;" 2475 + " All protected intents capped to priority 0"); 2476 } 2477 for (ActivityIntentInfo filter : mProtectedFilters) { 2478 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2479 if (DEBUG_FILTERS) { 2480 Slog.i(TAG, "Found setup wizard;" 2481 + " allow priority " + filter.getPriority() + ";" 2482 + " package: " + filter.activity.info.packageName 2483 + " activity: " + filter.activity.className 2484 + " priority: " + filter.getPriority()); 2485 } 2486 // skip setup wizard; allow it to keep the high priority filter 2487 continue; 2488 } 2489 Slog.w(TAG, "Protected action; cap priority to 0;" 2490 + " package: " + filter.activity.info.packageName 2491 + " activity: " + filter.activity.className 2492 + " origPrio: " + filter.getPriority()); 2493 filter.setPriority(0); 2494 } 2495 } 2496 mDeferProtectedFilters = false; 2497 mProtectedFilters.clear(); 2498 2499 // Now that we know all of the shared libraries, update all clients to have 2500 // the correct library paths. 2501 updateAllSharedLibrariesLPw(); 2502 2503 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2504 // NOTE: We ignore potential failures here during a system scan (like 2505 // the rest of the commands above) because there's precious little we 2506 // can do about it. A settings error is reported, though. 2507 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2508 false /* boot complete */); 2509 } 2510 2511 // Now that we know all the packages we are keeping, 2512 // read and update their last usage times. 2513 mPackageUsage.readLP(); 2514 2515 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2516 SystemClock.uptimeMillis()); 2517 Slog.i(TAG, "Time to scan packages: " 2518 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2519 + " seconds"); 2520 2521 // If the platform SDK has changed since the last time we booted, 2522 // we need to re-grant app permission to catch any new ones that 2523 // appear. This is really a hack, and means that apps can in some 2524 // cases get permissions that the user didn't initially explicitly 2525 // allow... it would be nice to have some better way to handle 2526 // this situation. 2527 int updateFlags = UPDATE_PERMISSIONS_ALL; 2528 if (ver.sdkVersion != mSdkVersion) { 2529 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2530 + mSdkVersion + "; regranting permissions for internal storage"); 2531 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2532 } 2533 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2534 ver.sdkVersion = mSdkVersion; 2535 2536 // If this is the first boot or an update from pre-M, and it is a normal 2537 // boot, then we need to initialize the default preferred apps across 2538 // all defined users. 2539 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2540 for (UserInfo user : sUserManager.getUsers(true)) { 2541 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2542 applyFactoryDefaultBrowserLPw(user.id); 2543 primeDomainVerificationsLPw(user.id); 2544 } 2545 } 2546 2547 // Prepare storage for system user really early during boot, 2548 // since core system apps like SettingsProvider and SystemUI 2549 // can't wait for user to start 2550 final int storageFlags; 2551 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2552 storageFlags = StorageManager.FLAG_STORAGE_DE; 2553 } else { 2554 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2555 } 2556 reconcileAppsData(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2557 storageFlags); 2558 2559 // If this is first boot after an OTA, and a normal boot, then 2560 // we need to clear code cache directories. 2561 if (mIsUpgrade && !onlyCore) { 2562 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2563 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2564 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2565 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2566 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2567 } 2568 } 2569 ver.fingerprint = Build.FINGERPRINT; 2570 } 2571 2572 checkDefaultBrowser(); 2573 2574 // clear only after permissions and other defaults have been updated 2575 mExistingSystemPackages.clear(); 2576 mPromoteSystemApps = false; 2577 2578 // All the changes are done during package scanning. 2579 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2580 2581 // can downgrade to reader 2582 mSettings.writeLPr(); 2583 2584 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2585 SystemClock.uptimeMillis()); 2586 2587 if (!mOnlyCore) { 2588 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2589 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2590 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2591 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2592 mIntentFilterVerifierComponent); 2593 } else { 2594 mRequiredVerifierPackage = null; 2595 mRequiredInstallerPackage = null; 2596 mIntentFilterVerifierComponent = null; 2597 mIntentFilterVerifier = null; 2598 } 2599 2600 mInstallerService = new PackageInstallerService(context, this); 2601 2602 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2603 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2604 // both the installer and resolver must be present to enable ephemeral 2605 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2606 if (DEBUG_EPHEMERAL) { 2607 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2608 + " installer:" + ephemeralInstallerComponent); 2609 } 2610 mEphemeralResolverComponent = ephemeralResolverComponent; 2611 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2612 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2613 mEphemeralResolverConnection = 2614 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2615 } else { 2616 if (DEBUG_EPHEMERAL) { 2617 final String missingComponent = 2618 (ephemeralResolverComponent == null) 2619 ? (ephemeralInstallerComponent == null) 2620 ? "resolver and installer" 2621 : "resolver" 2622 : "installer"; 2623 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2624 } 2625 mEphemeralResolverComponent = null; 2626 mEphemeralInstallerComponent = null; 2627 mEphemeralResolverConnection = null; 2628 } 2629 2630 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2631 } // synchronized (mPackages) 2632 } // synchronized (mInstallLock) 2633 2634 // Now after opening every single application zip, make sure they 2635 // are all flushed. Not really needed, but keeps things nice and 2636 // tidy. 2637 Runtime.getRuntime().gc(); 2638 2639 // The initial scanning above does many calls into installd while 2640 // holding the mPackages lock, but we're mostly interested in yelling 2641 // once we have a booted system. 2642 mInstaller.setWarnIfHeld(mPackages); 2643 2644 // Expose private service for system components to use. 2645 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2646 } 2647 2648 @Override 2649 public boolean isFirstBoot() { 2650 return !mRestoredSettings; 2651 } 2652 2653 @Override 2654 public boolean isOnlyCoreApps() { 2655 return mOnlyCore; 2656 } 2657 2658 @Override 2659 public boolean isUpgrade() { 2660 return mIsUpgrade; 2661 } 2662 2663 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2664 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2665 2666 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2667 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2668 UserHandle.USER_SYSTEM); 2669 if (matches.size() == 1) { 2670 return matches.get(0).getComponentInfo().packageName; 2671 } else { 2672 Log.e(TAG, "There should probably be exactly one verifier; found " + matches); 2673 return null; 2674 } 2675 } 2676 2677 private @NonNull String getRequiredInstallerLPr() { 2678 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2679 intent.addCategory(Intent.CATEGORY_DEFAULT); 2680 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2681 2682 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2683 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2684 UserHandle.USER_SYSTEM); 2685 if (matches.size() == 1) { 2686 return matches.get(0).getComponentInfo().packageName; 2687 } else { 2688 throw new RuntimeException("There must be exactly one installer; found " + matches); 2689 } 2690 } 2691 2692 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2693 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2694 2695 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2696 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2697 UserHandle.USER_SYSTEM); 2698 ResolveInfo best = null; 2699 final int N = matches.size(); 2700 for (int i = 0; i < N; i++) { 2701 final ResolveInfo cur = matches.get(i); 2702 final String packageName = cur.getComponentInfo().packageName; 2703 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2704 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2705 continue; 2706 } 2707 2708 if (best == null || cur.priority > best.priority) { 2709 best = cur; 2710 } 2711 } 2712 2713 if (best != null) { 2714 return best.getComponentInfo().getComponentName(); 2715 } else { 2716 throw new RuntimeException("There must be at least one intent filter verifier"); 2717 } 2718 } 2719 2720 private @Nullable ComponentName getEphemeralResolverLPr() { 2721 final String[] packageArray = 2722 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2723 if (packageArray.length == 0) { 2724 if (DEBUG_EPHEMERAL) { 2725 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2726 } 2727 return null; 2728 } 2729 2730 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2731 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 2732 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2733 UserHandle.USER_SYSTEM); 2734 2735 final int N = resolvers.size(); 2736 if (N == 0) { 2737 if (DEBUG_EPHEMERAL) { 2738 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2739 } 2740 return null; 2741 } 2742 2743 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2744 for (int i = 0; i < N; i++) { 2745 final ResolveInfo info = resolvers.get(i); 2746 2747 if (info.serviceInfo == null) { 2748 continue; 2749 } 2750 2751 final String packageName = info.serviceInfo.packageName; 2752 if (!possiblePackages.contains(packageName)) { 2753 if (DEBUG_EPHEMERAL) { 2754 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2755 + " pkg: " + packageName + ", info:" + info); 2756 } 2757 continue; 2758 } 2759 2760 if (DEBUG_EPHEMERAL) { 2761 Slog.v(TAG, "Ephemeral resolver found;" 2762 + " pkg: " + packageName + ", info:" + info); 2763 } 2764 return new ComponentName(packageName, info.serviceInfo.name); 2765 } 2766 if (DEBUG_EPHEMERAL) { 2767 Slog.v(TAG, "Ephemeral resolver NOT found"); 2768 } 2769 return null; 2770 } 2771 2772 private @Nullable ComponentName getEphemeralInstallerLPr() { 2773 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2774 intent.addCategory(Intent.CATEGORY_DEFAULT); 2775 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2776 2777 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2778 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2779 UserHandle.USER_SYSTEM); 2780 if (matches.size() == 0) { 2781 return null; 2782 } else if (matches.size() == 1) { 2783 return matches.get(0).getComponentInfo().getComponentName(); 2784 } else { 2785 throw new RuntimeException( 2786 "There must be at most one ephemeral installer; found " + matches); 2787 } 2788 } 2789 2790 private void primeDomainVerificationsLPw(int userId) { 2791 if (DEBUG_DOMAIN_VERIFICATION) { 2792 Slog.d(TAG, "Priming domain verifications in user " + userId); 2793 } 2794 2795 SystemConfig systemConfig = SystemConfig.getInstance(); 2796 ArraySet<String> packages = systemConfig.getLinkedApps(); 2797 ArraySet<String> domains = new ArraySet<String>(); 2798 2799 for (String packageName : packages) { 2800 PackageParser.Package pkg = mPackages.get(packageName); 2801 if (pkg != null) { 2802 if (!pkg.isSystemApp()) { 2803 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2804 continue; 2805 } 2806 2807 domains.clear(); 2808 for (PackageParser.Activity a : pkg.activities) { 2809 for (ActivityIntentInfo filter : a.intents) { 2810 if (hasValidDomains(filter)) { 2811 domains.addAll(filter.getHostsList()); 2812 } 2813 } 2814 } 2815 2816 if (domains.size() > 0) { 2817 if (DEBUG_DOMAIN_VERIFICATION) { 2818 Slog.v(TAG, " + " + packageName); 2819 } 2820 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2821 // state w.r.t. the formal app-linkage "no verification attempted" state; 2822 // and then 'always' in the per-user state actually used for intent resolution. 2823 final IntentFilterVerificationInfo ivi; 2824 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2825 new ArrayList<String>(domains)); 2826 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2827 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2828 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2829 } else { 2830 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2831 + "' does not handle web links"); 2832 } 2833 } else { 2834 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 2835 } 2836 } 2837 2838 scheduleWritePackageRestrictionsLocked(userId); 2839 scheduleWriteSettingsLocked(); 2840 } 2841 2842 private void applyFactoryDefaultBrowserLPw(int userId) { 2843 // The default browser app's package name is stored in a string resource, 2844 // with a product-specific overlay used for vendor customization. 2845 String browserPkg = mContext.getResources().getString( 2846 com.android.internal.R.string.default_browser); 2847 if (!TextUtils.isEmpty(browserPkg)) { 2848 // non-empty string => required to be a known package 2849 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2850 if (ps == null) { 2851 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2852 browserPkg = null; 2853 } else { 2854 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2855 } 2856 } 2857 2858 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2859 // default. If there's more than one, just leave everything alone. 2860 if (browserPkg == null) { 2861 calculateDefaultBrowserLPw(userId); 2862 } 2863 } 2864 2865 private void calculateDefaultBrowserLPw(int userId) { 2866 List<String> allBrowsers = resolveAllBrowserApps(userId); 2867 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2868 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2869 } 2870 2871 private List<String> resolveAllBrowserApps(int userId) { 2872 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2873 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 2874 PackageManager.MATCH_ALL, userId); 2875 2876 final int count = list.size(); 2877 List<String> result = new ArrayList<String>(count); 2878 for (int i=0; i<count; i++) { 2879 ResolveInfo info = list.get(i); 2880 if (info.activityInfo == null 2881 || !info.handleAllWebDataURI 2882 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2883 || result.contains(info.activityInfo.packageName)) { 2884 continue; 2885 } 2886 result.add(info.activityInfo.packageName); 2887 } 2888 2889 return result; 2890 } 2891 2892 private boolean packageIsBrowser(String packageName, int userId) { 2893 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 2894 PackageManager.MATCH_ALL, userId); 2895 final int N = list.size(); 2896 for (int i = 0; i < N; i++) { 2897 ResolveInfo info = list.get(i); 2898 if (packageName.equals(info.activityInfo.packageName)) { 2899 return true; 2900 } 2901 } 2902 return false; 2903 } 2904 2905 private void checkDefaultBrowser() { 2906 final int myUserId = UserHandle.myUserId(); 2907 final String packageName = getDefaultBrowserPackageName(myUserId); 2908 if (packageName != null) { 2909 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2910 if (info == null) { 2911 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2912 synchronized (mPackages) { 2913 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2914 } 2915 } 2916 } 2917 } 2918 2919 @Override 2920 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2921 throws RemoteException { 2922 try { 2923 return super.onTransact(code, data, reply, flags); 2924 } catch (RuntimeException e) { 2925 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2926 Slog.wtf(TAG, "Package Manager Crash", e); 2927 } 2928 throw e; 2929 } 2930 } 2931 2932 void cleanupInstallFailedPackage(PackageSetting ps) { 2933 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2934 2935 removeDataDirsLI(ps.volumeUuid, ps.name); 2936 if (ps.codePath != null) { 2937 removeCodePathLI(ps.codePath); 2938 } 2939 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2940 if (ps.resourcePath.isDirectory()) { 2941 FileUtils.deleteContents(ps.resourcePath); 2942 } 2943 ps.resourcePath.delete(); 2944 } 2945 mSettings.removePackageLPw(ps.name); 2946 } 2947 2948 static int[] appendInts(int[] cur, int[] add) { 2949 if (add == null) return cur; 2950 if (cur == null) return add; 2951 final int N = add.length; 2952 for (int i=0; i<N; i++) { 2953 cur = appendInt(cur, add[i]); 2954 } 2955 return cur; 2956 } 2957 2958 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 2959 if (!sUserManager.exists(userId)) return null; 2960 if (ps == null) { 2961 return null; 2962 } 2963 final PackageParser.Package p = ps.pkg; 2964 if (p == null) { 2965 return null; 2966 } 2967 2968 final PermissionsState permissionsState = ps.getPermissionsState(); 2969 2970 final int[] gids = permissionsState.computeGids(userId); 2971 final Set<String> permissions = permissionsState.getPermissions(userId); 2972 final PackageUserState state = ps.readUserState(userId); 2973 2974 return PackageParser.generatePackageInfo(p, gids, flags, 2975 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2976 } 2977 2978 @Override 2979 public void checkPackageStartable(String packageName, int userId) { 2980 final boolean userKeyUnlocked = isUserKeyUnlocked(userId); 2981 2982 synchronized (mPackages) { 2983 final PackageSetting ps = mSettings.mPackages.get(packageName); 2984 if (ps == null) { 2985 throw new SecurityException("Package " + packageName + " was not found!"); 2986 } 2987 2988 if (!ps.getInstalled(userId)) { 2989 throw new SecurityException( 2990 "Package " + packageName + " was not installed for user " + userId + "!"); 2991 } 2992 2993 if (mSafeMode && !ps.isSystem()) { 2994 throw new SecurityException("Package " + packageName + " not a system app!"); 2995 } 2996 2997 if (ps.frozen) { 2998 throw new SecurityException("Package " + packageName + " is currently frozen!"); 2999 } 3000 3001 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3002 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3003 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3004 } 3005 } 3006 } 3007 3008 @Override 3009 public boolean isPackageAvailable(String packageName, int userId) { 3010 if (!sUserManager.exists(userId)) return false; 3011 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3012 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3013 synchronized (mPackages) { 3014 PackageParser.Package p = mPackages.get(packageName); 3015 if (p != null) { 3016 final PackageSetting ps = (PackageSetting) p.mExtras; 3017 if (ps != null) { 3018 final PackageUserState state = ps.readUserState(userId); 3019 if (state != null) { 3020 return PackageParser.isAvailable(state); 3021 } 3022 } 3023 } 3024 } 3025 return false; 3026 } 3027 3028 @Override 3029 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3030 if (!sUserManager.exists(userId)) return null; 3031 flags = updateFlagsForPackage(flags, userId, packageName); 3032 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3033 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3034 // reader 3035 synchronized (mPackages) { 3036 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3037 PackageParser.Package p = null; 3038 if (matchFactoryOnly) { 3039 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3040 if (ps != null) { 3041 return generatePackageInfo(ps, flags, userId); 3042 } 3043 } 3044 if (p == null) { 3045 p = mPackages.get(packageName); 3046 if (matchFactoryOnly && !isSystemApp(p)) { 3047 return null; 3048 } 3049 } 3050 if (DEBUG_PACKAGE_INFO) 3051 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3052 if (p != null) { 3053 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3054 } 3055 if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3056 final PackageSetting ps = mSettings.mPackages.get(packageName); 3057 return generatePackageInfo(ps, flags, userId); 3058 } 3059 } 3060 return null; 3061 } 3062 3063 @Override 3064 public String[] currentToCanonicalPackageNames(String[] names) { 3065 String[] out = new String[names.length]; 3066 // reader 3067 synchronized (mPackages) { 3068 for (int i=names.length-1; i>=0; i--) { 3069 PackageSetting ps = mSettings.mPackages.get(names[i]); 3070 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3071 } 3072 } 3073 return out; 3074 } 3075 3076 @Override 3077 public String[] canonicalToCurrentPackageNames(String[] names) { 3078 String[] out = new String[names.length]; 3079 // reader 3080 synchronized (mPackages) { 3081 for (int i=names.length-1; i>=0; i--) { 3082 String cur = mSettings.mRenamedPackages.get(names[i]); 3083 out[i] = cur != null ? cur : names[i]; 3084 } 3085 } 3086 return out; 3087 } 3088 3089 @Override 3090 public int getPackageUid(String packageName, int flags, int userId) { 3091 if (!sUserManager.exists(userId)) return -1; 3092 flags = updateFlagsForPackage(flags, userId, packageName); 3093 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3094 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3095 3096 // reader 3097 synchronized (mPackages) { 3098 final PackageParser.Package p = mPackages.get(packageName); 3099 if (p != null && p.isMatch(flags)) { 3100 return UserHandle.getUid(userId, p.applicationInfo.uid); 3101 } 3102 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3103 final PackageSetting ps = mSettings.mPackages.get(packageName); 3104 if (ps != null && ps.isMatch(flags)) { 3105 return UserHandle.getUid(userId, ps.appId); 3106 } 3107 } 3108 } 3109 3110 return -1; 3111 } 3112 3113 @Override 3114 public int[] getPackageGids(String packageName, int flags, int userId) { 3115 if (!sUserManager.exists(userId)) return null; 3116 flags = updateFlagsForPackage(flags, userId, packageName); 3117 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3118 false /* requireFullPermission */, false /* checkShell */, 3119 "getPackageGids"); 3120 3121 // reader 3122 synchronized (mPackages) { 3123 final PackageParser.Package p = mPackages.get(packageName); 3124 if (p != null && p.isMatch(flags)) { 3125 PackageSetting ps = (PackageSetting) p.mExtras; 3126 return ps.getPermissionsState().computeGids(userId); 3127 } 3128 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3129 final PackageSetting ps = mSettings.mPackages.get(packageName); 3130 if (ps != null && ps.isMatch(flags)) { 3131 return ps.getPermissionsState().computeGids(userId); 3132 } 3133 } 3134 } 3135 3136 return null; 3137 } 3138 3139 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3140 if (bp.perm != null) { 3141 return PackageParser.generatePermissionInfo(bp.perm, flags); 3142 } 3143 PermissionInfo pi = new PermissionInfo(); 3144 pi.name = bp.name; 3145 pi.packageName = bp.sourcePackage; 3146 pi.nonLocalizedLabel = bp.name; 3147 pi.protectionLevel = bp.protectionLevel; 3148 return pi; 3149 } 3150 3151 @Override 3152 public PermissionInfo getPermissionInfo(String name, int flags) { 3153 // reader 3154 synchronized (mPackages) { 3155 final BasePermission p = mSettings.mPermissions.get(name); 3156 if (p != null) { 3157 return generatePermissionInfo(p, flags); 3158 } 3159 return null; 3160 } 3161 } 3162 3163 @Override 3164 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3165 int flags) { 3166 // reader 3167 synchronized (mPackages) { 3168 if (group != null && !mPermissionGroups.containsKey(group)) { 3169 // This is thrown as NameNotFoundException 3170 return null; 3171 } 3172 3173 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3174 for (BasePermission p : mSettings.mPermissions.values()) { 3175 if (group == null) { 3176 if (p.perm == null || p.perm.info.group == null) { 3177 out.add(generatePermissionInfo(p, flags)); 3178 } 3179 } else { 3180 if (p.perm != null && group.equals(p.perm.info.group)) { 3181 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3182 } 3183 } 3184 } 3185 return new ParceledListSlice<>(out); 3186 } 3187 } 3188 3189 @Override 3190 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3191 // reader 3192 synchronized (mPackages) { 3193 return PackageParser.generatePermissionGroupInfo( 3194 mPermissionGroups.get(name), flags); 3195 } 3196 } 3197 3198 @Override 3199 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3200 // reader 3201 synchronized (mPackages) { 3202 final int N = mPermissionGroups.size(); 3203 ArrayList<PermissionGroupInfo> out 3204 = new ArrayList<PermissionGroupInfo>(N); 3205 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3206 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3207 } 3208 return new ParceledListSlice<>(out); 3209 } 3210 } 3211 3212 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3213 int userId) { 3214 if (!sUserManager.exists(userId)) return null; 3215 PackageSetting ps = mSettings.mPackages.get(packageName); 3216 if (ps != null) { 3217 if (ps.pkg == null) { 3218 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3219 if (pInfo != null) { 3220 return pInfo.applicationInfo; 3221 } 3222 return null; 3223 } 3224 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3225 ps.readUserState(userId), userId); 3226 } 3227 return null; 3228 } 3229 3230 @Override 3231 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3232 if (!sUserManager.exists(userId)) return null; 3233 flags = updateFlagsForApplication(flags, userId, packageName); 3234 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3235 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3236 // writer 3237 synchronized (mPackages) { 3238 PackageParser.Package p = mPackages.get(packageName); 3239 if (DEBUG_PACKAGE_INFO) Log.v( 3240 TAG, "getApplicationInfo " + packageName 3241 + ": " + p); 3242 if (p != null) { 3243 PackageSetting ps = mSettings.mPackages.get(packageName); 3244 if (ps == null) return null; 3245 // Note: isEnabledLP() does not apply here - always return info 3246 return PackageParser.generateApplicationInfo( 3247 p, flags, ps.readUserState(userId), userId); 3248 } 3249 if ("android".equals(packageName)||"system".equals(packageName)) { 3250 return mAndroidApplication; 3251 } 3252 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3253 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3254 } 3255 } 3256 return null; 3257 } 3258 3259 @Override 3260 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3261 final IPackageDataObserver observer) { 3262 mContext.enforceCallingOrSelfPermission( 3263 android.Manifest.permission.CLEAR_APP_CACHE, null); 3264 // Queue up an async operation since clearing cache may take a little while. 3265 mHandler.post(new Runnable() { 3266 public void run() { 3267 mHandler.removeCallbacks(this); 3268 boolean success = true; 3269 synchronized (mInstallLock) { 3270 try { 3271 mInstaller.freeCache(volumeUuid, freeStorageSize); 3272 } catch (InstallerException e) { 3273 Slog.w(TAG, "Couldn't clear application caches: " + e); 3274 success = false; 3275 } 3276 } 3277 if (observer != null) { 3278 try { 3279 observer.onRemoveCompleted(null, success); 3280 } catch (RemoteException e) { 3281 Slog.w(TAG, "RemoveException when invoking call back"); 3282 } 3283 } 3284 } 3285 }); 3286 } 3287 3288 @Override 3289 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3290 final IntentSender pi) { 3291 mContext.enforceCallingOrSelfPermission( 3292 android.Manifest.permission.CLEAR_APP_CACHE, null); 3293 // Queue up an async operation since clearing cache may take a little while. 3294 mHandler.post(new Runnable() { 3295 public void run() { 3296 mHandler.removeCallbacks(this); 3297 boolean success = true; 3298 synchronized (mInstallLock) { 3299 try { 3300 mInstaller.freeCache(volumeUuid, freeStorageSize); 3301 } catch (InstallerException e) { 3302 Slog.w(TAG, "Couldn't clear application caches: " + e); 3303 success = false; 3304 } 3305 } 3306 if(pi != null) { 3307 try { 3308 // Callback via pending intent 3309 int code = success ? 1 : 0; 3310 pi.sendIntent(null, code, null, 3311 null, null); 3312 } catch (SendIntentException e1) { 3313 Slog.i(TAG, "Failed to send pending intent"); 3314 } 3315 } 3316 } 3317 }); 3318 } 3319 3320 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3321 synchronized (mInstallLock) { 3322 try { 3323 mInstaller.freeCache(volumeUuid, freeStorageSize); 3324 } catch (InstallerException e) { 3325 throw new IOException("Failed to free enough space", e); 3326 } 3327 } 3328 } 3329 3330 /** 3331 * Return if the user key is currently unlocked. 3332 */ 3333 private boolean isUserKeyUnlocked(int userId) { 3334 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 3335 final IMountService mount = IMountService.Stub 3336 .asInterface(ServiceManager.getService("mount")); 3337 if (mount == null) { 3338 Slog.w(TAG, "Early during boot, assuming locked"); 3339 return false; 3340 } 3341 final long token = Binder.clearCallingIdentity(); 3342 try { 3343 return mount.isUserKeyUnlocked(userId); 3344 } catch (RemoteException e) { 3345 throw e.rethrowAsRuntimeException(); 3346 } finally { 3347 Binder.restoreCallingIdentity(token); 3348 } 3349 } else { 3350 return true; 3351 } 3352 } 3353 3354 /** 3355 * Update given flags based on encryption status of current user. 3356 */ 3357 private int updateFlags(int flags, int userId) { 3358 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3359 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3360 // Caller expressed an explicit opinion about what encryption 3361 // aware/unaware components they want to see, so fall through and 3362 // give them what they want 3363 } else { 3364 // Caller expressed no opinion, so match based on user state 3365 if (isUserKeyUnlocked(userId)) { 3366 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3367 } else { 3368 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3369 } 3370 } 3371 return flags; 3372 } 3373 3374 /** 3375 * Update given flags when being used to request {@link PackageInfo}. 3376 */ 3377 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3378 boolean triaged = true; 3379 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3380 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3381 // Caller is asking for component details, so they'd better be 3382 // asking for specific encryption matching behavior, or be triaged 3383 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3384 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3385 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3386 triaged = false; 3387 } 3388 } 3389 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3390 | PackageManager.MATCH_SYSTEM_ONLY 3391 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3392 triaged = false; 3393 } 3394 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3395 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3396 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3397 } 3398 return updateFlags(flags, userId); 3399 } 3400 3401 /** 3402 * Update given flags when being used to request {@link ApplicationInfo}. 3403 */ 3404 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3405 return updateFlagsForPackage(flags, userId, cookie); 3406 } 3407 3408 /** 3409 * Update given flags when being used to request {@link ComponentInfo}. 3410 */ 3411 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3412 if (cookie instanceof Intent) { 3413 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3414 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3415 } 3416 } 3417 3418 boolean triaged = true; 3419 // Caller is asking for component details, so they'd better be 3420 // asking for specific encryption matching behavior, or be triaged 3421 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3422 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3423 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3424 triaged = false; 3425 } 3426 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3427 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3428 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3429 } 3430 3431 return updateFlags(flags, userId); 3432 } 3433 3434 /** 3435 * Update given flags when being used to request {@link ResolveInfo}. 3436 */ 3437 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3438 // Safe mode means we shouldn't match any third-party components 3439 if (mSafeMode) { 3440 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3441 } 3442 3443 return updateFlagsForComponent(flags, userId, cookie); 3444 } 3445 3446 @Override 3447 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3448 if (!sUserManager.exists(userId)) return null; 3449 flags = updateFlagsForComponent(flags, userId, component); 3450 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3451 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3452 synchronized (mPackages) { 3453 PackageParser.Activity a = mActivities.mActivities.get(component); 3454 3455 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3456 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3457 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3458 if (ps == null) return null; 3459 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3460 userId); 3461 } 3462 if (mResolveComponentName.equals(component)) { 3463 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3464 new PackageUserState(), userId); 3465 } 3466 } 3467 return null; 3468 } 3469 3470 @Override 3471 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3472 String resolvedType) { 3473 synchronized (mPackages) { 3474 if (component.equals(mResolveComponentName)) { 3475 // The resolver supports EVERYTHING! 3476 return true; 3477 } 3478 PackageParser.Activity a = mActivities.mActivities.get(component); 3479 if (a == null) { 3480 return false; 3481 } 3482 for (int i=0; i<a.intents.size(); i++) { 3483 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3484 intent.getData(), intent.getCategories(), TAG) >= 0) { 3485 return true; 3486 } 3487 } 3488 return false; 3489 } 3490 } 3491 3492 @Override 3493 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3494 if (!sUserManager.exists(userId)) return null; 3495 flags = updateFlagsForComponent(flags, userId, component); 3496 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3497 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3498 synchronized (mPackages) { 3499 PackageParser.Activity a = mReceivers.mActivities.get(component); 3500 if (DEBUG_PACKAGE_INFO) Log.v( 3501 TAG, "getReceiverInfo " + component + ": " + a); 3502 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3503 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3504 if (ps == null) return null; 3505 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3506 userId); 3507 } 3508 } 3509 return null; 3510 } 3511 3512 @Override 3513 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3514 if (!sUserManager.exists(userId)) return null; 3515 flags = updateFlagsForComponent(flags, userId, component); 3516 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3517 false /* requireFullPermission */, false /* checkShell */, "get service info"); 3518 synchronized (mPackages) { 3519 PackageParser.Service s = mServices.mServices.get(component); 3520 if (DEBUG_PACKAGE_INFO) Log.v( 3521 TAG, "getServiceInfo " + component + ": " + s); 3522 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3523 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3524 if (ps == null) return null; 3525 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3526 userId); 3527 } 3528 } 3529 return null; 3530 } 3531 3532 @Override 3533 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3534 if (!sUserManager.exists(userId)) return null; 3535 flags = updateFlagsForComponent(flags, userId, component); 3536 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3537 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 3538 synchronized (mPackages) { 3539 PackageParser.Provider p = mProviders.mProviders.get(component); 3540 if (DEBUG_PACKAGE_INFO) Log.v( 3541 TAG, "getProviderInfo " + component + ": " + p); 3542 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3543 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3544 if (ps == null) return null; 3545 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3546 userId); 3547 } 3548 } 3549 return null; 3550 } 3551 3552 @Override 3553 public String[] getSystemSharedLibraryNames() { 3554 Set<String> libSet; 3555 synchronized (mPackages) { 3556 libSet = mSharedLibraries.keySet(); 3557 int size = libSet.size(); 3558 if (size > 0) { 3559 String[] libs = new String[size]; 3560 libSet.toArray(libs); 3561 return libs; 3562 } 3563 } 3564 return null; 3565 } 3566 3567 @Override 3568 public @Nullable String getServicesSystemSharedLibraryPackageName() { 3569 synchronized (mPackages) { 3570 SharedLibraryEntry libraryEntry = mSharedLibraries.get( 3571 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 3572 if (libraryEntry != null) { 3573 return libraryEntry.apk; 3574 } 3575 } 3576 return null; 3577 } 3578 3579 @Override 3580 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 3581 synchronized (mPackages) { 3582 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values()); 3583 3584 final FeatureInfo fi = new FeatureInfo(); 3585 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3586 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3587 res.add(fi); 3588 3589 return new ParceledListSlice<>(res); 3590 } 3591 } 3592 3593 @Override 3594 public boolean hasSystemFeature(String name, int version) { 3595 synchronized (mPackages) { 3596 final FeatureInfo feat = mAvailableFeatures.get(name); 3597 if (feat == null) { 3598 return false; 3599 } else { 3600 return feat.version >= version; 3601 } 3602 } 3603 } 3604 3605 @Override 3606 public int checkPermission(String permName, String pkgName, int userId) { 3607 if (!sUserManager.exists(userId)) { 3608 return PackageManager.PERMISSION_DENIED; 3609 } 3610 3611 synchronized (mPackages) { 3612 final PackageParser.Package p = mPackages.get(pkgName); 3613 if (p != null && p.mExtras != null) { 3614 final PackageSetting ps = (PackageSetting) p.mExtras; 3615 final PermissionsState permissionsState = ps.getPermissionsState(); 3616 if (permissionsState.hasPermission(permName, userId)) { 3617 return PackageManager.PERMISSION_GRANTED; 3618 } 3619 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3620 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3621 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3622 return PackageManager.PERMISSION_GRANTED; 3623 } 3624 } 3625 } 3626 3627 return PackageManager.PERMISSION_DENIED; 3628 } 3629 3630 @Override 3631 public int checkUidPermission(String permName, int uid) { 3632 final int userId = UserHandle.getUserId(uid); 3633 3634 if (!sUserManager.exists(userId)) { 3635 return PackageManager.PERMISSION_DENIED; 3636 } 3637 3638 synchronized (mPackages) { 3639 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3640 if (obj != null) { 3641 final SettingBase ps = (SettingBase) obj; 3642 final PermissionsState permissionsState = ps.getPermissionsState(); 3643 if (permissionsState.hasPermission(permName, userId)) { 3644 return PackageManager.PERMISSION_GRANTED; 3645 } 3646 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3647 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3648 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3649 return PackageManager.PERMISSION_GRANTED; 3650 } 3651 } else { 3652 ArraySet<String> perms = mSystemPermissions.get(uid); 3653 if (perms != null) { 3654 if (perms.contains(permName)) { 3655 return PackageManager.PERMISSION_GRANTED; 3656 } 3657 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3658 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3659 return PackageManager.PERMISSION_GRANTED; 3660 } 3661 } 3662 } 3663 } 3664 3665 return PackageManager.PERMISSION_DENIED; 3666 } 3667 3668 @Override 3669 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3670 if (UserHandle.getCallingUserId() != userId) { 3671 mContext.enforceCallingPermission( 3672 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3673 "isPermissionRevokedByPolicy for user " + userId); 3674 } 3675 3676 if (checkPermission(permission, packageName, userId) 3677 == PackageManager.PERMISSION_GRANTED) { 3678 return false; 3679 } 3680 3681 final long identity = Binder.clearCallingIdentity(); 3682 try { 3683 final int flags = getPermissionFlags(permission, packageName, userId); 3684 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3685 } finally { 3686 Binder.restoreCallingIdentity(identity); 3687 } 3688 } 3689 3690 @Override 3691 public String getPermissionControllerPackageName() { 3692 synchronized (mPackages) { 3693 return mRequiredInstallerPackage; 3694 } 3695 } 3696 3697 /** 3698 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3699 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3700 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3701 * @param message the message to log on security exception 3702 */ 3703 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3704 boolean checkShell, String message) { 3705 if (userId < 0) { 3706 throw new IllegalArgumentException("Invalid userId " + userId); 3707 } 3708 if (checkShell) { 3709 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3710 } 3711 if (userId == UserHandle.getUserId(callingUid)) return; 3712 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3713 if (requireFullPermission) { 3714 mContext.enforceCallingOrSelfPermission( 3715 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3716 } else { 3717 try { 3718 mContext.enforceCallingOrSelfPermission( 3719 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3720 } catch (SecurityException se) { 3721 mContext.enforceCallingOrSelfPermission( 3722 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3723 } 3724 } 3725 } 3726 } 3727 3728 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3729 if (callingUid == Process.SHELL_UID) { 3730 if (userHandle >= 0 3731 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3732 throw new SecurityException("Shell does not have permission to access user " 3733 + userHandle); 3734 } else if (userHandle < 0) { 3735 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3736 + Debug.getCallers(3)); 3737 } 3738 } 3739 } 3740 3741 private BasePermission findPermissionTreeLP(String permName) { 3742 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3743 if (permName.startsWith(bp.name) && 3744 permName.length() > bp.name.length() && 3745 permName.charAt(bp.name.length()) == '.') { 3746 return bp; 3747 } 3748 } 3749 return null; 3750 } 3751 3752 private BasePermission checkPermissionTreeLP(String permName) { 3753 if (permName != null) { 3754 BasePermission bp = findPermissionTreeLP(permName); 3755 if (bp != null) { 3756 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3757 return bp; 3758 } 3759 throw new SecurityException("Calling uid " 3760 + Binder.getCallingUid() 3761 + " is not allowed to add to permission tree " 3762 + bp.name + " owned by uid " + bp.uid); 3763 } 3764 } 3765 throw new SecurityException("No permission tree found for " + permName); 3766 } 3767 3768 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3769 if (s1 == null) { 3770 return s2 == null; 3771 } 3772 if (s2 == null) { 3773 return false; 3774 } 3775 if (s1.getClass() != s2.getClass()) { 3776 return false; 3777 } 3778 return s1.equals(s2); 3779 } 3780 3781 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3782 if (pi1.icon != pi2.icon) return false; 3783 if (pi1.logo != pi2.logo) return false; 3784 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3785 if (!compareStrings(pi1.name, pi2.name)) return false; 3786 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3787 // We'll take care of setting this one. 3788 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3789 // These are not currently stored in settings. 3790 //if (!compareStrings(pi1.group, pi2.group)) return false; 3791 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3792 //if (pi1.labelRes != pi2.labelRes) return false; 3793 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3794 return true; 3795 } 3796 3797 int permissionInfoFootprint(PermissionInfo info) { 3798 int size = info.name.length(); 3799 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3800 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3801 return size; 3802 } 3803 3804 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3805 int size = 0; 3806 for (BasePermission perm : mSettings.mPermissions.values()) { 3807 if (perm.uid == tree.uid) { 3808 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3809 } 3810 } 3811 return size; 3812 } 3813 3814 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3815 // We calculate the max size of permissions defined by this uid and throw 3816 // if that plus the size of 'info' would exceed our stated maximum. 3817 if (tree.uid != Process.SYSTEM_UID) { 3818 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3819 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3820 throw new SecurityException("Permission tree size cap exceeded"); 3821 } 3822 } 3823 } 3824 3825 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3826 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3827 throw new SecurityException("Label must be specified in permission"); 3828 } 3829 BasePermission tree = checkPermissionTreeLP(info.name); 3830 BasePermission bp = mSettings.mPermissions.get(info.name); 3831 boolean added = bp == null; 3832 boolean changed = true; 3833 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3834 if (added) { 3835 enforcePermissionCapLocked(info, tree); 3836 bp = new BasePermission(info.name, tree.sourcePackage, 3837 BasePermission.TYPE_DYNAMIC); 3838 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3839 throw new SecurityException( 3840 "Not allowed to modify non-dynamic permission " 3841 + info.name); 3842 } else { 3843 if (bp.protectionLevel == fixedLevel 3844 && bp.perm.owner.equals(tree.perm.owner) 3845 && bp.uid == tree.uid 3846 && comparePermissionInfos(bp.perm.info, info)) { 3847 changed = false; 3848 } 3849 } 3850 bp.protectionLevel = fixedLevel; 3851 info = new PermissionInfo(info); 3852 info.protectionLevel = fixedLevel; 3853 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3854 bp.perm.info.packageName = tree.perm.info.packageName; 3855 bp.uid = tree.uid; 3856 if (added) { 3857 mSettings.mPermissions.put(info.name, bp); 3858 } 3859 if (changed) { 3860 if (!async) { 3861 mSettings.writeLPr(); 3862 } else { 3863 scheduleWriteSettingsLocked(); 3864 } 3865 } 3866 return added; 3867 } 3868 3869 @Override 3870 public boolean addPermission(PermissionInfo info) { 3871 synchronized (mPackages) { 3872 return addPermissionLocked(info, false); 3873 } 3874 } 3875 3876 @Override 3877 public boolean addPermissionAsync(PermissionInfo info) { 3878 synchronized (mPackages) { 3879 return addPermissionLocked(info, true); 3880 } 3881 } 3882 3883 @Override 3884 public void removePermission(String name) { 3885 synchronized (mPackages) { 3886 checkPermissionTreeLP(name); 3887 BasePermission bp = mSettings.mPermissions.get(name); 3888 if (bp != null) { 3889 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3890 throw new SecurityException( 3891 "Not allowed to modify non-dynamic permission " 3892 + name); 3893 } 3894 mSettings.mPermissions.remove(name); 3895 mSettings.writeLPr(); 3896 } 3897 } 3898 } 3899 3900 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 3901 BasePermission bp) { 3902 int index = pkg.requestedPermissions.indexOf(bp.name); 3903 if (index == -1) { 3904 throw new SecurityException("Package " + pkg.packageName 3905 + " has not requested permission " + bp.name); 3906 } 3907 if (!bp.isRuntime() && !bp.isDevelopment()) { 3908 throw new SecurityException("Permission " + bp.name 3909 + " is not a changeable permission type"); 3910 } 3911 } 3912 3913 @Override 3914 public void grantRuntimePermission(String packageName, String name, final int userId) { 3915 if (!sUserManager.exists(userId)) { 3916 Log.e(TAG, "No such user:" + userId); 3917 return; 3918 } 3919 3920 mContext.enforceCallingOrSelfPermission( 3921 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 3922 "grantRuntimePermission"); 3923 3924 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3925 true /* requireFullPermission */, true /* checkShell */, 3926 "grantRuntimePermission"); 3927 3928 final int uid; 3929 final SettingBase sb; 3930 3931 synchronized (mPackages) { 3932 final PackageParser.Package pkg = mPackages.get(packageName); 3933 if (pkg == null) { 3934 throw new IllegalArgumentException("Unknown package: " + packageName); 3935 } 3936 3937 final BasePermission bp = mSettings.mPermissions.get(name); 3938 if (bp == null) { 3939 throw new IllegalArgumentException("Unknown permission: " + name); 3940 } 3941 3942 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3943 3944 // If a permission review is required for legacy apps we represent 3945 // their permissions as always granted runtime ones since we need 3946 // to keep the review required permission flag per user while an 3947 // install permission's state is shared across all users. 3948 if (Build.PERMISSIONS_REVIEW_REQUIRED 3949 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 3950 && bp.isRuntime()) { 3951 return; 3952 } 3953 3954 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3955 sb = (SettingBase) pkg.mExtras; 3956 if (sb == null) { 3957 throw new IllegalArgumentException("Unknown package: " + packageName); 3958 } 3959 3960 final PermissionsState permissionsState = sb.getPermissionsState(); 3961 3962 final int flags = permissionsState.getPermissionFlags(name, userId); 3963 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3964 throw new SecurityException("Cannot grant system fixed permission " 3965 + name + " for package " + packageName); 3966 } 3967 3968 if (bp.isDevelopment()) { 3969 // Development permissions must be handled specially, since they are not 3970 // normal runtime permissions. For now they apply to all users. 3971 if (permissionsState.grantInstallPermission(bp) != 3972 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3973 scheduleWriteSettingsLocked(); 3974 } 3975 return; 3976 } 3977 3978 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 3979 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 3980 return; 3981 } 3982 3983 final int result = permissionsState.grantRuntimePermission(bp, userId); 3984 switch (result) { 3985 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3986 return; 3987 } 3988 3989 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3990 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3991 mHandler.post(new Runnable() { 3992 @Override 3993 public void run() { 3994 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 3995 } 3996 }); 3997 } 3998 break; 3999 } 4000 4001 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4002 4003 // Not critical if that is lost - app has to request again. 4004 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4005 } 4006 4007 // Only need to do this if user is initialized. Otherwise it's a new user 4008 // and there are no processes running as the user yet and there's no need 4009 // to make an expensive call to remount processes for the changed permissions. 4010 if (READ_EXTERNAL_STORAGE.equals(name) 4011 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4012 final long token = Binder.clearCallingIdentity(); 4013 try { 4014 if (sUserManager.isInitialized(userId)) { 4015 MountServiceInternal mountServiceInternal = LocalServices.getService( 4016 MountServiceInternal.class); 4017 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 4018 } 4019 } finally { 4020 Binder.restoreCallingIdentity(token); 4021 } 4022 } 4023 } 4024 4025 @Override 4026 public void revokeRuntimePermission(String packageName, String name, int userId) { 4027 if (!sUserManager.exists(userId)) { 4028 Log.e(TAG, "No such user:" + userId); 4029 return; 4030 } 4031 4032 mContext.enforceCallingOrSelfPermission( 4033 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4034 "revokeRuntimePermission"); 4035 4036 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4037 true /* requireFullPermission */, true /* checkShell */, 4038 "revokeRuntimePermission"); 4039 4040 final int appId; 4041 4042 synchronized (mPackages) { 4043 final PackageParser.Package pkg = mPackages.get(packageName); 4044 if (pkg == null) { 4045 throw new IllegalArgumentException("Unknown package: " + packageName); 4046 } 4047 4048 final BasePermission bp = mSettings.mPermissions.get(name); 4049 if (bp == null) { 4050 throw new IllegalArgumentException("Unknown permission: " + name); 4051 } 4052 4053 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4054 4055 // If a permission review is required for legacy apps we represent 4056 // their permissions as always granted runtime ones since we need 4057 // to keep the review required permission flag per user while an 4058 // install permission's state is shared across all users. 4059 if (Build.PERMISSIONS_REVIEW_REQUIRED 4060 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4061 && bp.isRuntime()) { 4062 return; 4063 } 4064 4065 SettingBase sb = (SettingBase) pkg.mExtras; 4066 if (sb == null) { 4067 throw new IllegalArgumentException("Unknown package: " + packageName); 4068 } 4069 4070 final PermissionsState permissionsState = sb.getPermissionsState(); 4071 4072 final int flags = permissionsState.getPermissionFlags(name, userId); 4073 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4074 throw new SecurityException("Cannot revoke system fixed permission " 4075 + name + " for package " + packageName); 4076 } 4077 4078 if (bp.isDevelopment()) { 4079 // Development permissions must be handled specially, since they are not 4080 // normal runtime permissions. For now they apply to all users. 4081 if (permissionsState.revokeInstallPermission(bp) != 4082 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4083 scheduleWriteSettingsLocked(); 4084 } 4085 return; 4086 } 4087 4088 if (permissionsState.revokeRuntimePermission(bp, userId) == 4089 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4090 return; 4091 } 4092 4093 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4094 4095 // Critical, after this call app should never have the permission. 4096 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4097 4098 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4099 } 4100 4101 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4102 } 4103 4104 @Override 4105 public void resetRuntimePermissions() { 4106 mContext.enforceCallingOrSelfPermission( 4107 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4108 "revokeRuntimePermission"); 4109 4110 int callingUid = Binder.getCallingUid(); 4111 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4112 mContext.enforceCallingOrSelfPermission( 4113 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4114 "resetRuntimePermissions"); 4115 } 4116 4117 synchronized (mPackages) { 4118 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4119 for (int userId : UserManagerService.getInstance().getUserIds()) { 4120 final int packageCount = mPackages.size(); 4121 for (int i = 0; i < packageCount; i++) { 4122 PackageParser.Package pkg = mPackages.valueAt(i); 4123 if (!(pkg.mExtras instanceof PackageSetting)) { 4124 continue; 4125 } 4126 PackageSetting ps = (PackageSetting) pkg.mExtras; 4127 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4128 } 4129 } 4130 } 4131 } 4132 4133 @Override 4134 public int getPermissionFlags(String name, String packageName, int userId) { 4135 if (!sUserManager.exists(userId)) { 4136 return 0; 4137 } 4138 4139 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4140 4141 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4142 true /* requireFullPermission */, false /* checkShell */, 4143 "getPermissionFlags"); 4144 4145 synchronized (mPackages) { 4146 final PackageParser.Package pkg = mPackages.get(packageName); 4147 if (pkg == null) { 4148 throw new IllegalArgumentException("Unknown package: " + packageName); 4149 } 4150 4151 final BasePermission bp = mSettings.mPermissions.get(name); 4152 if (bp == null) { 4153 throw new IllegalArgumentException("Unknown permission: " + name); 4154 } 4155 4156 SettingBase sb = (SettingBase) pkg.mExtras; 4157 if (sb == null) { 4158 throw new IllegalArgumentException("Unknown package: " + packageName); 4159 } 4160 4161 PermissionsState permissionsState = sb.getPermissionsState(); 4162 return permissionsState.getPermissionFlags(name, userId); 4163 } 4164 } 4165 4166 @Override 4167 public void updatePermissionFlags(String name, String packageName, int flagMask, 4168 int flagValues, int userId) { 4169 if (!sUserManager.exists(userId)) { 4170 return; 4171 } 4172 4173 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4174 4175 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4176 true /* requireFullPermission */, true /* checkShell */, 4177 "updatePermissionFlags"); 4178 4179 // Only the system can change these flags and nothing else. 4180 if (getCallingUid() != Process.SYSTEM_UID) { 4181 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4182 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4183 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4184 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4185 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4186 } 4187 4188 synchronized (mPackages) { 4189 final PackageParser.Package pkg = mPackages.get(packageName); 4190 if (pkg == null) { 4191 throw new IllegalArgumentException("Unknown package: " + packageName); 4192 } 4193 4194 final BasePermission bp = mSettings.mPermissions.get(name); 4195 if (bp == null) { 4196 throw new IllegalArgumentException("Unknown permission: " + name); 4197 } 4198 4199 SettingBase sb = (SettingBase) pkg.mExtras; 4200 if (sb == null) { 4201 throw new IllegalArgumentException("Unknown package: " + packageName); 4202 } 4203 4204 PermissionsState permissionsState = sb.getPermissionsState(); 4205 4206 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4207 4208 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4209 // Install and runtime permissions are stored in different places, 4210 // so figure out what permission changed and persist the change. 4211 if (permissionsState.getInstallPermissionState(name) != null) { 4212 scheduleWriteSettingsLocked(); 4213 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4214 || hadState) { 4215 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4216 } 4217 } 4218 } 4219 } 4220 4221 /** 4222 * Update the permission flags for all packages and runtime permissions of a user in order 4223 * to allow device or profile owner to remove POLICY_FIXED. 4224 */ 4225 @Override 4226 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4227 if (!sUserManager.exists(userId)) { 4228 return; 4229 } 4230 4231 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4232 4233 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4234 true /* requireFullPermission */, true /* checkShell */, 4235 "updatePermissionFlagsForAllApps"); 4236 4237 // Only the system can change system fixed flags. 4238 if (getCallingUid() != Process.SYSTEM_UID) { 4239 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4240 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4241 } 4242 4243 synchronized (mPackages) { 4244 boolean changed = false; 4245 final int packageCount = mPackages.size(); 4246 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4247 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4248 SettingBase sb = (SettingBase) pkg.mExtras; 4249 if (sb == null) { 4250 continue; 4251 } 4252 PermissionsState permissionsState = sb.getPermissionsState(); 4253 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4254 userId, flagMask, flagValues); 4255 } 4256 if (changed) { 4257 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4258 } 4259 } 4260 } 4261 4262 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4263 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4264 != PackageManager.PERMISSION_GRANTED 4265 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4266 != PackageManager.PERMISSION_GRANTED) { 4267 throw new SecurityException(message + " requires " 4268 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4269 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4270 } 4271 } 4272 4273 @Override 4274 public boolean shouldShowRequestPermissionRationale(String permissionName, 4275 String packageName, int userId) { 4276 if (UserHandle.getCallingUserId() != userId) { 4277 mContext.enforceCallingPermission( 4278 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4279 "canShowRequestPermissionRationale for user " + userId); 4280 } 4281 4282 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4283 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4284 return false; 4285 } 4286 4287 if (checkPermission(permissionName, packageName, userId) 4288 == PackageManager.PERMISSION_GRANTED) { 4289 return false; 4290 } 4291 4292 final int flags; 4293 4294 final long identity = Binder.clearCallingIdentity(); 4295 try { 4296 flags = getPermissionFlags(permissionName, 4297 packageName, userId); 4298 } finally { 4299 Binder.restoreCallingIdentity(identity); 4300 } 4301 4302 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4303 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4304 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4305 4306 if ((flags & fixedFlags) != 0) { 4307 return false; 4308 } 4309 4310 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4311 } 4312 4313 @Override 4314 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4315 mContext.enforceCallingOrSelfPermission( 4316 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4317 "addOnPermissionsChangeListener"); 4318 4319 synchronized (mPackages) { 4320 mOnPermissionChangeListeners.addListenerLocked(listener); 4321 } 4322 } 4323 4324 @Override 4325 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4326 synchronized (mPackages) { 4327 mOnPermissionChangeListeners.removeListenerLocked(listener); 4328 } 4329 } 4330 4331 @Override 4332 public boolean isProtectedBroadcast(String actionName) { 4333 synchronized (mPackages) { 4334 if (mProtectedBroadcasts.contains(actionName)) { 4335 return true; 4336 } else if (actionName != null) { 4337 // TODO: remove these terrible hacks 4338 if (actionName.startsWith("android.net.netmon.lingerExpired") 4339 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4340 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 4341 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 4342 return true; 4343 } 4344 } 4345 } 4346 return false; 4347 } 4348 4349 @Override 4350 public int checkSignatures(String pkg1, String pkg2) { 4351 synchronized (mPackages) { 4352 final PackageParser.Package p1 = mPackages.get(pkg1); 4353 final PackageParser.Package p2 = mPackages.get(pkg2); 4354 if (p1 == null || p1.mExtras == null 4355 || p2 == null || p2.mExtras == null) { 4356 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4357 } 4358 return compareSignatures(p1.mSignatures, p2.mSignatures); 4359 } 4360 } 4361 4362 @Override 4363 public int checkUidSignatures(int uid1, int uid2) { 4364 // Map to base uids. 4365 uid1 = UserHandle.getAppId(uid1); 4366 uid2 = UserHandle.getAppId(uid2); 4367 // reader 4368 synchronized (mPackages) { 4369 Signature[] s1; 4370 Signature[] s2; 4371 Object obj = mSettings.getUserIdLPr(uid1); 4372 if (obj != null) { 4373 if (obj instanceof SharedUserSetting) { 4374 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4375 } else if (obj instanceof PackageSetting) { 4376 s1 = ((PackageSetting)obj).signatures.mSignatures; 4377 } else { 4378 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4379 } 4380 } else { 4381 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4382 } 4383 obj = mSettings.getUserIdLPr(uid2); 4384 if (obj != null) { 4385 if (obj instanceof SharedUserSetting) { 4386 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4387 } else if (obj instanceof PackageSetting) { 4388 s2 = ((PackageSetting)obj).signatures.mSignatures; 4389 } else { 4390 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4391 } 4392 } else { 4393 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4394 } 4395 return compareSignatures(s1, s2); 4396 } 4397 } 4398 4399 private void killUid(int appId, int userId, String reason) { 4400 final long identity = Binder.clearCallingIdentity(); 4401 try { 4402 IActivityManager am = ActivityManagerNative.getDefault(); 4403 if (am != null) { 4404 try { 4405 am.killUid(appId, userId, reason); 4406 } catch (RemoteException e) { 4407 /* ignore - same process */ 4408 } 4409 } 4410 } finally { 4411 Binder.restoreCallingIdentity(identity); 4412 } 4413 } 4414 4415 /** 4416 * Compares two sets of signatures. Returns: 4417 * <br /> 4418 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4419 * <br /> 4420 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4421 * <br /> 4422 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4423 * <br /> 4424 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4425 * <br /> 4426 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4427 */ 4428 static int compareSignatures(Signature[] s1, Signature[] s2) { 4429 if (s1 == null) { 4430 return s2 == null 4431 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4432 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4433 } 4434 4435 if (s2 == null) { 4436 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4437 } 4438 4439 if (s1.length != s2.length) { 4440 return PackageManager.SIGNATURE_NO_MATCH; 4441 } 4442 4443 // Since both signature sets are of size 1, we can compare without HashSets. 4444 if (s1.length == 1) { 4445 return s1[0].equals(s2[0]) ? 4446 PackageManager.SIGNATURE_MATCH : 4447 PackageManager.SIGNATURE_NO_MATCH; 4448 } 4449 4450 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4451 for (Signature sig : s1) { 4452 set1.add(sig); 4453 } 4454 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4455 for (Signature sig : s2) { 4456 set2.add(sig); 4457 } 4458 // Make sure s2 contains all signatures in s1. 4459 if (set1.equals(set2)) { 4460 return PackageManager.SIGNATURE_MATCH; 4461 } 4462 return PackageManager.SIGNATURE_NO_MATCH; 4463 } 4464 4465 /** 4466 * If the database version for this type of package (internal storage or 4467 * external storage) is less than the version where package signatures 4468 * were updated, return true. 4469 */ 4470 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4471 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4472 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4473 } 4474 4475 /** 4476 * Used for backward compatibility to make sure any packages with 4477 * certificate chains get upgraded to the new style. {@code existingSigs} 4478 * will be in the old format (since they were stored on disk from before the 4479 * system upgrade) and {@code scannedSigs} will be in the newer format. 4480 */ 4481 private int compareSignaturesCompat(PackageSignatures existingSigs, 4482 PackageParser.Package scannedPkg) { 4483 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4484 return PackageManager.SIGNATURE_NO_MATCH; 4485 } 4486 4487 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4488 for (Signature sig : existingSigs.mSignatures) { 4489 existingSet.add(sig); 4490 } 4491 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4492 for (Signature sig : scannedPkg.mSignatures) { 4493 try { 4494 Signature[] chainSignatures = sig.getChainSignatures(); 4495 for (Signature chainSig : chainSignatures) { 4496 scannedCompatSet.add(chainSig); 4497 } 4498 } catch (CertificateEncodingException e) { 4499 scannedCompatSet.add(sig); 4500 } 4501 } 4502 /* 4503 * Make sure the expanded scanned set contains all signatures in the 4504 * existing one. 4505 */ 4506 if (scannedCompatSet.equals(existingSet)) { 4507 // Migrate the old signatures to the new scheme. 4508 existingSigs.assignSignatures(scannedPkg.mSignatures); 4509 // The new KeySets will be re-added later in the scanning process. 4510 synchronized (mPackages) { 4511 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4512 } 4513 return PackageManager.SIGNATURE_MATCH; 4514 } 4515 return PackageManager.SIGNATURE_NO_MATCH; 4516 } 4517 4518 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4519 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4520 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4521 } 4522 4523 private int compareSignaturesRecover(PackageSignatures existingSigs, 4524 PackageParser.Package scannedPkg) { 4525 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4526 return PackageManager.SIGNATURE_NO_MATCH; 4527 } 4528 4529 String msg = null; 4530 try { 4531 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4532 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4533 + scannedPkg.packageName); 4534 return PackageManager.SIGNATURE_MATCH; 4535 } 4536 } catch (CertificateException e) { 4537 msg = e.getMessage(); 4538 } 4539 4540 logCriticalInfo(Log.INFO, 4541 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4542 return PackageManager.SIGNATURE_NO_MATCH; 4543 } 4544 4545 @Override 4546 public List<String> getAllPackages() { 4547 synchronized (mPackages) { 4548 return new ArrayList<String>(mPackages.keySet()); 4549 } 4550 } 4551 4552 @Override 4553 public String[] getPackagesForUid(int uid) { 4554 uid = UserHandle.getAppId(uid); 4555 // reader 4556 synchronized (mPackages) { 4557 Object obj = mSettings.getUserIdLPr(uid); 4558 if (obj instanceof SharedUserSetting) { 4559 final SharedUserSetting sus = (SharedUserSetting) obj; 4560 final int N = sus.packages.size(); 4561 final String[] res = new String[N]; 4562 final Iterator<PackageSetting> it = sus.packages.iterator(); 4563 int i = 0; 4564 while (it.hasNext()) { 4565 res[i++] = it.next().name; 4566 } 4567 return res; 4568 } else if (obj instanceof PackageSetting) { 4569 final PackageSetting ps = (PackageSetting) obj; 4570 return new String[] { ps.name }; 4571 } 4572 } 4573 return null; 4574 } 4575 4576 @Override 4577 public String getNameForUid(int uid) { 4578 // reader 4579 synchronized (mPackages) { 4580 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4581 if (obj instanceof SharedUserSetting) { 4582 final SharedUserSetting sus = (SharedUserSetting) obj; 4583 return sus.name + ":" + sus.userId; 4584 } else if (obj instanceof PackageSetting) { 4585 final PackageSetting ps = (PackageSetting) obj; 4586 return ps.name; 4587 } 4588 } 4589 return null; 4590 } 4591 4592 @Override 4593 public int getUidForSharedUser(String sharedUserName) { 4594 if(sharedUserName == null) { 4595 return -1; 4596 } 4597 // reader 4598 synchronized (mPackages) { 4599 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4600 if (suid == null) { 4601 return -1; 4602 } 4603 return suid.userId; 4604 } 4605 } 4606 4607 @Override 4608 public int getFlagsForUid(int uid) { 4609 synchronized (mPackages) { 4610 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4611 if (obj instanceof SharedUserSetting) { 4612 final SharedUserSetting sus = (SharedUserSetting) obj; 4613 return sus.pkgFlags; 4614 } else if (obj instanceof PackageSetting) { 4615 final PackageSetting ps = (PackageSetting) obj; 4616 return ps.pkgFlags; 4617 } 4618 } 4619 return 0; 4620 } 4621 4622 @Override 4623 public int getPrivateFlagsForUid(int uid) { 4624 synchronized (mPackages) { 4625 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4626 if (obj instanceof SharedUserSetting) { 4627 final SharedUserSetting sus = (SharedUserSetting) obj; 4628 return sus.pkgPrivateFlags; 4629 } else if (obj instanceof PackageSetting) { 4630 final PackageSetting ps = (PackageSetting) obj; 4631 return ps.pkgPrivateFlags; 4632 } 4633 } 4634 return 0; 4635 } 4636 4637 @Override 4638 public boolean isUidPrivileged(int uid) { 4639 uid = UserHandle.getAppId(uid); 4640 // reader 4641 synchronized (mPackages) { 4642 Object obj = mSettings.getUserIdLPr(uid); 4643 if (obj instanceof SharedUserSetting) { 4644 final SharedUserSetting sus = (SharedUserSetting) obj; 4645 final Iterator<PackageSetting> it = sus.packages.iterator(); 4646 while (it.hasNext()) { 4647 if (it.next().isPrivileged()) { 4648 return true; 4649 } 4650 } 4651 } else if (obj instanceof PackageSetting) { 4652 final PackageSetting ps = (PackageSetting) obj; 4653 return ps.isPrivileged(); 4654 } 4655 } 4656 return false; 4657 } 4658 4659 @Override 4660 public String[] getAppOpPermissionPackages(String permissionName) { 4661 synchronized (mPackages) { 4662 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4663 if (pkgs == null) { 4664 return null; 4665 } 4666 return pkgs.toArray(new String[pkgs.size()]); 4667 } 4668 } 4669 4670 @Override 4671 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4672 int flags, int userId) { 4673 if (!sUserManager.exists(userId)) return null; 4674 flags = updateFlagsForResolve(flags, userId, intent); 4675 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4676 false /* requireFullPermission */, false /* checkShell */, "resolve intent"); 4677 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4678 userId); 4679 final ResolveInfo bestChoice = 4680 chooseBestActivity(intent, resolvedType, flags, query, userId); 4681 4682 if (isEphemeralAllowed(intent, query, userId)) { 4683 final EphemeralResolveInfo ai = 4684 getEphemeralResolveInfo(intent, resolvedType, userId); 4685 if (ai != null) { 4686 if (DEBUG_EPHEMERAL) { 4687 Slog.v(TAG, "Returning an EphemeralResolveInfo"); 4688 } 4689 bestChoice.ephemeralInstaller = mEphemeralInstallerInfo; 4690 bestChoice.ephemeralResolveInfo = ai; 4691 } 4692 } 4693 return bestChoice; 4694 } 4695 4696 @Override 4697 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4698 IntentFilter filter, int match, ComponentName activity) { 4699 final int userId = UserHandle.getCallingUserId(); 4700 if (DEBUG_PREFERRED) { 4701 Log.v(TAG, "setLastChosenActivity intent=" + intent 4702 + " resolvedType=" + resolvedType 4703 + " flags=" + flags 4704 + " filter=" + filter 4705 + " match=" + match 4706 + " activity=" + activity); 4707 filter.dump(new PrintStreamPrinter(System.out), " "); 4708 } 4709 intent.setComponent(null); 4710 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4711 userId); 4712 // Find any earlier preferred or last chosen entries and nuke them 4713 findPreferredActivity(intent, resolvedType, 4714 flags, query, 0, false, true, false, userId); 4715 // Add the new activity as the last chosen for this filter 4716 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4717 "Setting last chosen"); 4718 } 4719 4720 @Override 4721 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4722 final int userId = UserHandle.getCallingUserId(); 4723 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4724 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4725 userId); 4726 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4727 false, false, false, userId); 4728 } 4729 4730 4731 private boolean isEphemeralAllowed( 4732 Intent intent, List<ResolveInfo> resolvedActivites, int userId) { 4733 // Short circuit and return early if possible. 4734 if (DISABLE_EPHEMERAL_APPS) { 4735 return false; 4736 } 4737 final int callingUser = UserHandle.getCallingUserId(); 4738 if (callingUser != UserHandle.USER_SYSTEM) { 4739 return false; 4740 } 4741 if (mEphemeralResolverConnection == null) { 4742 return false; 4743 } 4744 if (intent.getComponent() != null) { 4745 return false; 4746 } 4747 if (intent.getPackage() != null) { 4748 return false; 4749 } 4750 final boolean isWebUri = hasWebURI(intent); 4751 if (!isWebUri) { 4752 return false; 4753 } 4754 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4755 synchronized (mPackages) { 4756 final int count = resolvedActivites.size(); 4757 for (int n = 0; n < count; n++) { 4758 ResolveInfo info = resolvedActivites.get(n); 4759 String packageName = info.activityInfo.packageName; 4760 PackageSetting ps = mSettings.mPackages.get(packageName); 4761 if (ps != null) { 4762 // Try to get the status from User settings first 4763 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4764 int status = (int) (packedStatus >> 32); 4765 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4766 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4767 if (DEBUG_EPHEMERAL) { 4768 Slog.v(TAG, "DENY ephemeral apps;" 4769 + " pkg: " + packageName + ", status: " + status); 4770 } 4771 return false; 4772 } 4773 } 4774 } 4775 } 4776 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4777 return true; 4778 } 4779 4780 private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType, 4781 int userId) { 4782 MessageDigest digest = null; 4783 try { 4784 digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM); 4785 } catch (NoSuchAlgorithmException e) { 4786 // If we can't create a digest, ignore ephemeral apps. 4787 return null; 4788 } 4789 4790 final byte[] hostBytes = intent.getData().getHost().getBytes(); 4791 final byte[] digestBytes = digest.digest(hostBytes); 4792 int shaPrefix = 4793 digestBytes[0] << 24 4794 | digestBytes[1] << 16 4795 | digestBytes[2] << 8 4796 | digestBytes[3] << 0; 4797 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4798 mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix); 4799 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4800 // No hash prefix match; there are no ephemeral apps for this domain. 4801 return null; 4802 } 4803 for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) { 4804 EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i); 4805 if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) { 4806 continue; 4807 } 4808 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 4809 // No filters; this should never happen. 4810 if (filters.isEmpty()) { 4811 continue; 4812 } 4813 // We have a domain match; resolve the filters to see if anything matches. 4814 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4815 for (int j = filters.size() - 1; j >= 0; --j) { 4816 final EphemeralResolveIntentInfo intentInfo = 4817 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 4818 ephemeralResolver.addFilter(intentInfo); 4819 } 4820 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 4821 intent, resolvedType, false /*defaultOnly*/, userId); 4822 if (!matchedResolveInfoList.isEmpty()) { 4823 return matchedResolveInfoList.get(0); 4824 } 4825 } 4826 // Hash or filter mis-match; no ephemeral apps for this domain. 4827 return null; 4828 } 4829 4830 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4831 int flags, List<ResolveInfo> query, int userId) { 4832 if (query != null) { 4833 final int N = query.size(); 4834 if (N == 1) { 4835 return query.get(0); 4836 } else if (N > 1) { 4837 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4838 // If there is more than one activity with the same priority, 4839 // then let the user decide between them. 4840 ResolveInfo r0 = query.get(0); 4841 ResolveInfo r1 = query.get(1); 4842 if (DEBUG_INTENT_MATCHING || debug) { 4843 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4844 + r1.activityInfo.name + "=" + r1.priority); 4845 } 4846 // If the first activity has a higher priority, or a different 4847 // default, then it is always desirable to pick it. 4848 if (r0.priority != r1.priority 4849 || r0.preferredOrder != r1.preferredOrder 4850 || r0.isDefault != r1.isDefault) { 4851 return query.get(0); 4852 } 4853 // If we have saved a preference for a preferred activity for 4854 // this Intent, use that. 4855 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4856 flags, query, r0.priority, true, false, debug, userId); 4857 if (ri != null) { 4858 return ri; 4859 } 4860 ri = new ResolveInfo(mResolveInfo); 4861 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4862 ri.activityInfo.applicationInfo = new ApplicationInfo( 4863 ri.activityInfo.applicationInfo); 4864 if (userId != 0) { 4865 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4866 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4867 } 4868 // Make sure that the resolver is displayable in car mode 4869 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 4870 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 4871 return ri; 4872 } 4873 } 4874 return null; 4875 } 4876 4877 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4878 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4879 final int N = query.size(); 4880 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4881 .get(userId); 4882 // Get the list of persistent preferred activities that handle the intent 4883 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4884 List<PersistentPreferredActivity> pprefs = ppir != null 4885 ? ppir.queryIntent(intent, resolvedType, 4886 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4887 : null; 4888 if (pprefs != null && pprefs.size() > 0) { 4889 final int M = pprefs.size(); 4890 for (int i=0; i<M; i++) { 4891 final PersistentPreferredActivity ppa = pprefs.get(i); 4892 if (DEBUG_PREFERRED || debug) { 4893 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4894 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4895 + "\n component=" + ppa.mComponent); 4896 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4897 } 4898 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4899 flags | MATCH_DISABLED_COMPONENTS, userId); 4900 if (DEBUG_PREFERRED || debug) { 4901 Slog.v(TAG, "Found persistent preferred activity:"); 4902 if (ai != null) { 4903 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4904 } else { 4905 Slog.v(TAG, " null"); 4906 } 4907 } 4908 if (ai == null) { 4909 // This previously registered persistent preferred activity 4910 // component is no longer known. Ignore it and do NOT remove it. 4911 continue; 4912 } 4913 for (int j=0; j<N; j++) { 4914 final ResolveInfo ri = query.get(j); 4915 if (!ri.activityInfo.applicationInfo.packageName 4916 .equals(ai.applicationInfo.packageName)) { 4917 continue; 4918 } 4919 if (!ri.activityInfo.name.equals(ai.name)) { 4920 continue; 4921 } 4922 // Found a persistent preference that can handle the intent. 4923 if (DEBUG_PREFERRED || debug) { 4924 Slog.v(TAG, "Returning persistent preferred activity: " + 4925 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4926 } 4927 return ri; 4928 } 4929 } 4930 } 4931 return null; 4932 } 4933 4934 // TODO: handle preferred activities missing while user has amnesia 4935 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4936 List<ResolveInfo> query, int priority, boolean always, 4937 boolean removeMatches, boolean debug, int userId) { 4938 if (!sUserManager.exists(userId)) return null; 4939 flags = updateFlagsForResolve(flags, userId, intent); 4940 // writer 4941 synchronized (mPackages) { 4942 if (intent.getSelector() != null) { 4943 intent = intent.getSelector(); 4944 } 4945 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4946 4947 // Try to find a matching persistent preferred activity. 4948 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4949 debug, userId); 4950 4951 // If a persistent preferred activity matched, use it. 4952 if (pri != null) { 4953 return pri; 4954 } 4955 4956 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4957 // Get the list of preferred activities that handle the intent 4958 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4959 List<PreferredActivity> prefs = pir != null 4960 ? pir.queryIntent(intent, resolvedType, 4961 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4962 : null; 4963 if (prefs != null && prefs.size() > 0) { 4964 boolean changed = false; 4965 try { 4966 // First figure out how good the original match set is. 4967 // We will only allow preferred activities that came 4968 // from the same match quality. 4969 int match = 0; 4970 4971 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4972 4973 final int N = query.size(); 4974 for (int j=0; j<N; j++) { 4975 final ResolveInfo ri = query.get(j); 4976 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4977 + ": 0x" + Integer.toHexString(match)); 4978 if (ri.match > match) { 4979 match = ri.match; 4980 } 4981 } 4982 4983 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4984 + Integer.toHexString(match)); 4985 4986 match &= IntentFilter.MATCH_CATEGORY_MASK; 4987 final int M = prefs.size(); 4988 for (int i=0; i<M; i++) { 4989 final PreferredActivity pa = prefs.get(i); 4990 if (DEBUG_PREFERRED || debug) { 4991 Slog.v(TAG, "Checking PreferredActivity ds=" 4992 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4993 + "\n component=" + pa.mPref.mComponent); 4994 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4995 } 4996 if (pa.mPref.mMatch != match) { 4997 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4998 + Integer.toHexString(pa.mPref.mMatch)); 4999 continue; 5000 } 5001 // If it's not an "always" type preferred activity and that's what we're 5002 // looking for, skip it. 5003 if (always && !pa.mPref.mAlways) { 5004 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5005 continue; 5006 } 5007 final ActivityInfo ai = getActivityInfo( 5008 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5009 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5010 userId); 5011 if (DEBUG_PREFERRED || debug) { 5012 Slog.v(TAG, "Found preferred activity:"); 5013 if (ai != null) { 5014 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5015 } else { 5016 Slog.v(TAG, " null"); 5017 } 5018 } 5019 if (ai == null) { 5020 // This previously registered preferred activity 5021 // component is no longer known. Most likely an update 5022 // to the app was installed and in the new version this 5023 // component no longer exists. Clean it up by removing 5024 // it from the preferred activities list, and skip it. 5025 Slog.w(TAG, "Removing dangling preferred activity: " 5026 + pa.mPref.mComponent); 5027 pir.removeFilter(pa); 5028 changed = true; 5029 continue; 5030 } 5031 for (int j=0; j<N; j++) { 5032 final ResolveInfo ri = query.get(j); 5033 if (!ri.activityInfo.applicationInfo.packageName 5034 .equals(ai.applicationInfo.packageName)) { 5035 continue; 5036 } 5037 if (!ri.activityInfo.name.equals(ai.name)) { 5038 continue; 5039 } 5040 5041 if (removeMatches) { 5042 pir.removeFilter(pa); 5043 changed = true; 5044 if (DEBUG_PREFERRED) { 5045 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 5046 } 5047 break; 5048 } 5049 5050 // Okay we found a previously set preferred or last chosen app. 5051 // If the result set is different from when this 5052 // was created, we need to clear it and re-ask the 5053 // user their preference, if we're looking for an "always" type entry. 5054 if (always && !pa.mPref.sameSet(query)) { 5055 Slog.i(TAG, "Result set changed, dropping preferred activity for " 5056 + intent + " type " + resolvedType); 5057 if (DEBUG_PREFERRED) { 5058 Slog.v(TAG, "Removing preferred activity since set changed " 5059 + pa.mPref.mComponent); 5060 } 5061 pir.removeFilter(pa); 5062 // Re-add the filter as a "last chosen" entry (!always) 5063 PreferredActivity lastChosen = new PreferredActivity( 5064 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5065 pir.addFilter(lastChosen); 5066 changed = true; 5067 return null; 5068 } 5069 5070 // Yay! Either the set matched or we're looking for the last chosen 5071 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5072 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5073 return ri; 5074 } 5075 } 5076 } finally { 5077 if (changed) { 5078 if (DEBUG_PREFERRED) { 5079 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5080 } 5081 scheduleWritePackageRestrictionsLocked(userId); 5082 } 5083 } 5084 } 5085 } 5086 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5087 return null; 5088 } 5089 5090 /* 5091 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5092 */ 5093 @Override 5094 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5095 int targetUserId) { 5096 mContext.enforceCallingOrSelfPermission( 5097 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5098 List<CrossProfileIntentFilter> matches = 5099 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5100 if (matches != null) { 5101 int size = matches.size(); 5102 for (int i = 0; i < size; i++) { 5103 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5104 } 5105 } 5106 if (hasWebURI(intent)) { 5107 // cross-profile app linking works only towards the parent. 5108 final UserInfo parent = getProfileParent(sourceUserId); 5109 synchronized(mPackages) { 5110 int flags = updateFlagsForResolve(0, parent.id, intent); 5111 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5112 intent, resolvedType, flags, sourceUserId, parent.id); 5113 return xpDomainInfo != null; 5114 } 5115 } 5116 return false; 5117 } 5118 5119 private UserInfo getProfileParent(int userId) { 5120 final long identity = Binder.clearCallingIdentity(); 5121 try { 5122 return sUserManager.getProfileParent(userId); 5123 } finally { 5124 Binder.restoreCallingIdentity(identity); 5125 } 5126 } 5127 5128 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5129 String resolvedType, int userId) { 5130 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5131 if (resolver != null) { 5132 return resolver.queryIntent(intent, resolvedType, false, userId); 5133 } 5134 return null; 5135 } 5136 5137 @Override 5138 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5139 String resolvedType, int flags, int userId) { 5140 return new ParceledListSlice<>( 5141 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5142 } 5143 5144 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5145 String resolvedType, int flags, int userId) { 5146 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5147 flags = updateFlagsForResolve(flags, userId, intent); 5148 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5149 false /* requireFullPermission */, false /* checkShell */, 5150 "query intent activities"); 5151 ComponentName comp = intent.getComponent(); 5152 if (comp == null) { 5153 if (intent.getSelector() != null) { 5154 intent = intent.getSelector(); 5155 comp = intent.getComponent(); 5156 } 5157 } 5158 5159 if (comp != null) { 5160 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5161 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5162 if (ai != null) { 5163 final ResolveInfo ri = new ResolveInfo(); 5164 ri.activityInfo = ai; 5165 list.add(ri); 5166 } 5167 return list; 5168 } 5169 5170 // reader 5171 synchronized (mPackages) { 5172 final String pkgName = intent.getPackage(); 5173 if (pkgName == null) { 5174 List<CrossProfileIntentFilter> matchingFilters = 5175 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5176 // Check for results that need to skip the current profile. 5177 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5178 resolvedType, flags, userId); 5179 if (xpResolveInfo != null) { 5180 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 5181 result.add(xpResolveInfo); 5182 return filterIfNotSystemUser(result, userId); 5183 } 5184 5185 // Check for results in the current profile. 5186 List<ResolveInfo> result = mActivities.queryIntent( 5187 intent, resolvedType, flags, userId); 5188 result = filterIfNotSystemUser(result, userId); 5189 5190 // Check for cross profile results. 5191 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5192 xpResolveInfo = queryCrossProfileIntents( 5193 matchingFilters, intent, resolvedType, flags, userId, 5194 hasNonNegativePriorityResult); 5195 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5196 boolean isVisibleToUser = filterIfNotSystemUser( 5197 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5198 if (isVisibleToUser) { 5199 result.add(xpResolveInfo); 5200 Collections.sort(result, mResolvePrioritySorter); 5201 } 5202 } 5203 if (hasWebURI(intent)) { 5204 CrossProfileDomainInfo xpDomainInfo = null; 5205 final UserInfo parent = getProfileParent(userId); 5206 if (parent != null) { 5207 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5208 flags, userId, parent.id); 5209 } 5210 if (xpDomainInfo != null) { 5211 if (xpResolveInfo != null) { 5212 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5213 // in the result. 5214 result.remove(xpResolveInfo); 5215 } 5216 if (result.size() == 0) { 5217 result.add(xpDomainInfo.resolveInfo); 5218 return result; 5219 } 5220 } else if (result.size() <= 1) { 5221 return result; 5222 } 5223 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 5224 xpDomainInfo, userId); 5225 Collections.sort(result, mResolvePrioritySorter); 5226 } 5227 return result; 5228 } 5229 final PackageParser.Package pkg = mPackages.get(pkgName); 5230 if (pkg != null) { 5231 return filterIfNotSystemUser( 5232 mActivities.queryIntentForPackage( 5233 intent, resolvedType, flags, pkg.activities, userId), 5234 userId); 5235 } 5236 return new ArrayList<ResolveInfo>(); 5237 } 5238 } 5239 5240 private static class CrossProfileDomainInfo { 5241 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5242 ResolveInfo resolveInfo; 5243 /* Best domain verification status of the activities found in the other profile */ 5244 int bestDomainVerificationStatus; 5245 } 5246 5247 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5248 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5249 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5250 sourceUserId)) { 5251 return null; 5252 } 5253 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5254 resolvedType, flags, parentUserId); 5255 5256 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5257 return null; 5258 } 5259 CrossProfileDomainInfo result = null; 5260 int size = resultTargetUser.size(); 5261 for (int i = 0; i < size; i++) { 5262 ResolveInfo riTargetUser = resultTargetUser.get(i); 5263 // Intent filter verification is only for filters that specify a host. So don't return 5264 // those that handle all web uris. 5265 if (riTargetUser.handleAllWebDataURI) { 5266 continue; 5267 } 5268 String packageName = riTargetUser.activityInfo.packageName; 5269 PackageSetting ps = mSettings.mPackages.get(packageName); 5270 if (ps == null) { 5271 continue; 5272 } 5273 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5274 int status = (int)(verificationState >> 32); 5275 if (result == null) { 5276 result = new CrossProfileDomainInfo(); 5277 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5278 sourceUserId, parentUserId); 5279 result.bestDomainVerificationStatus = status; 5280 } else { 5281 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5282 result.bestDomainVerificationStatus); 5283 } 5284 } 5285 // Don't consider matches with status NEVER across profiles. 5286 if (result != null && result.bestDomainVerificationStatus 5287 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5288 return null; 5289 } 5290 return result; 5291 } 5292 5293 /** 5294 * Verification statuses are ordered from the worse to the best, except for 5295 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5296 */ 5297 private int bestDomainVerificationStatus(int status1, int status2) { 5298 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5299 return status2; 5300 } 5301 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5302 return status1; 5303 } 5304 return (int) MathUtils.max(status1, status2); 5305 } 5306 5307 private boolean isUserEnabled(int userId) { 5308 long callingId = Binder.clearCallingIdentity(); 5309 try { 5310 UserInfo userInfo = sUserManager.getUserInfo(userId); 5311 return userInfo != null && userInfo.isEnabled(); 5312 } finally { 5313 Binder.restoreCallingIdentity(callingId); 5314 } 5315 } 5316 5317 /** 5318 * Filter out activities with systemUserOnly flag set, when current user is not System. 5319 * 5320 * @return filtered list 5321 */ 5322 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5323 if (userId == UserHandle.USER_SYSTEM) { 5324 return resolveInfos; 5325 } 5326 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5327 ResolveInfo info = resolveInfos.get(i); 5328 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5329 resolveInfos.remove(i); 5330 } 5331 } 5332 return resolveInfos; 5333 } 5334 5335 /** 5336 * @param resolveInfos list of resolve infos in descending priority order 5337 * @return if the list contains a resolve info with non-negative priority 5338 */ 5339 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5340 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5341 } 5342 5343 private static boolean hasWebURI(Intent intent) { 5344 if (intent.getData() == null) { 5345 return false; 5346 } 5347 final String scheme = intent.getScheme(); 5348 if (TextUtils.isEmpty(scheme)) { 5349 return false; 5350 } 5351 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5352 } 5353 5354 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5355 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5356 int userId) { 5357 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5358 5359 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5360 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5361 candidates.size()); 5362 } 5363 5364 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5365 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5366 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5367 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5368 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5369 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5370 5371 synchronized (mPackages) { 5372 final int count = candidates.size(); 5373 // First, try to use linked apps. Partition the candidates into four lists: 5374 // one for the final results, one for the "do not use ever", one for "undefined status" 5375 // and finally one for "browser app type". 5376 for (int n=0; n<count; n++) { 5377 ResolveInfo info = candidates.get(n); 5378 String packageName = info.activityInfo.packageName; 5379 PackageSetting ps = mSettings.mPackages.get(packageName); 5380 if (ps != null) { 5381 // Add to the special match all list (Browser use case) 5382 if (info.handleAllWebDataURI) { 5383 matchAllList.add(info); 5384 continue; 5385 } 5386 // Try to get the status from User settings first 5387 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5388 int status = (int)(packedStatus >> 32); 5389 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5390 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5391 if (DEBUG_DOMAIN_VERIFICATION) { 5392 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5393 + " : linkgen=" + linkGeneration); 5394 } 5395 // Use link-enabled generation as preferredOrder, i.e. 5396 // prefer newly-enabled over earlier-enabled. 5397 info.preferredOrder = linkGeneration; 5398 alwaysList.add(info); 5399 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5400 if (DEBUG_DOMAIN_VERIFICATION) { 5401 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5402 } 5403 neverList.add(info); 5404 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5405 if (DEBUG_DOMAIN_VERIFICATION) { 5406 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5407 } 5408 alwaysAskList.add(info); 5409 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5410 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5411 if (DEBUG_DOMAIN_VERIFICATION) { 5412 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5413 } 5414 undefinedList.add(info); 5415 } 5416 } 5417 } 5418 5419 // We'll want to include browser possibilities in a few cases 5420 boolean includeBrowser = false; 5421 5422 // First try to add the "always" resolution(s) for the current user, if any 5423 if (alwaysList.size() > 0) { 5424 result.addAll(alwaysList); 5425 } else { 5426 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5427 result.addAll(undefinedList); 5428 // Maybe add one for the other profile. 5429 if (xpDomainInfo != null && ( 5430 xpDomainInfo.bestDomainVerificationStatus 5431 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5432 result.add(xpDomainInfo.resolveInfo); 5433 } 5434 includeBrowser = true; 5435 } 5436 5437 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5438 // If there were 'always' entries their preferred order has been set, so we also 5439 // back that off to make the alternatives equivalent 5440 if (alwaysAskList.size() > 0) { 5441 for (ResolveInfo i : result) { 5442 i.preferredOrder = 0; 5443 } 5444 result.addAll(alwaysAskList); 5445 includeBrowser = true; 5446 } 5447 5448 if (includeBrowser) { 5449 // Also add browsers (all of them or only the default one) 5450 if (DEBUG_DOMAIN_VERIFICATION) { 5451 Slog.v(TAG, " ...including browsers in candidate set"); 5452 } 5453 if ((matchFlags & MATCH_ALL) != 0) { 5454 result.addAll(matchAllList); 5455 } else { 5456 // Browser/generic handling case. If there's a default browser, go straight 5457 // to that (but only if there is no other higher-priority match). 5458 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5459 int maxMatchPrio = 0; 5460 ResolveInfo defaultBrowserMatch = null; 5461 final int numCandidates = matchAllList.size(); 5462 for (int n = 0; n < numCandidates; n++) { 5463 ResolveInfo info = matchAllList.get(n); 5464 // track the highest overall match priority... 5465 if (info.priority > maxMatchPrio) { 5466 maxMatchPrio = info.priority; 5467 } 5468 // ...and the highest-priority default browser match 5469 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5470 if (defaultBrowserMatch == null 5471 || (defaultBrowserMatch.priority < info.priority)) { 5472 if (debug) { 5473 Slog.v(TAG, "Considering default browser match " + info); 5474 } 5475 defaultBrowserMatch = info; 5476 } 5477 } 5478 } 5479 if (defaultBrowserMatch != null 5480 && defaultBrowserMatch.priority >= maxMatchPrio 5481 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5482 { 5483 if (debug) { 5484 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5485 } 5486 result.add(defaultBrowserMatch); 5487 } else { 5488 result.addAll(matchAllList); 5489 } 5490 } 5491 5492 // If there is nothing selected, add all candidates and remove the ones that the user 5493 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5494 if (result.size() == 0) { 5495 result.addAll(candidates); 5496 result.removeAll(neverList); 5497 } 5498 } 5499 } 5500 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5501 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5502 result.size()); 5503 for (ResolveInfo info : result) { 5504 Slog.v(TAG, " + " + info.activityInfo); 5505 } 5506 } 5507 return result; 5508 } 5509 5510 // Returns a packed value as a long: 5511 // 5512 // high 'int'-sized word: link status: undefined/ask/never/always. 5513 // low 'int'-sized word: relative priority among 'always' results. 5514 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5515 long result = ps.getDomainVerificationStatusForUser(userId); 5516 // if none available, get the master status 5517 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5518 if (ps.getIntentFilterVerificationInfo() != null) { 5519 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5520 } 5521 } 5522 return result; 5523 } 5524 5525 private ResolveInfo querySkipCurrentProfileIntents( 5526 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5527 int flags, int sourceUserId) { 5528 if (matchingFilters != null) { 5529 int size = matchingFilters.size(); 5530 for (int i = 0; i < size; i ++) { 5531 CrossProfileIntentFilter filter = matchingFilters.get(i); 5532 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5533 // Checking if there are activities in the target user that can handle the 5534 // intent. 5535 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5536 resolvedType, flags, sourceUserId); 5537 if (resolveInfo != null) { 5538 return resolveInfo; 5539 } 5540 } 5541 } 5542 } 5543 return null; 5544 } 5545 5546 // Return matching ResolveInfo in target user if any. 5547 private ResolveInfo queryCrossProfileIntents( 5548 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5549 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5550 if (matchingFilters != null) { 5551 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5552 // match the same intent. For performance reasons, it is better not to 5553 // run queryIntent twice for the same userId 5554 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5555 int size = matchingFilters.size(); 5556 for (int i = 0; i < size; i++) { 5557 CrossProfileIntentFilter filter = matchingFilters.get(i); 5558 int targetUserId = filter.getTargetUserId(); 5559 boolean skipCurrentProfile = 5560 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5561 boolean skipCurrentProfileIfNoMatchFound = 5562 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5563 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5564 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5565 // Checking if there are activities in the target user that can handle the 5566 // intent. 5567 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5568 resolvedType, flags, sourceUserId); 5569 if (resolveInfo != null) return resolveInfo; 5570 alreadyTriedUserIds.put(targetUserId, true); 5571 } 5572 } 5573 } 5574 return null; 5575 } 5576 5577 /** 5578 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5579 * will forward the intent to the filter's target user. 5580 * Otherwise, returns null. 5581 */ 5582 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5583 String resolvedType, int flags, int sourceUserId) { 5584 int targetUserId = filter.getTargetUserId(); 5585 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5586 resolvedType, flags, targetUserId); 5587 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5588 // If all the matches in the target profile are suspended, return null. 5589 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5590 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5591 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5592 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5593 targetUserId); 5594 } 5595 } 5596 } 5597 return null; 5598 } 5599 5600 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5601 int sourceUserId, int targetUserId) { 5602 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5603 long ident = Binder.clearCallingIdentity(); 5604 boolean targetIsProfile; 5605 try { 5606 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5607 } finally { 5608 Binder.restoreCallingIdentity(ident); 5609 } 5610 String className; 5611 if (targetIsProfile) { 5612 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5613 } else { 5614 className = FORWARD_INTENT_TO_PARENT; 5615 } 5616 ComponentName forwardingActivityComponentName = new ComponentName( 5617 mAndroidApplication.packageName, className); 5618 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5619 sourceUserId); 5620 if (!targetIsProfile) { 5621 forwardingActivityInfo.showUserIcon = targetUserId; 5622 forwardingResolveInfo.noResourceId = true; 5623 } 5624 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5625 forwardingResolveInfo.priority = 0; 5626 forwardingResolveInfo.preferredOrder = 0; 5627 forwardingResolveInfo.match = 0; 5628 forwardingResolveInfo.isDefault = true; 5629 forwardingResolveInfo.filter = filter; 5630 forwardingResolveInfo.targetUserId = targetUserId; 5631 return forwardingResolveInfo; 5632 } 5633 5634 @Override 5635 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5636 Intent[] specifics, String[] specificTypes, Intent intent, 5637 String resolvedType, int flags, int userId) { 5638 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 5639 specificTypes, intent, resolvedType, flags, userId)); 5640 } 5641 5642 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 5643 Intent[] specifics, String[] specificTypes, Intent intent, 5644 String resolvedType, int flags, int userId) { 5645 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5646 flags = updateFlagsForResolve(flags, userId, intent); 5647 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5648 false /* requireFullPermission */, false /* checkShell */, 5649 "query intent activity options"); 5650 final String resultsAction = intent.getAction(); 5651 5652 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 5653 | PackageManager.GET_RESOLVED_FILTER, userId); 5654 5655 if (DEBUG_INTENT_MATCHING) { 5656 Log.v(TAG, "Query " + intent + ": " + results); 5657 } 5658 5659 int specificsPos = 0; 5660 int N; 5661 5662 // todo: note that the algorithm used here is O(N^2). This 5663 // isn't a problem in our current environment, but if we start running 5664 // into situations where we have more than 5 or 10 matches then this 5665 // should probably be changed to something smarter... 5666 5667 // First we go through and resolve each of the specific items 5668 // that were supplied, taking care of removing any corresponding 5669 // duplicate items in the generic resolve list. 5670 if (specifics != null) { 5671 for (int i=0; i<specifics.length; i++) { 5672 final Intent sintent = specifics[i]; 5673 if (sintent == null) { 5674 continue; 5675 } 5676 5677 if (DEBUG_INTENT_MATCHING) { 5678 Log.v(TAG, "Specific #" + i + ": " + sintent); 5679 } 5680 5681 String action = sintent.getAction(); 5682 if (resultsAction != null && resultsAction.equals(action)) { 5683 // If this action was explicitly requested, then don't 5684 // remove things that have it. 5685 action = null; 5686 } 5687 5688 ResolveInfo ri = null; 5689 ActivityInfo ai = null; 5690 5691 ComponentName comp = sintent.getComponent(); 5692 if (comp == null) { 5693 ri = resolveIntent( 5694 sintent, 5695 specificTypes != null ? specificTypes[i] : null, 5696 flags, userId); 5697 if (ri == null) { 5698 continue; 5699 } 5700 if (ri == mResolveInfo) { 5701 // ACK! Must do something better with this. 5702 } 5703 ai = ri.activityInfo; 5704 comp = new ComponentName(ai.applicationInfo.packageName, 5705 ai.name); 5706 } else { 5707 ai = getActivityInfo(comp, flags, userId); 5708 if (ai == null) { 5709 continue; 5710 } 5711 } 5712 5713 // Look for any generic query activities that are duplicates 5714 // of this specific one, and remove them from the results. 5715 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5716 N = results.size(); 5717 int j; 5718 for (j=specificsPos; j<N; j++) { 5719 ResolveInfo sri = results.get(j); 5720 if ((sri.activityInfo.name.equals(comp.getClassName()) 5721 && sri.activityInfo.applicationInfo.packageName.equals( 5722 comp.getPackageName())) 5723 || (action != null && sri.filter.matchAction(action))) { 5724 results.remove(j); 5725 if (DEBUG_INTENT_MATCHING) Log.v( 5726 TAG, "Removing duplicate item from " + j 5727 + " due to specific " + specificsPos); 5728 if (ri == null) { 5729 ri = sri; 5730 } 5731 j--; 5732 N--; 5733 } 5734 } 5735 5736 // Add this specific item to its proper place. 5737 if (ri == null) { 5738 ri = new ResolveInfo(); 5739 ri.activityInfo = ai; 5740 } 5741 results.add(specificsPos, ri); 5742 ri.specificIndex = i; 5743 specificsPos++; 5744 } 5745 } 5746 5747 // Now we go through the remaining generic results and remove any 5748 // duplicate actions that are found here. 5749 N = results.size(); 5750 for (int i=specificsPos; i<N-1; i++) { 5751 final ResolveInfo rii = results.get(i); 5752 if (rii.filter == null) { 5753 continue; 5754 } 5755 5756 // Iterate over all of the actions of this result's intent 5757 // filter... typically this should be just one. 5758 final Iterator<String> it = rii.filter.actionsIterator(); 5759 if (it == null) { 5760 continue; 5761 } 5762 while (it.hasNext()) { 5763 final String action = it.next(); 5764 if (resultsAction != null && resultsAction.equals(action)) { 5765 // If this action was explicitly requested, then don't 5766 // remove things that have it. 5767 continue; 5768 } 5769 for (int j=i+1; j<N; j++) { 5770 final ResolveInfo rij = results.get(j); 5771 if (rij.filter != null && rij.filter.hasAction(action)) { 5772 results.remove(j); 5773 if (DEBUG_INTENT_MATCHING) Log.v( 5774 TAG, "Removing duplicate item from " + j 5775 + " due to action " + action + " at " + i); 5776 j--; 5777 N--; 5778 } 5779 } 5780 } 5781 5782 // If the caller didn't request filter information, drop it now 5783 // so we don't have to marshall/unmarshall it. 5784 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5785 rii.filter = null; 5786 } 5787 } 5788 5789 // Filter out the caller activity if so requested. 5790 if (caller != null) { 5791 N = results.size(); 5792 for (int i=0; i<N; i++) { 5793 ActivityInfo ainfo = results.get(i).activityInfo; 5794 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5795 && caller.getClassName().equals(ainfo.name)) { 5796 results.remove(i); 5797 break; 5798 } 5799 } 5800 } 5801 5802 // If the caller didn't request filter information, 5803 // drop them now so we don't have to 5804 // marshall/unmarshall it. 5805 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5806 N = results.size(); 5807 for (int i=0; i<N; i++) { 5808 results.get(i).filter = null; 5809 } 5810 } 5811 5812 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5813 return results; 5814 } 5815 5816 @Override 5817 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 5818 String resolvedType, int flags, int userId) { 5819 return new ParceledListSlice<>( 5820 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 5821 } 5822 5823 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 5824 String resolvedType, int flags, int userId) { 5825 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5826 flags = updateFlagsForResolve(flags, userId, intent); 5827 ComponentName comp = intent.getComponent(); 5828 if (comp == null) { 5829 if (intent.getSelector() != null) { 5830 intent = intent.getSelector(); 5831 comp = intent.getComponent(); 5832 } 5833 } 5834 if (comp != null) { 5835 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5836 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5837 if (ai != null) { 5838 ResolveInfo ri = new ResolveInfo(); 5839 ri.activityInfo = ai; 5840 list.add(ri); 5841 } 5842 return list; 5843 } 5844 5845 // reader 5846 synchronized (mPackages) { 5847 String pkgName = intent.getPackage(); 5848 if (pkgName == null) { 5849 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5850 } 5851 final PackageParser.Package pkg = mPackages.get(pkgName); 5852 if (pkg != null) { 5853 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5854 userId); 5855 } 5856 return Collections.emptyList(); 5857 } 5858 } 5859 5860 @Override 5861 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5862 if (!sUserManager.exists(userId)) return null; 5863 flags = updateFlagsForResolve(flags, userId, intent); 5864 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 5865 if (query != null) { 5866 if (query.size() >= 1) { 5867 // If there is more than one service with the same priority, 5868 // just arbitrarily pick the first one. 5869 return query.get(0); 5870 } 5871 } 5872 return null; 5873 } 5874 5875 @Override 5876 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 5877 String resolvedType, int flags, int userId) { 5878 return new ParceledListSlice<>( 5879 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 5880 } 5881 5882 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 5883 String resolvedType, int flags, int userId) { 5884 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5885 flags = updateFlagsForResolve(flags, userId, intent); 5886 ComponentName comp = intent.getComponent(); 5887 if (comp == null) { 5888 if (intent.getSelector() != null) { 5889 intent = intent.getSelector(); 5890 comp = intent.getComponent(); 5891 } 5892 } 5893 if (comp != null) { 5894 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5895 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5896 if (si != null) { 5897 final ResolveInfo ri = new ResolveInfo(); 5898 ri.serviceInfo = si; 5899 list.add(ri); 5900 } 5901 return list; 5902 } 5903 5904 // reader 5905 synchronized (mPackages) { 5906 String pkgName = intent.getPackage(); 5907 if (pkgName == null) { 5908 return mServices.queryIntent(intent, resolvedType, flags, userId); 5909 } 5910 final PackageParser.Package pkg = mPackages.get(pkgName); 5911 if (pkg != null) { 5912 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5913 userId); 5914 } 5915 return Collections.emptyList(); 5916 } 5917 } 5918 5919 @Override 5920 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 5921 String resolvedType, int flags, int userId) { 5922 return new ParceledListSlice<>( 5923 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 5924 } 5925 5926 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 5927 Intent intent, String resolvedType, int flags, int userId) { 5928 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5929 flags = updateFlagsForResolve(flags, userId, intent); 5930 ComponentName comp = intent.getComponent(); 5931 if (comp == null) { 5932 if (intent.getSelector() != null) { 5933 intent = intent.getSelector(); 5934 comp = intent.getComponent(); 5935 } 5936 } 5937 if (comp != null) { 5938 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5939 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5940 if (pi != null) { 5941 final ResolveInfo ri = new ResolveInfo(); 5942 ri.providerInfo = pi; 5943 list.add(ri); 5944 } 5945 return list; 5946 } 5947 5948 // reader 5949 synchronized (mPackages) { 5950 String pkgName = intent.getPackage(); 5951 if (pkgName == null) { 5952 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5953 } 5954 final PackageParser.Package pkg = mPackages.get(pkgName); 5955 if (pkg != null) { 5956 return mProviders.queryIntentForPackage( 5957 intent, resolvedType, flags, pkg.providers, userId); 5958 } 5959 return Collections.emptyList(); 5960 } 5961 } 5962 5963 @Override 5964 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5965 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 5966 flags = updateFlagsForPackage(flags, userId, null); 5967 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 5968 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5969 true /* requireFullPermission */, false /* checkShell */, 5970 "get installed packages"); 5971 5972 // writer 5973 synchronized (mPackages) { 5974 ArrayList<PackageInfo> list; 5975 if (listUninstalled) { 5976 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5977 for (PackageSetting ps : mSettings.mPackages.values()) { 5978 final PackageInfo pi; 5979 if (ps.pkg != null) { 5980 pi = generatePackageInfo(ps, flags, userId); 5981 } else { 5982 pi = generatePackageInfo(ps, flags, userId); 5983 } 5984 if (pi != null) { 5985 list.add(pi); 5986 } 5987 } 5988 } else { 5989 list = new ArrayList<PackageInfo>(mPackages.size()); 5990 for (PackageParser.Package p : mPackages.values()) { 5991 final PackageInfo pi = 5992 generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 5993 if (pi != null) { 5994 list.add(pi); 5995 } 5996 } 5997 } 5998 5999 return new ParceledListSlice<PackageInfo>(list); 6000 } 6001 } 6002 6003 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 6004 String[] permissions, boolean[] tmp, int flags, int userId) { 6005 int numMatch = 0; 6006 final PermissionsState permissionsState = ps.getPermissionsState(); 6007 for (int i=0; i<permissions.length; i++) { 6008 final String permission = permissions[i]; 6009 if (permissionsState.hasPermission(permission, userId)) { 6010 tmp[i] = true; 6011 numMatch++; 6012 } else { 6013 tmp[i] = false; 6014 } 6015 } 6016 if (numMatch == 0) { 6017 return; 6018 } 6019 final PackageInfo pi; 6020 if (ps.pkg != null) { 6021 pi = generatePackageInfo(ps, flags, userId); 6022 } else { 6023 pi = generatePackageInfo(ps, flags, userId); 6024 } 6025 // The above might return null in cases of uninstalled apps or install-state 6026 // skew across users/profiles. 6027 if (pi != null) { 6028 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 6029 if (numMatch == permissions.length) { 6030 pi.requestedPermissions = permissions; 6031 } else { 6032 pi.requestedPermissions = new String[numMatch]; 6033 numMatch = 0; 6034 for (int i=0; i<permissions.length; i++) { 6035 if (tmp[i]) { 6036 pi.requestedPermissions[numMatch] = permissions[i]; 6037 numMatch++; 6038 } 6039 } 6040 } 6041 } 6042 list.add(pi); 6043 } 6044 } 6045 6046 @Override 6047 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 6048 String[] permissions, int flags, int userId) { 6049 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6050 flags = updateFlagsForPackage(flags, userId, permissions); 6051 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6052 6053 // writer 6054 synchronized (mPackages) { 6055 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 6056 boolean[] tmpBools = new boolean[permissions.length]; 6057 if (listUninstalled) { 6058 for (PackageSetting ps : mSettings.mPackages.values()) { 6059 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 6060 } 6061 } else { 6062 for (PackageParser.Package pkg : mPackages.values()) { 6063 PackageSetting ps = (PackageSetting)pkg.mExtras; 6064 if (ps != null) { 6065 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6066 userId); 6067 } 6068 } 6069 } 6070 6071 return new ParceledListSlice<PackageInfo>(list); 6072 } 6073 } 6074 6075 @Override 6076 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 6077 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6078 flags = updateFlagsForApplication(flags, userId, null); 6079 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6080 6081 // writer 6082 synchronized (mPackages) { 6083 ArrayList<ApplicationInfo> list; 6084 if (listUninstalled) { 6085 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 6086 for (PackageSetting ps : mSettings.mPackages.values()) { 6087 ApplicationInfo ai; 6088 if (ps.pkg != null) { 6089 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 6090 ps.readUserState(userId), userId); 6091 } else { 6092 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 6093 } 6094 if (ai != null) { 6095 list.add(ai); 6096 } 6097 } 6098 } else { 6099 list = new ArrayList<ApplicationInfo>(mPackages.size()); 6100 for (PackageParser.Package p : mPackages.values()) { 6101 if (p.mExtras != null) { 6102 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6103 ((PackageSetting)p.mExtras).readUserState(userId), userId); 6104 if (ai != null) { 6105 list.add(ai); 6106 } 6107 } 6108 } 6109 } 6110 6111 return new ParceledListSlice<ApplicationInfo>(list); 6112 } 6113 } 6114 6115 @Override 6116 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 6117 if (DISABLE_EPHEMERAL_APPS) { 6118 return null; 6119 } 6120 6121 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6122 "getEphemeralApplications"); 6123 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6124 true /* requireFullPermission */, false /* checkShell */, 6125 "getEphemeralApplications"); 6126 synchronized (mPackages) { 6127 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 6128 .getEphemeralApplicationsLPw(userId); 6129 if (ephemeralApps != null) { 6130 return new ParceledListSlice<>(ephemeralApps); 6131 } 6132 } 6133 return null; 6134 } 6135 6136 @Override 6137 public boolean isEphemeralApplication(String packageName, int userId) { 6138 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6139 true /* requireFullPermission */, false /* checkShell */, 6140 "isEphemeral"); 6141 if (DISABLE_EPHEMERAL_APPS) { 6142 return false; 6143 } 6144 6145 if (!isCallerSameApp(packageName)) { 6146 return false; 6147 } 6148 synchronized (mPackages) { 6149 PackageParser.Package pkg = mPackages.get(packageName); 6150 if (pkg != null) { 6151 return pkg.applicationInfo.isEphemeralApp(); 6152 } 6153 } 6154 return false; 6155 } 6156 6157 @Override 6158 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6159 if (DISABLE_EPHEMERAL_APPS) { 6160 return null; 6161 } 6162 6163 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6164 true /* requireFullPermission */, false /* checkShell */, 6165 "getCookie"); 6166 if (!isCallerSameApp(packageName)) { 6167 return null; 6168 } 6169 synchronized (mPackages) { 6170 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6171 packageName, userId); 6172 } 6173 } 6174 6175 @Override 6176 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6177 if (DISABLE_EPHEMERAL_APPS) { 6178 return true; 6179 } 6180 6181 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6182 true /* requireFullPermission */, true /* checkShell */, 6183 "setCookie"); 6184 if (!isCallerSameApp(packageName)) { 6185 return false; 6186 } 6187 synchronized (mPackages) { 6188 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6189 packageName, cookie, userId); 6190 } 6191 } 6192 6193 @Override 6194 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6195 if (DISABLE_EPHEMERAL_APPS) { 6196 return null; 6197 } 6198 6199 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6200 "getEphemeralApplicationIcon"); 6201 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6202 true /* requireFullPermission */, false /* checkShell */, 6203 "getEphemeralApplicationIcon"); 6204 synchronized (mPackages) { 6205 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6206 packageName, userId); 6207 } 6208 } 6209 6210 private boolean isCallerSameApp(String packageName) { 6211 PackageParser.Package pkg = mPackages.get(packageName); 6212 return pkg != null 6213 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6214 } 6215 6216 @Override 6217 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 6218 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 6219 } 6220 6221 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 6222 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6223 6224 // reader 6225 synchronized (mPackages) { 6226 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6227 final int userId = UserHandle.getCallingUserId(); 6228 while (i.hasNext()) { 6229 final PackageParser.Package p = i.next(); 6230 if (p.applicationInfo == null) continue; 6231 6232 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 6233 && !p.applicationInfo.isDirectBootAware(); 6234 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 6235 && p.applicationInfo.isDirectBootAware(); 6236 6237 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6238 && (!mSafeMode || isSystemApp(p)) 6239 && (matchesUnaware || matchesAware)) { 6240 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6241 if (ps != null) { 6242 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6243 ps.readUserState(userId), userId); 6244 if (ai != null) { 6245 finalList.add(ai); 6246 } 6247 } 6248 } 6249 } 6250 } 6251 6252 return finalList; 6253 } 6254 6255 @Override 6256 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6257 if (!sUserManager.exists(userId)) return null; 6258 flags = updateFlagsForComponent(flags, userId, name); 6259 // reader 6260 synchronized (mPackages) { 6261 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6262 PackageSetting ps = provider != null 6263 ? mSettings.mPackages.get(provider.owner.packageName) 6264 : null; 6265 return ps != null 6266 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6267 ? PackageParser.generateProviderInfo(provider, flags, 6268 ps.readUserState(userId), userId) 6269 : null; 6270 } 6271 } 6272 6273 /** 6274 * @deprecated 6275 */ 6276 @Deprecated 6277 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6278 // reader 6279 synchronized (mPackages) { 6280 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6281 .entrySet().iterator(); 6282 final int userId = UserHandle.getCallingUserId(); 6283 while (i.hasNext()) { 6284 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6285 PackageParser.Provider p = entry.getValue(); 6286 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6287 6288 if (ps != null && p.syncable 6289 && (!mSafeMode || (p.info.applicationInfo.flags 6290 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6291 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6292 ps.readUserState(userId), userId); 6293 if (info != null) { 6294 outNames.add(entry.getKey()); 6295 outInfo.add(info); 6296 } 6297 } 6298 } 6299 } 6300 } 6301 6302 @Override 6303 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6304 int uid, int flags) { 6305 final int userId = processName != null ? UserHandle.getUserId(uid) 6306 : UserHandle.getCallingUserId(); 6307 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6308 flags = updateFlagsForComponent(flags, userId, processName); 6309 6310 ArrayList<ProviderInfo> finalList = null; 6311 // reader 6312 synchronized (mPackages) { 6313 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6314 while (i.hasNext()) { 6315 final PackageParser.Provider p = i.next(); 6316 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6317 if (ps != null && p.info.authority != null 6318 && (processName == null 6319 || (p.info.processName.equals(processName) 6320 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6321 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6322 if (finalList == null) { 6323 finalList = new ArrayList<ProviderInfo>(3); 6324 } 6325 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6326 ps.readUserState(userId), userId); 6327 if (info != null) { 6328 finalList.add(info); 6329 } 6330 } 6331 } 6332 } 6333 6334 if (finalList != null) { 6335 Collections.sort(finalList, mProviderInitOrderSorter); 6336 return new ParceledListSlice<ProviderInfo>(finalList); 6337 } 6338 6339 return ParceledListSlice.emptyList(); 6340 } 6341 6342 @Override 6343 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6344 // reader 6345 synchronized (mPackages) { 6346 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6347 return PackageParser.generateInstrumentationInfo(i, flags); 6348 } 6349 } 6350 6351 @Override 6352 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 6353 String targetPackage, int flags) { 6354 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 6355 } 6356 6357 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 6358 int flags) { 6359 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 6360 6361 // reader 6362 synchronized (mPackages) { 6363 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6364 while (i.hasNext()) { 6365 final PackageParser.Instrumentation p = i.next(); 6366 if (targetPackage == null 6367 || targetPackage.equals(p.info.targetPackage)) { 6368 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6369 flags); 6370 if (ii != null) { 6371 finalList.add(ii); 6372 } 6373 } 6374 } 6375 } 6376 6377 return finalList; 6378 } 6379 6380 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6381 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6382 if (overlays == null) { 6383 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6384 return; 6385 } 6386 for (PackageParser.Package opkg : overlays.values()) { 6387 // Not much to do if idmap fails: we already logged the error 6388 // and we certainly don't want to abort installation of pkg simply 6389 // because an overlay didn't fit properly. For these reasons, 6390 // ignore the return value of createIdmapForPackagePairLI. 6391 createIdmapForPackagePairLI(pkg, opkg); 6392 } 6393 } 6394 6395 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6396 PackageParser.Package opkg) { 6397 if (!opkg.mTrustedOverlay) { 6398 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6399 opkg.baseCodePath + ": overlay not trusted"); 6400 return false; 6401 } 6402 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6403 if (overlaySet == null) { 6404 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6405 opkg.baseCodePath + " but target package has no known overlays"); 6406 return false; 6407 } 6408 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6409 // TODO: generate idmap for split APKs 6410 try { 6411 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6412 } catch (InstallerException e) { 6413 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6414 + opkg.baseCodePath); 6415 return false; 6416 } 6417 PackageParser.Package[] overlayArray = 6418 overlaySet.values().toArray(new PackageParser.Package[0]); 6419 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6420 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6421 return p1.mOverlayPriority - p2.mOverlayPriority; 6422 } 6423 }; 6424 Arrays.sort(overlayArray, cmp); 6425 6426 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6427 int i = 0; 6428 for (PackageParser.Package p : overlayArray) { 6429 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6430 } 6431 return true; 6432 } 6433 6434 private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6435 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6436 try { 6437 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6438 } finally { 6439 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6440 } 6441 } 6442 6443 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6444 final File[] files = dir.listFiles(); 6445 if (ArrayUtils.isEmpty(files)) { 6446 Log.d(TAG, "No files in app dir " + dir); 6447 return; 6448 } 6449 6450 if (DEBUG_PACKAGE_SCANNING) { 6451 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6452 + " flags=0x" + Integer.toHexString(parseFlags)); 6453 } 6454 6455 for (File file : files) { 6456 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6457 && !PackageInstallerService.isStageName(file.getName()); 6458 if (!isPackage) { 6459 // Ignore entries which are not packages 6460 continue; 6461 } 6462 try { 6463 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6464 scanFlags, currentTime, null); 6465 } catch (PackageManagerException e) { 6466 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6467 6468 // Delete invalid userdata apps 6469 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6470 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6471 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6472 removeCodePathLI(file); 6473 } 6474 } 6475 } 6476 } 6477 6478 private static File getSettingsProblemFile() { 6479 File dataDir = Environment.getDataDirectory(); 6480 File systemDir = new File(dataDir, "system"); 6481 File fname = new File(systemDir, "uiderrors.txt"); 6482 return fname; 6483 } 6484 6485 static void reportSettingsProblem(int priority, String msg) { 6486 logCriticalInfo(priority, msg); 6487 } 6488 6489 static void logCriticalInfo(int priority, String msg) { 6490 Slog.println(priority, TAG, msg); 6491 EventLogTags.writePmCriticalInfo(msg); 6492 try { 6493 File fname = getSettingsProblemFile(); 6494 FileOutputStream out = new FileOutputStream(fname, true); 6495 PrintWriter pw = new FastPrintWriter(out); 6496 SimpleDateFormat formatter = new SimpleDateFormat(); 6497 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6498 pw.println(dateString + ": " + msg); 6499 pw.close(); 6500 FileUtils.setPermissions( 6501 fname.toString(), 6502 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6503 -1, -1); 6504 } catch (java.io.IOException e) { 6505 } 6506 } 6507 6508 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6509 int parseFlags) throws PackageManagerException { 6510 if (ps != null 6511 && ps.codePath.equals(srcFile) 6512 && ps.timeStamp == srcFile.lastModified() 6513 && !isCompatSignatureUpdateNeeded(pkg) 6514 && !isRecoverSignatureUpdateNeeded(pkg)) { 6515 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6516 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6517 ArraySet<PublicKey> signingKs; 6518 synchronized (mPackages) { 6519 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6520 } 6521 if (ps.signatures.mSignatures != null 6522 && ps.signatures.mSignatures.length != 0 6523 && signingKs != null) { 6524 // Optimization: reuse the existing cached certificates 6525 // if the package appears to be unchanged. 6526 pkg.mSignatures = ps.signatures.mSignatures; 6527 pkg.mSigningKeys = signingKs; 6528 return; 6529 } 6530 6531 Slog.w(TAG, "PackageSetting for " + ps.name 6532 + " is missing signatures. Collecting certs again to recover them."); 6533 } else { 6534 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6535 } 6536 6537 try { 6538 PackageParser.collectCertificates(pkg, parseFlags); 6539 } catch (PackageParserException e) { 6540 throw PackageManagerException.from(e); 6541 } 6542 } 6543 6544 /** 6545 * Traces a package scan. 6546 * @see #scanPackageLI(File, int, int, long, UserHandle) 6547 */ 6548 private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags, 6549 long currentTime, UserHandle user) throws PackageManagerException { 6550 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6551 try { 6552 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6553 } finally { 6554 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6555 } 6556 } 6557 6558 /** 6559 * Scans a package and returns the newly parsed package. 6560 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6561 */ 6562 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6563 long currentTime, UserHandle user) throws PackageManagerException { 6564 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6565 parseFlags |= mDefParseFlags; 6566 PackageParser pp = new PackageParser(); 6567 pp.setSeparateProcesses(mSeparateProcesses); 6568 pp.setOnlyCoreApps(mOnlyCore); 6569 pp.setDisplayMetrics(mMetrics); 6570 6571 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6572 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6573 } 6574 6575 final PackageParser.Package pkg; 6576 try { 6577 pkg = pp.parsePackage(scanFile, parseFlags); 6578 } catch (PackageParserException e) { 6579 throw PackageManagerException.from(e); 6580 } 6581 6582 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6583 } 6584 6585 /** 6586 * Scans a package and returns the newly parsed package. 6587 * @throws PackageManagerException on a parse error. 6588 */ 6589 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6590 int parseFlags, int scanFlags, long currentTime, UserHandle user) 6591 throws PackageManagerException { 6592 // If the package has children and this is the first dive in the function 6593 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6594 // packages (parent and children) would be successfully scanned before the 6595 // actual scan since scanning mutates internal state and we want to atomically 6596 // install the package and its children. 6597 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6598 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6599 scanFlags |= SCAN_CHECK_ONLY; 6600 } 6601 } else { 6602 scanFlags &= ~SCAN_CHECK_ONLY; 6603 } 6604 6605 // Scan the parent 6606 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, parseFlags, 6607 scanFlags, currentTime, user); 6608 6609 // Scan the children 6610 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6611 for (int i = 0; i < childCount; i++) { 6612 PackageParser.Package childPackage = pkg.childPackages.get(i); 6613 scanPackageInternalLI(childPackage, scanFile, parseFlags, scanFlags, 6614 currentTime, user); 6615 } 6616 6617 6618 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6619 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6620 } 6621 6622 return scannedPkg; 6623 } 6624 6625 /** 6626 * Scans a package and returns the newly parsed package. 6627 * @throws PackageManagerException on a parse error. 6628 */ 6629 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6630 int parseFlags, int scanFlags, long currentTime, UserHandle user) 6631 throws PackageManagerException { 6632 PackageSetting ps = null; 6633 PackageSetting updatedPkg; 6634 // reader 6635 synchronized (mPackages) { 6636 // Look to see if we already know about this package. 6637 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6638 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6639 // This package has been renamed to its original name. Let's 6640 // use that. 6641 ps = mSettings.peekPackageLPr(oldName); 6642 } 6643 // If there was no original package, see one for the real package name. 6644 if (ps == null) { 6645 ps = mSettings.peekPackageLPr(pkg.packageName); 6646 } 6647 // Check to see if this package could be hiding/updating a system 6648 // package. Must look for it either under the original or real 6649 // package name depending on our state. 6650 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6651 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6652 6653 // If this is a package we don't know about on the system partition, we 6654 // may need to remove disabled child packages on the system partition 6655 // or may need to not add child packages if the parent apk is updated 6656 // on the data partition and no longer defines this child package. 6657 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6658 // If this is a parent package for an updated system app and this system 6659 // app got an OTA update which no longer defines some of the child packages 6660 // we have to prune them from the disabled system packages. 6661 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6662 if (disabledPs != null) { 6663 final int scannedChildCount = (pkg.childPackages != null) 6664 ? pkg.childPackages.size() : 0; 6665 final int disabledChildCount = disabledPs.childPackageNames != null 6666 ? disabledPs.childPackageNames.size() : 0; 6667 for (int i = 0; i < disabledChildCount; i++) { 6668 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6669 boolean disabledPackageAvailable = false; 6670 for (int j = 0; j < scannedChildCount; j++) { 6671 PackageParser.Package childPkg = pkg.childPackages.get(j); 6672 if (childPkg.packageName.equals(disabledChildPackageName)) { 6673 disabledPackageAvailable = true; 6674 break; 6675 } 6676 } 6677 if (!disabledPackageAvailable) { 6678 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6679 } 6680 } 6681 } 6682 } 6683 } 6684 6685 boolean updatedPkgBetter = false; 6686 // First check if this is a system package that may involve an update 6687 if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6688 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6689 // it needs to drop FLAG_PRIVILEGED. 6690 if (locationIsPrivileged(scanFile)) { 6691 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6692 } else { 6693 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6694 } 6695 6696 if (ps != null && !ps.codePath.equals(scanFile)) { 6697 // The path has changed from what was last scanned... check the 6698 // version of the new path against what we have stored to determine 6699 // what to do. 6700 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6701 if (pkg.mVersionCode <= ps.versionCode) { 6702 // The system package has been updated and the code path does not match 6703 // Ignore entry. Skip it. 6704 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6705 + " ignored: updated version " + ps.versionCode 6706 + " better than this " + pkg.mVersionCode); 6707 if (!updatedPkg.codePath.equals(scanFile)) { 6708 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6709 + ps.name + " changing from " + updatedPkg.codePathString 6710 + " to " + scanFile); 6711 updatedPkg.codePath = scanFile; 6712 updatedPkg.codePathString = scanFile.toString(); 6713 updatedPkg.resourcePath = scanFile; 6714 updatedPkg.resourcePathString = scanFile.toString(); 6715 } 6716 updatedPkg.pkg = pkg; 6717 updatedPkg.versionCode = pkg.mVersionCode; 6718 6719 // Update the disabled system child packages to point to the package too. 6720 final int childCount = updatedPkg.childPackageNames != null 6721 ? updatedPkg.childPackageNames.size() : 0; 6722 for (int i = 0; i < childCount; i++) { 6723 String childPackageName = updatedPkg.childPackageNames.get(i); 6724 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 6725 childPackageName); 6726 if (updatedChildPkg != null) { 6727 updatedChildPkg.pkg = pkg; 6728 updatedChildPkg.versionCode = pkg.mVersionCode; 6729 } 6730 } 6731 6732 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 6733 + scanFile + " ignored: updated version " + ps.versionCode 6734 + " better than this " + pkg.mVersionCode); 6735 } else { 6736 // The current app on the system partition is better than 6737 // what we have updated to on the data partition; switch 6738 // back to the system partition version. 6739 // At this point, its safely assumed that package installation for 6740 // apps in system partition will go through. If not there won't be a working 6741 // version of the app 6742 // writer 6743 synchronized (mPackages) { 6744 // Just remove the loaded entries from package lists. 6745 mPackages.remove(ps.name); 6746 } 6747 6748 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6749 + " reverting from " + ps.codePathString 6750 + ": new version " + pkg.mVersionCode 6751 + " better than installed " + ps.versionCode); 6752 6753 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6754 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6755 synchronized (mInstallLock) { 6756 args.cleanUpResourcesLI(); 6757 } 6758 synchronized (mPackages) { 6759 mSettings.enableSystemPackageLPw(ps.name); 6760 } 6761 updatedPkgBetter = true; 6762 } 6763 } 6764 } 6765 6766 if (updatedPkg != null) { 6767 // An updated system app will not have the PARSE_IS_SYSTEM flag set 6768 // initially 6769 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 6770 6771 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 6772 // flag set initially 6773 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 6774 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 6775 } 6776 } 6777 6778 // Verify certificates against what was last scanned 6779 collectCertificatesLI(ps, pkg, scanFile, parseFlags); 6780 6781 /* 6782 * A new system app appeared, but we already had a non-system one of the 6783 * same name installed earlier. 6784 */ 6785 boolean shouldHideSystemApp = false; 6786 if (updatedPkg == null && ps != null 6787 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 6788 /* 6789 * Check to make sure the signatures match first. If they don't, 6790 * wipe the installed application and its data. 6791 */ 6792 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 6793 != PackageManager.SIGNATURE_MATCH) { 6794 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 6795 + " signatures don't match existing userdata copy; removing"); 6796 deletePackageLI(pkg.packageName, null, true, null, 0, null, false, null); 6797 ps = null; 6798 } else { 6799 /* 6800 * If the newly-added system app is an older version than the 6801 * already installed version, hide it. It will be scanned later 6802 * and re-added like an update. 6803 */ 6804 if (pkg.mVersionCode <= ps.versionCode) { 6805 shouldHideSystemApp = true; 6806 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 6807 + " but new version " + pkg.mVersionCode + " better than installed " 6808 + ps.versionCode + "; hiding system"); 6809 } else { 6810 /* 6811 * The newly found system app is a newer version that the 6812 * one previously installed. Simply remove the 6813 * already-installed application and replace it with our own 6814 * while keeping the application data. 6815 */ 6816 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6817 + " reverting from " + ps.codePathString + ": new version " 6818 + pkg.mVersionCode + " better than installed " + ps.versionCode); 6819 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6820 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6821 synchronized (mInstallLock) { 6822 args.cleanUpResourcesLI(); 6823 } 6824 } 6825 } 6826 } 6827 6828 // The apk is forward locked (not public) if its code and resources 6829 // are kept in different files. (except for app in either system or 6830 // vendor path). 6831 // TODO grab this value from PackageSettings 6832 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6833 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 6834 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 6835 } 6836 } 6837 6838 // TODO: extend to support forward-locked splits 6839 String resourcePath = null; 6840 String baseResourcePath = null; 6841 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 6842 if (ps != null && ps.resourcePathString != null) { 6843 resourcePath = ps.resourcePathString; 6844 baseResourcePath = ps.resourcePathString; 6845 } else { 6846 // Should not happen at all. Just log an error. 6847 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 6848 } 6849 } else { 6850 resourcePath = pkg.codePath; 6851 baseResourcePath = pkg.baseCodePath; 6852 } 6853 6854 // Set application objects path explicitly. 6855 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 6856 pkg.setApplicationInfoCodePath(pkg.codePath); 6857 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 6858 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 6859 pkg.setApplicationInfoResourcePath(resourcePath); 6860 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 6861 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 6862 6863 // Note that we invoke the following method only if we are about to unpack an application 6864 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 6865 | SCAN_UPDATE_SIGNATURE, currentTime, user); 6866 6867 /* 6868 * If the system app should be overridden by a previously installed 6869 * data, hide the system app now and let the /data/app scan pick it up 6870 * again. 6871 */ 6872 if (shouldHideSystemApp) { 6873 synchronized (mPackages) { 6874 mSettings.disableSystemPackageLPw(pkg.packageName, true); 6875 } 6876 } 6877 6878 return scannedPkg; 6879 } 6880 6881 private static String fixProcessName(String defProcessName, 6882 String processName, int uid) { 6883 if (processName == null) { 6884 return defProcessName; 6885 } 6886 return processName; 6887 } 6888 6889 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 6890 throws PackageManagerException { 6891 if (pkgSetting.signatures.mSignatures != null) { 6892 // Already existing package. Make sure signatures match 6893 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 6894 == PackageManager.SIGNATURE_MATCH; 6895 if (!match) { 6896 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 6897 == PackageManager.SIGNATURE_MATCH; 6898 } 6899 if (!match) { 6900 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 6901 == PackageManager.SIGNATURE_MATCH; 6902 } 6903 if (!match) { 6904 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 6905 + pkg.packageName + " signatures do not match the " 6906 + "previously installed version; ignoring!"); 6907 } 6908 } 6909 6910 // Check for shared user signatures 6911 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 6912 // Already existing package. Make sure signatures match 6913 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6914 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 6915 if (!match) { 6916 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 6917 == PackageManager.SIGNATURE_MATCH; 6918 } 6919 if (!match) { 6920 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 6921 == PackageManager.SIGNATURE_MATCH; 6922 } 6923 if (!match) { 6924 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 6925 "Package " + pkg.packageName 6926 + " has no signatures that match those in shared user " 6927 + pkgSetting.sharedUser.name + "; ignoring!"); 6928 } 6929 } 6930 } 6931 6932 /** 6933 * Enforces that only the system UID or root's UID can call a method exposed 6934 * via Binder. 6935 * 6936 * @param message used as message if SecurityException is thrown 6937 * @throws SecurityException if the caller is not system or root 6938 */ 6939 private static final void enforceSystemOrRoot(String message) { 6940 final int uid = Binder.getCallingUid(); 6941 if (uid != Process.SYSTEM_UID && uid != 0) { 6942 throw new SecurityException(message); 6943 } 6944 } 6945 6946 @Override 6947 public void performFstrimIfNeeded() { 6948 enforceSystemOrRoot("Only the system can request fstrim"); 6949 6950 // Before everything else, see whether we need to fstrim. 6951 try { 6952 IMountService ms = PackageHelper.getMountService(); 6953 if (ms != null) { 6954 final boolean isUpgrade = isUpgrade(); 6955 boolean doTrim = isUpgrade; 6956 if (doTrim) { 6957 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 6958 } else { 6959 final long interval = android.provider.Settings.Global.getLong( 6960 mContext.getContentResolver(), 6961 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 6962 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 6963 if (interval > 0) { 6964 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 6965 if (timeSinceLast > interval) { 6966 doTrim = true; 6967 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 6968 + "; running immediately"); 6969 } 6970 } 6971 } 6972 if (doTrim) { 6973 if (!isFirstBoot()) { 6974 try { 6975 ActivityManagerNative.getDefault().showBootMessage( 6976 mContext.getResources().getString( 6977 R.string.android_upgrading_fstrim), true); 6978 } catch (RemoteException e) { 6979 } 6980 } 6981 ms.runMaintenance(); 6982 } 6983 } else { 6984 Slog.e(TAG, "Mount service unavailable!"); 6985 } 6986 } catch (RemoteException e) { 6987 // Can't happen; MountService is local 6988 } 6989 } 6990 6991 @Override 6992 public void updatePackagesIfNeeded() { 6993 enforceSystemOrRoot("Only the system can request package update"); 6994 6995 // We need to re-extract after an OTA. 6996 boolean causeUpgrade = isUpgrade(); 6997 6998 // First boot or factory reset. 6999 // Note: we also handle devices that are upgrading to N right now as if it is their 7000 // first boot, as they do not have profile data. 7001 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 7002 7003 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 7004 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 7005 7006 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 7007 return; 7008 } 7009 7010 List<PackageParser.Package> pkgs; 7011 synchronized (mPackages) { 7012 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 7013 } 7014 7015 UsageStatsManager usageMgr = 7016 (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 7017 7018 int curr = 0; 7019 int total = pkgs.size(); 7020 for (PackageParser.Package pkg : pkgs) { 7021 curr++; 7022 7023 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 7024 if (DEBUG_DEXOPT) { 7025 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 7026 } 7027 continue; 7028 } 7029 7030 if (!causeFirstBoot && usageMgr.isAppInactive(pkg.packageName)) { 7031 if (DEBUG_DEXOPT) { 7032 Log.i(TAG, "Skipping update of of idle app " + pkg.packageName); 7033 } 7034 continue; 7035 } 7036 7037 if (DEBUG_DEXOPT) { 7038 Log.i(TAG, "Extracting app " + curr + " of " + total + ": " + pkg.packageName); 7039 } 7040 7041 if (!isFirstBoot()) { 7042 try { 7043 ActivityManagerNative.getDefault().showBootMessage( 7044 mContext.getResources().getString(R.string.android_upgrading_apk, 7045 curr, total), true); 7046 } catch (RemoteException e) { 7047 } 7048 } 7049 7050 performDexOpt(pkg.packageName, 7051 null /* instructionSet */, 7052 false /* checkProfiles */, 7053 causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT, 7054 false /* force */); 7055 } 7056 } 7057 7058 @Override 7059 public void notifyPackageUse(String packageName) { 7060 synchronized (mPackages) { 7061 PackageParser.Package p = mPackages.get(packageName); 7062 if (p == null) { 7063 return; 7064 } 7065 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 7066 } 7067 } 7068 7069 // TODO: this is not used nor needed. Delete it. 7070 @Override 7071 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 7072 return performDexOptTraced(packageName, instructionSet, false /* checkProfiles */, 7073 getFullCompilerFilter(), false /* force */); 7074 } 7075 7076 @Override 7077 public boolean performDexOpt(String packageName, String instructionSet, 7078 boolean checkProfiles, int compileReason, boolean force) { 7079 return performDexOptTraced(packageName, instructionSet, checkProfiles, 7080 getCompilerFilterForReason(compileReason), force); 7081 } 7082 7083 @Override 7084 public boolean performDexOptMode(String packageName, String instructionSet, 7085 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7086 return performDexOptTraced(packageName, instructionSet, checkProfiles, 7087 targetCompilerFilter, force); 7088 } 7089 7090 private boolean performDexOptTraced(String packageName, String instructionSet, 7091 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7092 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7093 try { 7094 return performDexOptInternal(packageName, instructionSet, checkProfiles, 7095 targetCompilerFilter, force); 7096 } finally { 7097 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7098 } 7099 } 7100 7101 private boolean performDexOptInternal(String packageName, String instructionSet, 7102 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7103 PackageParser.Package p; 7104 final String targetInstructionSet; 7105 synchronized (mPackages) { 7106 p = mPackages.get(packageName); 7107 if (p == null) { 7108 return false; 7109 } 7110 mPackageUsage.write(false); 7111 7112 targetInstructionSet = instructionSet != null ? instructionSet : 7113 getPrimaryInstructionSet(p.applicationInfo); 7114 } 7115 long callingId = Binder.clearCallingIdentity(); 7116 try { 7117 synchronized (mInstallLock) { 7118 final String[] instructionSets = new String[] { targetInstructionSet }; 7119 int result = performDexOptInternalWithDependenciesLI(p, instructionSets, 7120 checkProfiles, targetCompilerFilter, force); 7121 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 7122 } 7123 } finally { 7124 Binder.restoreCallingIdentity(callingId); 7125 } 7126 } 7127 7128 public ArraySet<String> getOptimizablePackages() { 7129 ArraySet<String> pkgs = new ArraySet<String>(); 7130 synchronized (mPackages) { 7131 for (PackageParser.Package p : mPackages.values()) { 7132 if (PackageDexOptimizer.canOptimizePackage(p)) { 7133 pkgs.add(p.packageName); 7134 } 7135 } 7136 } 7137 return pkgs; 7138 } 7139 7140 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7141 String instructionSets[], boolean checkProfiles, String targetCompilerFilter, 7142 boolean force) { 7143 // Select the dex optimizer based on the force parameter. 7144 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7145 // allocate an object here. 7146 PackageDexOptimizer pdo = force 7147 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7148 : mPackageDexOptimizer; 7149 7150 // Optimize all dependencies first. Note: we ignore the return value and march on 7151 // on errors. 7152 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7153 if (!deps.isEmpty()) { 7154 for (PackageParser.Package depPackage : deps) { 7155 // TODO: Analyze and investigate if we (should) profile libraries. 7156 // Currently this will do a full compilation of the library by default. 7157 pdo.performDexOpt(depPackage, instructionSets, false /* checkProfiles */, 7158 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY)); 7159 } 7160 } 7161 7162 return pdo.performDexOpt(p, instructionSets, checkProfiles, targetCompilerFilter); 7163 } 7164 7165 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7166 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7167 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7168 Set<String> collectedNames = new HashSet<>(); 7169 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7170 7171 retValue.remove(p); 7172 7173 return retValue; 7174 } else { 7175 return Collections.emptyList(); 7176 } 7177 } 7178 7179 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7180 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7181 if (!collectedNames.contains(p.packageName)) { 7182 collectedNames.add(p.packageName); 7183 collected.add(p); 7184 7185 if (p.usesLibraries != null) { 7186 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7187 } 7188 if (p.usesOptionalLibraries != null) { 7189 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7190 collectedNames); 7191 } 7192 } 7193 } 7194 7195 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7196 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7197 for (String libName : libs) { 7198 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7199 if (libPkg != null) { 7200 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7201 } 7202 } 7203 } 7204 7205 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7206 synchronized (mPackages) { 7207 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7208 if (lib != null && lib.apk != null) { 7209 return mPackages.get(lib.apk); 7210 } 7211 } 7212 return null; 7213 } 7214 7215 public void shutdown() { 7216 mPackageUsage.write(true); 7217 } 7218 7219 @Override 7220 public void forceDexOpt(String packageName) { 7221 enforceSystemOrRoot("forceDexOpt"); 7222 7223 PackageParser.Package pkg; 7224 synchronized (mPackages) { 7225 pkg = mPackages.get(packageName); 7226 if (pkg == null) { 7227 throw new IllegalArgumentException("Unknown package: " + packageName); 7228 } 7229 } 7230 7231 synchronized (mInstallLock) { 7232 final String[] instructionSets = new String[] { 7233 getPrimaryInstructionSet(pkg.applicationInfo) }; 7234 7235 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7236 7237 // Whoever is calling forceDexOpt wants a fully compiled package. 7238 // Don't use profiles since that may cause compilation to be skipped. 7239 final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets, 7240 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7241 true /* force */); 7242 7243 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7244 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7245 throw new IllegalStateException("Failed to dexopt: " + res); 7246 } 7247 } 7248 } 7249 7250 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7251 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7252 Slog.w(TAG, "Unable to update from " + oldPkg.name 7253 + " to " + newPkg.packageName 7254 + ": old package not in system partition"); 7255 return false; 7256 } else if (mPackages.get(oldPkg.name) != null) { 7257 Slog.w(TAG, "Unable to update from " + oldPkg.name 7258 + " to " + newPkg.packageName 7259 + ": old package still exists"); 7260 return false; 7261 } 7262 return true; 7263 } 7264 7265 private boolean removeDataDirsLI(String volumeUuid, String packageName) { 7266 // TODO: triage flags as part of 26466827 7267 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 7268 7269 boolean res = true; 7270 final int[] users = sUserManager.getUserIds(); 7271 for (int user : users) { 7272 try { 7273 mInstaller.destroyAppData(volumeUuid, packageName, user, flags); 7274 } catch (InstallerException e) { 7275 Slog.w(TAG, "Failed to delete data directory", e); 7276 res = false; 7277 } 7278 } 7279 return res; 7280 } 7281 7282 void removeCodePathLI(File codePath) { 7283 if (codePath.isDirectory()) { 7284 try { 7285 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7286 } catch (InstallerException e) { 7287 Slog.w(TAG, "Failed to remove code path", e); 7288 } 7289 } else { 7290 codePath.delete(); 7291 } 7292 } 7293 7294 void destroyAppDataLI(String volumeUuid, String packageName, int userId, int flags) { 7295 try { 7296 mInstaller.destroyAppData(volumeUuid, packageName, userId, flags); 7297 } catch (InstallerException e) { 7298 Slog.w(TAG, "Failed to destroy app data", e); 7299 } 7300 } 7301 7302 void restoreconAppDataLI(String volumeUuid, String packageName, int userId, int flags, 7303 int appId, String seinfo) { 7304 try { 7305 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, seinfo); 7306 } catch (InstallerException e) { 7307 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 7308 } 7309 } 7310 7311 private void deleteProfilesLI(String packageName, boolean destroy) { 7312 final PackageParser.Package pkg; 7313 synchronized (mPackages) { 7314 pkg = mPackages.get(packageName); 7315 } 7316 if (pkg == null) { 7317 Slog.w(TAG, "Failed to delete profiles. No package: " + packageName); 7318 return; 7319 } 7320 deleteProfilesLI(pkg, destroy); 7321 } 7322 7323 private void deleteProfilesLI(PackageParser.Package pkg, boolean destroy) { 7324 try { 7325 if (destroy) { 7326 mInstaller.destroyAppProfiles(pkg.packageName); 7327 } else { 7328 mInstaller.clearAppProfiles(pkg.packageName); 7329 } 7330 } catch (InstallerException ex) { 7331 Log.e(TAG, "Could not delete profiles for package " + pkg.packageName); 7332 } 7333 } 7334 7335 private void deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 7336 final PackageParser.Package pkg; 7337 synchronized (mPackages) { 7338 pkg = mPackages.get(packageName); 7339 } 7340 if (pkg == null) { 7341 Slog.w(TAG, "Failed to delete code cache directory. No package: " + packageName); 7342 return; 7343 } 7344 deleteCodeCacheDirsLI(pkg); 7345 } 7346 7347 private void deleteCodeCacheDirsLI(PackageParser.Package pkg) { 7348 // TODO: triage flags as part of 26466827 7349 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 7350 7351 int[] users = sUserManager.getUserIds(); 7352 int res = 0; 7353 for (int user : users) { 7354 // Remove the parent code cache 7355 try { 7356 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, user, 7357 flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 7358 } catch (InstallerException e) { 7359 Slog.w(TAG, "Failed to delete code cache directory", e); 7360 } 7361 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7362 for (int i = 0; i < childCount; i++) { 7363 PackageParser.Package childPkg = pkg.childPackages.get(i); 7364 // Remove the child code cache 7365 try { 7366 mInstaller.clearAppData(childPkg.volumeUuid, childPkg.packageName, 7367 user, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 7368 } catch (InstallerException e) { 7369 Slog.w(TAG, "Failed to delete code cache directory", e); 7370 } 7371 } 7372 } 7373 } 7374 7375 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7376 long lastUpdateTime) { 7377 // Set parent install/update time 7378 PackageSetting ps = (PackageSetting) pkg.mExtras; 7379 if (ps != null) { 7380 ps.firstInstallTime = firstInstallTime; 7381 ps.lastUpdateTime = lastUpdateTime; 7382 } 7383 // Set children install/update time 7384 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7385 for (int i = 0; i < childCount; i++) { 7386 PackageParser.Package childPkg = pkg.childPackages.get(i); 7387 ps = (PackageSetting) childPkg.mExtras; 7388 if (ps != null) { 7389 ps.firstInstallTime = firstInstallTime; 7390 ps.lastUpdateTime = lastUpdateTime; 7391 } 7392 } 7393 } 7394 7395 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7396 PackageParser.Package changingLib) { 7397 if (file.path != null) { 7398 usesLibraryFiles.add(file.path); 7399 return; 7400 } 7401 PackageParser.Package p = mPackages.get(file.apk); 7402 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7403 // If we are doing this while in the middle of updating a library apk, 7404 // then we need to make sure to use that new apk for determining the 7405 // dependencies here. (We haven't yet finished committing the new apk 7406 // to the package manager state.) 7407 if (p == null || p.packageName.equals(changingLib.packageName)) { 7408 p = changingLib; 7409 } 7410 } 7411 if (p != null) { 7412 usesLibraryFiles.addAll(p.getAllCodePaths()); 7413 } 7414 } 7415 7416 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7417 PackageParser.Package changingLib) throws PackageManagerException { 7418 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7419 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7420 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7421 for (int i=0; i<N; i++) { 7422 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7423 if (file == null) { 7424 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7425 "Package " + pkg.packageName + " requires unavailable shared library " 7426 + pkg.usesLibraries.get(i) + "; failing!"); 7427 } 7428 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7429 } 7430 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7431 for (int i=0; i<N; i++) { 7432 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7433 if (file == null) { 7434 Slog.w(TAG, "Package " + pkg.packageName 7435 + " desires unavailable shared library " 7436 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7437 } else { 7438 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7439 } 7440 } 7441 N = usesLibraryFiles.size(); 7442 if (N > 0) { 7443 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7444 } else { 7445 pkg.usesLibraryFiles = null; 7446 } 7447 } 7448 } 7449 7450 private static boolean hasString(List<String> list, List<String> which) { 7451 if (list == null) { 7452 return false; 7453 } 7454 for (int i=list.size()-1; i>=0; i--) { 7455 for (int j=which.size()-1; j>=0; j--) { 7456 if (which.get(j).equals(list.get(i))) { 7457 return true; 7458 } 7459 } 7460 } 7461 return false; 7462 } 7463 7464 private void updateAllSharedLibrariesLPw() { 7465 for (PackageParser.Package pkg : mPackages.values()) { 7466 try { 7467 updateSharedLibrariesLPw(pkg, null); 7468 } catch (PackageManagerException e) { 7469 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7470 } 7471 } 7472 } 7473 7474 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7475 PackageParser.Package changingPkg) { 7476 ArrayList<PackageParser.Package> res = null; 7477 for (PackageParser.Package pkg : mPackages.values()) { 7478 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7479 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7480 if (res == null) { 7481 res = new ArrayList<PackageParser.Package>(); 7482 } 7483 res.add(pkg); 7484 try { 7485 updateSharedLibrariesLPw(pkg, changingPkg); 7486 } catch (PackageManagerException e) { 7487 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7488 } 7489 } 7490 } 7491 return res; 7492 } 7493 7494 /** 7495 * Derive the value of the {@code cpuAbiOverride} based on the provided 7496 * value and an optional stored value from the package settings. 7497 */ 7498 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7499 String cpuAbiOverride = null; 7500 7501 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7502 cpuAbiOverride = null; 7503 } else if (abiOverride != null) { 7504 cpuAbiOverride = abiOverride; 7505 } else if (settings != null) { 7506 cpuAbiOverride = settings.cpuAbiOverrideString; 7507 } 7508 7509 return cpuAbiOverride; 7510 } 7511 7512 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags, 7513 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7514 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7515 // If the package has children and this is the first dive in the function 7516 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7517 // whether all packages (parent and children) would be successfully scanned 7518 // before the actual scan since scanning mutates internal state and we want 7519 // to atomically install the package and its children. 7520 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7521 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7522 scanFlags |= SCAN_CHECK_ONLY; 7523 } 7524 } else { 7525 scanFlags &= ~SCAN_CHECK_ONLY; 7526 } 7527 7528 final PackageParser.Package scannedPkg; 7529 try { 7530 // Scan the parent 7531 scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user); 7532 // Scan the children 7533 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7534 for (int i = 0; i < childCount; i++) { 7535 PackageParser.Package childPkg = pkg.childPackages.get(i); 7536 scanPackageLI(childPkg, parseFlags, 7537 scanFlags, currentTime, user); 7538 } 7539 } finally { 7540 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7541 } 7542 7543 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7544 return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user); 7545 } 7546 7547 return scannedPkg; 7548 } 7549 7550 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 7551 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7552 boolean success = false; 7553 try { 7554 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 7555 currentTime, user); 7556 success = true; 7557 return res; 7558 } finally { 7559 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 7560 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 7561 } 7562 } 7563 } 7564 7565 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 7566 int scanFlags, long currentTime, UserHandle user) 7567 throws PackageManagerException { 7568 final File scanFile = new File(pkg.codePath); 7569 if (pkg.applicationInfo.getCodePath() == null || 7570 pkg.applicationInfo.getResourcePath() == null) { 7571 // Bail out. The resource and code paths haven't been set. 7572 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7573 "Code and resource paths haven't been set correctly"); 7574 } 7575 7576 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 7577 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 7578 } else { 7579 // Only allow system apps to be flagged as core apps. 7580 pkg.coreApp = false; 7581 } 7582 7583 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 7584 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7585 } 7586 7587 if (mCustomResolverComponentName != null && 7588 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 7589 setUpCustomResolverActivity(pkg); 7590 } 7591 7592 if (pkg.packageName.equals("android")) { 7593 synchronized (mPackages) { 7594 if (mAndroidApplication != null) { 7595 Slog.w(TAG, "*************************************************"); 7596 Slog.w(TAG, "Core android package being redefined. Skipping."); 7597 Slog.w(TAG, " file=" + scanFile); 7598 Slog.w(TAG, "*************************************************"); 7599 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7600 "Core android package being redefined. Skipping."); 7601 } 7602 7603 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7604 // Set up information for our fall-back user intent resolution activity. 7605 mPlatformPackage = pkg; 7606 pkg.mVersionCode = mSdkVersion; 7607 mAndroidApplication = pkg.applicationInfo; 7608 7609 if (!mResolverReplaced) { 7610 mResolveActivity.applicationInfo = mAndroidApplication; 7611 mResolveActivity.name = ResolverActivity.class.getName(); 7612 mResolveActivity.packageName = mAndroidApplication.packageName; 7613 mResolveActivity.processName = "system:ui"; 7614 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7615 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 7616 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 7617 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 7618 mResolveActivity.exported = true; 7619 mResolveActivity.enabled = true; 7620 mResolveInfo.activityInfo = mResolveActivity; 7621 mResolveInfo.priority = 0; 7622 mResolveInfo.preferredOrder = 0; 7623 mResolveInfo.match = 0; 7624 mResolveComponentName = new ComponentName( 7625 mAndroidApplication.packageName, mResolveActivity.name); 7626 } 7627 } 7628 } 7629 } 7630 7631 if (DEBUG_PACKAGE_SCANNING) { 7632 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7633 Log.d(TAG, "Scanning package " + pkg.packageName); 7634 } 7635 7636 synchronized (mPackages) { 7637 if (mPackages.containsKey(pkg.packageName) 7638 || mSharedLibraries.containsKey(pkg.packageName)) { 7639 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7640 "Application package " + pkg.packageName 7641 + " already installed. Skipping duplicate."); 7642 } 7643 7644 // If we're only installing presumed-existing packages, require that the 7645 // scanned APK is both already known and at the path previously established 7646 // for it. Previously unknown packages we pick up normally, but if we have an 7647 // a priori expectation about this package's install presence, enforce it. 7648 // With a singular exception for new system packages. When an OTA contains 7649 // a new system package, we allow the codepath to change from a system location 7650 // to the user-installed location. If we don't allow this change, any newer, 7651 // user-installed version of the application will be ignored. 7652 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 7653 if (mExpectingBetter.containsKey(pkg.packageName)) { 7654 logCriticalInfo(Log.WARN, 7655 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 7656 } else { 7657 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 7658 if (known != null) { 7659 if (DEBUG_PACKAGE_SCANNING) { 7660 Log.d(TAG, "Examining " + pkg.codePath 7661 + " and requiring known paths " + known.codePathString 7662 + " & " + known.resourcePathString); 7663 } 7664 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 7665 || !pkg.applicationInfo.getResourcePath().equals( 7666 known.resourcePathString)) { 7667 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 7668 "Application package " + pkg.packageName 7669 + " found at " + pkg.applicationInfo.getCodePath() 7670 + " but expected at " + known.codePathString 7671 + "; ignoring."); 7672 } 7673 } 7674 } 7675 } 7676 } 7677 7678 // Initialize package source and resource directories 7679 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 7680 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 7681 7682 SharedUserSetting suid = null; 7683 PackageSetting pkgSetting = null; 7684 7685 if (!isSystemApp(pkg)) { 7686 // Only system apps can use these features. 7687 pkg.mOriginalPackages = null; 7688 pkg.mRealPackage = null; 7689 pkg.mAdoptPermissions = null; 7690 } 7691 7692 // Getting the package setting may have a side-effect, so if we 7693 // are only checking if scan would succeed, stash a copy of the 7694 // old setting to restore at the end. 7695 PackageSetting nonMutatedPs = null; 7696 7697 // writer 7698 synchronized (mPackages) { 7699 if (pkg.mSharedUserId != null) { 7700 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 7701 if (suid == null) { 7702 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7703 "Creating application package " + pkg.packageName 7704 + " for shared user failed"); 7705 } 7706 if (DEBUG_PACKAGE_SCANNING) { 7707 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7708 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 7709 + "): packages=" + suid.packages); 7710 } 7711 } 7712 7713 // Check if we are renaming from an original package name. 7714 PackageSetting origPackage = null; 7715 String realName = null; 7716 if (pkg.mOriginalPackages != null) { 7717 // This package may need to be renamed to a previously 7718 // installed name. Let's check on that... 7719 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 7720 if (pkg.mOriginalPackages.contains(renamed)) { 7721 // This package had originally been installed as the 7722 // original name, and we have already taken care of 7723 // transitioning to the new one. Just update the new 7724 // one to continue using the old name. 7725 realName = pkg.mRealPackage; 7726 if (!pkg.packageName.equals(renamed)) { 7727 // Callers into this function may have already taken 7728 // care of renaming the package; only do it here if 7729 // it is not already done. 7730 pkg.setPackageName(renamed); 7731 } 7732 7733 } else { 7734 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 7735 if ((origPackage = mSettings.peekPackageLPr( 7736 pkg.mOriginalPackages.get(i))) != null) { 7737 // We do have the package already installed under its 7738 // original name... should we use it? 7739 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 7740 // New package is not compatible with original. 7741 origPackage = null; 7742 continue; 7743 } else if (origPackage.sharedUser != null) { 7744 // Make sure uid is compatible between packages. 7745 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 7746 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 7747 + " to " + pkg.packageName + ": old uid " 7748 + origPackage.sharedUser.name 7749 + " differs from " + pkg.mSharedUserId); 7750 origPackage = null; 7751 continue; 7752 } 7753 } else { 7754 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 7755 + pkg.packageName + " to old name " + origPackage.name); 7756 } 7757 break; 7758 } 7759 } 7760 } 7761 } 7762 7763 if (mTransferedPackages.contains(pkg.packageName)) { 7764 Slog.w(TAG, "Package " + pkg.packageName 7765 + " was transferred to another, but its .apk remains"); 7766 } 7767 7768 // See comments in nonMutatedPs declaration 7769 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7770 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 7771 if (foundPs != null) { 7772 nonMutatedPs = new PackageSetting(foundPs); 7773 } 7774 } 7775 7776 // Just create the setting, don't add it yet. For already existing packages 7777 // the PkgSetting exists already and doesn't have to be created. 7778 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 7779 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 7780 pkg.applicationInfo.primaryCpuAbi, 7781 pkg.applicationInfo.secondaryCpuAbi, 7782 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 7783 user, false); 7784 if (pkgSetting == null) { 7785 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7786 "Creating application package " + pkg.packageName + " failed"); 7787 } 7788 7789 if (pkgSetting.origPackage != null) { 7790 // If we are first transitioning from an original package, 7791 // fix up the new package's name now. We need to do this after 7792 // looking up the package under its new name, so getPackageLP 7793 // can take care of fiddling things correctly. 7794 pkg.setPackageName(origPackage.name); 7795 7796 // File a report about this. 7797 String msg = "New package " + pkgSetting.realName 7798 + " renamed to replace old package " + pkgSetting.name; 7799 reportSettingsProblem(Log.WARN, msg); 7800 7801 // Make a note of it. 7802 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7803 mTransferedPackages.add(origPackage.name); 7804 } 7805 7806 // No longer need to retain this. 7807 pkgSetting.origPackage = null; 7808 } 7809 7810 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 7811 // Make a note of it. 7812 mTransferedPackages.add(pkg.packageName); 7813 } 7814 7815 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 7816 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 7817 } 7818 7819 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7820 // Check all shared libraries and map to their actual file path. 7821 // We only do this here for apps not on a system dir, because those 7822 // are the only ones that can fail an install due to this. We 7823 // will take care of the system apps by updating all of their 7824 // library paths after the scan is done. 7825 updateSharedLibrariesLPw(pkg, null); 7826 } 7827 7828 if (mFoundPolicyFile) { 7829 SELinuxMMAC.assignSeinfoValue(pkg); 7830 } 7831 7832 pkg.applicationInfo.uid = pkgSetting.appId; 7833 pkg.mExtras = pkgSetting; 7834 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 7835 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 7836 // We just determined the app is signed correctly, so bring 7837 // over the latest parsed certs. 7838 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7839 } else { 7840 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7841 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7842 "Package " + pkg.packageName + " upgrade keys do not match the " 7843 + "previously installed version"); 7844 } else { 7845 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7846 String msg = "System package " + pkg.packageName 7847 + " signature changed; retaining data."; 7848 reportSettingsProblem(Log.WARN, msg); 7849 } 7850 } 7851 } else { 7852 try { 7853 verifySignaturesLP(pkgSetting, pkg); 7854 // We just determined the app is signed correctly, so bring 7855 // over the latest parsed certs. 7856 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7857 } catch (PackageManagerException e) { 7858 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7859 throw e; 7860 } 7861 // The signature has changed, but this package is in the system 7862 // image... let's recover! 7863 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7864 // However... if this package is part of a shared user, but it 7865 // doesn't match the signature of the shared user, let's fail. 7866 // What this means is that you can't change the signatures 7867 // associated with an overall shared user, which doesn't seem all 7868 // that unreasonable. 7869 if (pkgSetting.sharedUser != null) { 7870 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7871 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 7872 throw new PackageManagerException( 7873 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 7874 "Signature mismatch for shared user: " 7875 + pkgSetting.sharedUser); 7876 } 7877 } 7878 // File a report about this. 7879 String msg = "System package " + pkg.packageName 7880 + " signature changed; retaining data."; 7881 reportSettingsProblem(Log.WARN, msg); 7882 } 7883 } 7884 // Verify that this new package doesn't have any content providers 7885 // that conflict with existing packages. Only do this if the 7886 // package isn't already installed, since we don't want to break 7887 // things that are installed. 7888 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 7889 final int N = pkg.providers.size(); 7890 int i; 7891 for (i=0; i<N; i++) { 7892 PackageParser.Provider p = pkg.providers.get(i); 7893 if (p.info.authority != null) { 7894 String names[] = p.info.authority.split(";"); 7895 for (int j = 0; j < names.length; j++) { 7896 if (mProvidersByAuthority.containsKey(names[j])) { 7897 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7898 final String otherPackageName = 7899 ((other != null && other.getComponentName() != null) ? 7900 other.getComponentName().getPackageName() : "?"); 7901 throw new PackageManagerException( 7902 INSTALL_FAILED_CONFLICTING_PROVIDER, 7903 "Can't install because provider name " + names[j] 7904 + " (in package " + pkg.applicationInfo.packageName 7905 + ") is already used by " + otherPackageName); 7906 } 7907 } 7908 } 7909 } 7910 } 7911 7912 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 7913 // This package wants to adopt ownership of permissions from 7914 // another package. 7915 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 7916 final String origName = pkg.mAdoptPermissions.get(i); 7917 final PackageSetting orig = mSettings.peekPackageLPr(origName); 7918 if (orig != null) { 7919 if (verifyPackageUpdateLPr(orig, pkg)) { 7920 Slog.i(TAG, "Adopting permissions from " + origName + " to " 7921 + pkg.packageName); 7922 mSettings.transferPermissionsLPw(origName, pkg.packageName); 7923 } 7924 } 7925 } 7926 } 7927 } 7928 7929 final String pkgName = pkg.packageName; 7930 7931 final long scanFileTime = scanFile.lastModified(); 7932 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 7933 pkg.applicationInfo.processName = fixProcessName( 7934 pkg.applicationInfo.packageName, 7935 pkg.applicationInfo.processName, 7936 pkg.applicationInfo.uid); 7937 7938 if (pkg != mPlatformPackage) { 7939 // Get all of our default paths setup 7940 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 7941 } 7942 7943 final String path = scanFile.getPath(); 7944 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 7945 7946 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 7947 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 7948 7949 // Some system apps still use directory structure for native libraries 7950 // in which case we might end up not detecting abi solely based on apk 7951 // structure. Try to detect abi based on directory structure. 7952 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 7953 pkg.applicationInfo.primaryCpuAbi == null) { 7954 setBundledAppAbisAndRoots(pkg, pkgSetting); 7955 setNativeLibraryPaths(pkg); 7956 } 7957 7958 } else { 7959 if ((scanFlags & SCAN_MOVE) != 0) { 7960 // We haven't run dex-opt for this move (since we've moved the compiled output too) 7961 // but we already have this packages package info in the PackageSetting. We just 7962 // use that and derive the native library path based on the new codepath. 7963 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 7964 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 7965 } 7966 7967 // Set native library paths again. For moves, the path will be updated based on the 7968 // ABIs we've determined above. For non-moves, the path will be updated based on the 7969 // ABIs we determined during compilation, but the path will depend on the final 7970 // package path (after the rename away from the stage path). 7971 setNativeLibraryPaths(pkg); 7972 } 7973 7974 // This is a special case for the "system" package, where the ABI is 7975 // dictated by the zygote configuration (and init.rc). We should keep track 7976 // of this ABI so that we can deal with "normal" applications that run under 7977 // the same UID correctly. 7978 if (mPlatformPackage == pkg) { 7979 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 7980 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 7981 } 7982 7983 // If there's a mismatch between the abi-override in the package setting 7984 // and the abiOverride specified for the install. Warn about this because we 7985 // would've already compiled the app without taking the package setting into 7986 // account. 7987 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 7988 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 7989 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 7990 " for package " + pkg.packageName); 7991 } 7992 } 7993 7994 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7995 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7996 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 7997 7998 // Copy the derived override back to the parsed package, so that we can 7999 // update the package settings accordingly. 8000 pkg.cpuAbiOverride = cpuAbiOverride; 8001 8002 if (DEBUG_ABI_SELECTION) { 8003 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 8004 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 8005 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 8006 } 8007 8008 // Push the derived path down into PackageSettings so we know what to 8009 // clean up at uninstall time. 8010 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 8011 8012 if (DEBUG_ABI_SELECTION) { 8013 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 8014 " primary=" + pkg.applicationInfo.primaryCpuAbi + 8015 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 8016 } 8017 8018 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 8019 // We don't do this here during boot because we can do it all 8020 // at once after scanning all existing packages. 8021 // 8022 // We also do this *before* we perform dexopt on this package, so that 8023 // we can avoid redundant dexopts, and also to make sure we've got the 8024 // code and package path correct. 8025 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 8026 pkg, true /* boot complete */); 8027 } 8028 8029 if (mFactoryTest && pkg.requestedPermissions.contains( 8030 android.Manifest.permission.FACTORY_TEST)) { 8031 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 8032 } 8033 8034 ArrayList<PackageParser.Package> clientLibPkgs = null; 8035 8036 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8037 if (nonMutatedPs != null) { 8038 synchronized (mPackages) { 8039 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 8040 } 8041 } 8042 return pkg; 8043 } 8044 8045 // Only privileged apps and updated privileged apps can add child packages. 8046 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 8047 if ((parseFlags & PARSE_IS_PRIVILEGED) == 0) { 8048 throw new PackageManagerException("Only privileged apps and updated " 8049 + "privileged apps can add child packages. Ignoring package " 8050 + pkg.packageName); 8051 } 8052 final int childCount = pkg.childPackages.size(); 8053 for (int i = 0; i < childCount; i++) { 8054 PackageParser.Package childPkg = pkg.childPackages.get(i); 8055 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 8056 childPkg.packageName)) { 8057 throw new PackageManagerException("Cannot override a child package of " 8058 + "another disabled system app. Ignoring package " + pkg.packageName); 8059 } 8060 } 8061 } 8062 8063 // writer 8064 synchronized (mPackages) { 8065 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8066 // Only system apps can add new shared libraries. 8067 if (pkg.libraryNames != null) { 8068 for (int i=0; i<pkg.libraryNames.size(); i++) { 8069 String name = pkg.libraryNames.get(i); 8070 boolean allowed = false; 8071 if (pkg.isUpdatedSystemApp()) { 8072 // New library entries can only be added through the 8073 // system image. This is important to get rid of a lot 8074 // of nasty edge cases: for example if we allowed a non- 8075 // system update of the app to add a library, then uninstalling 8076 // the update would make the library go away, and assumptions 8077 // we made such as through app install filtering would now 8078 // have allowed apps on the device which aren't compatible 8079 // with it. Better to just have the restriction here, be 8080 // conservative, and create many fewer cases that can negatively 8081 // impact the user experience. 8082 final PackageSetting sysPs = mSettings 8083 .getDisabledSystemPkgLPr(pkg.packageName); 8084 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 8085 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 8086 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 8087 allowed = true; 8088 break; 8089 } 8090 } 8091 } 8092 } else { 8093 allowed = true; 8094 } 8095 if (allowed) { 8096 if (!mSharedLibraries.containsKey(name)) { 8097 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 8098 } else if (!name.equals(pkg.packageName)) { 8099 Slog.w(TAG, "Package " + pkg.packageName + " library " 8100 + name + " already exists; skipping"); 8101 } 8102 } else { 8103 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 8104 + name + " that is not declared on system image; skipping"); 8105 } 8106 } 8107 if ((scanFlags & SCAN_BOOTING) == 0) { 8108 // If we are not booting, we need to update any applications 8109 // that are clients of our shared library. If we are booting, 8110 // this will all be done once the scan is complete. 8111 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 8112 } 8113 } 8114 } 8115 } 8116 8117 // Request the ActivityManager to kill the process(only for existing packages) 8118 // so that we do not end up in a confused state while the user is still using the older 8119 // version of the application while the new one gets installed. 8120 final boolean isReplacing = (scanFlags & SCAN_REPLACING) != 0; 8121 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 8122 if (killApp) { 8123 if (isReplacing) { 8124 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication"); 8125 8126 killApplication(pkg.applicationInfo.packageName, 8127 pkg.applicationInfo.uid, "replace pkg"); 8128 8129 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8130 } 8131 } 8132 8133 // Also need to kill any apps that are dependent on the library. 8134 if (clientLibPkgs != null) { 8135 for (int i=0; i<clientLibPkgs.size(); i++) { 8136 PackageParser.Package clientPkg = clientLibPkgs.get(i); 8137 killApplication(clientPkg.applicationInfo.packageName, 8138 clientPkg.applicationInfo.uid, "update lib"); 8139 } 8140 } 8141 8142 // Make sure we're not adding any bogus keyset info 8143 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8144 ksms.assertScannedPackageValid(pkg); 8145 8146 // writer 8147 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 8148 8149 boolean createIdmapFailed = false; 8150 synchronized (mPackages) { 8151 // We don't expect installation to fail beyond this point 8152 8153 // Add the new setting to mSettings 8154 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 8155 // Add the new setting to mPackages 8156 mPackages.put(pkg.applicationInfo.packageName, pkg); 8157 // Make sure we don't accidentally delete its data. 8158 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 8159 while (iter.hasNext()) { 8160 PackageCleanItem item = iter.next(); 8161 if (pkgName.equals(item.packageName)) { 8162 iter.remove(); 8163 } 8164 } 8165 8166 // Take care of first install / last update times. 8167 if (currentTime != 0) { 8168 if (pkgSetting.firstInstallTime == 0) { 8169 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8170 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 8171 pkgSetting.lastUpdateTime = currentTime; 8172 } 8173 } else if (pkgSetting.firstInstallTime == 0) { 8174 // We need *something*. Take time time stamp of the file. 8175 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8176 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8177 if (scanFileTime != pkgSetting.timeStamp) { 8178 // A package on the system image has changed; consider this 8179 // to be an update. 8180 pkgSetting.lastUpdateTime = scanFileTime; 8181 } 8182 } 8183 8184 // Add the package's KeySets to the global KeySetManagerService 8185 ksms.addScannedPackageLPw(pkg); 8186 8187 int N = pkg.providers.size(); 8188 StringBuilder r = null; 8189 int i; 8190 for (i=0; i<N; i++) { 8191 PackageParser.Provider p = pkg.providers.get(i); 8192 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 8193 p.info.processName, pkg.applicationInfo.uid); 8194 mProviders.addProvider(p); 8195 p.syncable = p.info.isSyncable; 8196 if (p.info.authority != null) { 8197 String names[] = p.info.authority.split(";"); 8198 p.info.authority = null; 8199 for (int j = 0; j < names.length; j++) { 8200 if (j == 1 && p.syncable) { 8201 // We only want the first authority for a provider to possibly be 8202 // syncable, so if we already added this provider using a different 8203 // authority clear the syncable flag. We copy the provider before 8204 // changing it because the mProviders object contains a reference 8205 // to a provider that we don't want to change. 8206 // Only do this for the second authority since the resulting provider 8207 // object can be the same for all future authorities for this provider. 8208 p = new PackageParser.Provider(p); 8209 p.syncable = false; 8210 } 8211 if (!mProvidersByAuthority.containsKey(names[j])) { 8212 mProvidersByAuthority.put(names[j], p); 8213 if (p.info.authority == null) { 8214 p.info.authority = names[j]; 8215 } else { 8216 p.info.authority = p.info.authority + ";" + names[j]; 8217 } 8218 if (DEBUG_PACKAGE_SCANNING) { 8219 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 8220 Log.d(TAG, "Registered content provider: " + names[j] 8221 + ", className = " + p.info.name + ", isSyncable = " 8222 + p.info.isSyncable); 8223 } 8224 } else { 8225 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8226 Slog.w(TAG, "Skipping provider name " + names[j] + 8227 " (in package " + pkg.applicationInfo.packageName + 8228 "): name already used by " 8229 + ((other != null && other.getComponentName() != null) 8230 ? other.getComponentName().getPackageName() : "?")); 8231 } 8232 } 8233 } 8234 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8235 if (r == null) { 8236 r = new StringBuilder(256); 8237 } else { 8238 r.append(' '); 8239 } 8240 r.append(p.info.name); 8241 } 8242 } 8243 if (r != null) { 8244 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8245 } 8246 8247 N = pkg.services.size(); 8248 r = null; 8249 for (i=0; i<N; i++) { 8250 PackageParser.Service s = pkg.services.get(i); 8251 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8252 s.info.processName, pkg.applicationInfo.uid); 8253 mServices.addService(s); 8254 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8255 if (r == null) { 8256 r = new StringBuilder(256); 8257 } else { 8258 r.append(' '); 8259 } 8260 r.append(s.info.name); 8261 } 8262 } 8263 if (r != null) { 8264 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8265 } 8266 8267 N = pkg.receivers.size(); 8268 r = null; 8269 for (i=0; i<N; i++) { 8270 PackageParser.Activity a = pkg.receivers.get(i); 8271 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8272 a.info.processName, pkg.applicationInfo.uid); 8273 mReceivers.addActivity(a, "receiver"); 8274 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8275 if (r == null) { 8276 r = new StringBuilder(256); 8277 } else { 8278 r.append(' '); 8279 } 8280 r.append(a.info.name); 8281 } 8282 } 8283 if (r != null) { 8284 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8285 } 8286 8287 N = pkg.activities.size(); 8288 r = null; 8289 for (i=0; i<N; i++) { 8290 PackageParser.Activity a = pkg.activities.get(i); 8291 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8292 a.info.processName, pkg.applicationInfo.uid); 8293 mActivities.addActivity(a, "activity"); 8294 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8295 if (r == null) { 8296 r = new StringBuilder(256); 8297 } else { 8298 r.append(' '); 8299 } 8300 r.append(a.info.name); 8301 } 8302 } 8303 if (r != null) { 8304 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8305 } 8306 8307 N = pkg.permissionGroups.size(); 8308 r = null; 8309 for (i=0; i<N; i++) { 8310 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8311 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8312 if (cur == null) { 8313 mPermissionGroups.put(pg.info.name, pg); 8314 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8315 if (r == null) { 8316 r = new StringBuilder(256); 8317 } else { 8318 r.append(' '); 8319 } 8320 r.append(pg.info.name); 8321 } 8322 } else { 8323 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8324 + pg.info.packageName + " ignored: original from " 8325 + cur.info.packageName); 8326 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8327 if (r == null) { 8328 r = new StringBuilder(256); 8329 } else { 8330 r.append(' '); 8331 } 8332 r.append("DUP:"); 8333 r.append(pg.info.name); 8334 } 8335 } 8336 } 8337 if (r != null) { 8338 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8339 } 8340 8341 N = pkg.permissions.size(); 8342 r = null; 8343 for (i=0; i<N; i++) { 8344 PackageParser.Permission p = pkg.permissions.get(i); 8345 8346 // Assume by default that we did not install this permission into the system. 8347 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8348 8349 // Now that permission groups have a special meaning, we ignore permission 8350 // groups for legacy apps to prevent unexpected behavior. In particular, 8351 // permissions for one app being granted to someone just becase they happen 8352 // to be in a group defined by another app (before this had no implications). 8353 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8354 p.group = mPermissionGroups.get(p.info.group); 8355 // Warn for a permission in an unknown group. 8356 if (p.info.group != null && p.group == null) { 8357 Slog.w(TAG, "Permission " + p.info.name + " from package " 8358 + p.info.packageName + " in an unknown group " + p.info.group); 8359 } 8360 } 8361 8362 ArrayMap<String, BasePermission> permissionMap = 8363 p.tree ? mSettings.mPermissionTrees 8364 : mSettings.mPermissions; 8365 BasePermission bp = permissionMap.get(p.info.name); 8366 8367 // Allow system apps to redefine non-system permissions 8368 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8369 final boolean currentOwnerIsSystem = (bp.perm != null 8370 && isSystemApp(bp.perm.owner)); 8371 if (isSystemApp(p.owner)) { 8372 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8373 // It's a built-in permission and no owner, take ownership now 8374 bp.packageSetting = pkgSetting; 8375 bp.perm = p; 8376 bp.uid = pkg.applicationInfo.uid; 8377 bp.sourcePackage = p.info.packageName; 8378 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8379 } else if (!currentOwnerIsSystem) { 8380 String msg = "New decl " + p.owner + " of permission " 8381 + p.info.name + " is system; overriding " + bp.sourcePackage; 8382 reportSettingsProblem(Log.WARN, msg); 8383 bp = null; 8384 } 8385 } 8386 } 8387 8388 if (bp == null) { 8389 bp = new BasePermission(p.info.name, p.info.packageName, 8390 BasePermission.TYPE_NORMAL); 8391 permissionMap.put(p.info.name, bp); 8392 } 8393 8394 if (bp.perm == null) { 8395 if (bp.sourcePackage == null 8396 || bp.sourcePackage.equals(p.info.packageName)) { 8397 BasePermission tree = findPermissionTreeLP(p.info.name); 8398 if (tree == null 8399 || tree.sourcePackage.equals(p.info.packageName)) { 8400 bp.packageSetting = pkgSetting; 8401 bp.perm = p; 8402 bp.uid = pkg.applicationInfo.uid; 8403 bp.sourcePackage = p.info.packageName; 8404 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8405 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8406 if (r == null) { 8407 r = new StringBuilder(256); 8408 } else { 8409 r.append(' '); 8410 } 8411 r.append(p.info.name); 8412 } 8413 } else { 8414 Slog.w(TAG, "Permission " + p.info.name + " from package " 8415 + p.info.packageName + " ignored: base tree " 8416 + tree.name + " is from package " 8417 + tree.sourcePackage); 8418 } 8419 } else { 8420 Slog.w(TAG, "Permission " + p.info.name + " from package " 8421 + p.info.packageName + " ignored: original from " 8422 + bp.sourcePackage); 8423 } 8424 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8425 if (r == null) { 8426 r = new StringBuilder(256); 8427 } else { 8428 r.append(' '); 8429 } 8430 r.append("DUP:"); 8431 r.append(p.info.name); 8432 } 8433 if (bp.perm == p) { 8434 bp.protectionLevel = p.info.protectionLevel; 8435 } 8436 } 8437 8438 if (r != null) { 8439 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 8440 } 8441 8442 N = pkg.instrumentation.size(); 8443 r = null; 8444 for (i=0; i<N; i++) { 8445 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8446 a.info.packageName = pkg.applicationInfo.packageName; 8447 a.info.sourceDir = pkg.applicationInfo.sourceDir; 8448 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 8449 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 8450 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 8451 a.info.dataDir = pkg.applicationInfo.dataDir; 8452 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 8453 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 8454 8455 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 8456 // need other information about the application, like the ABI and what not ? 8457 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 8458 mInstrumentation.put(a.getComponentName(), a); 8459 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8460 if (r == null) { 8461 r = new StringBuilder(256); 8462 } else { 8463 r.append(' '); 8464 } 8465 r.append(a.info.name); 8466 } 8467 } 8468 if (r != null) { 8469 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 8470 } 8471 8472 if (pkg.protectedBroadcasts != null) { 8473 N = pkg.protectedBroadcasts.size(); 8474 for (i=0; i<N; i++) { 8475 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 8476 } 8477 } 8478 8479 pkgSetting.setTimeStamp(scanFileTime); 8480 8481 // Create idmap files for pairs of (packages, overlay packages). 8482 // Note: "android", ie framework-res.apk, is handled by native layers. 8483 if (pkg.mOverlayTarget != null) { 8484 // This is an overlay package. 8485 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 8486 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 8487 mOverlays.put(pkg.mOverlayTarget, 8488 new ArrayMap<String, PackageParser.Package>()); 8489 } 8490 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 8491 map.put(pkg.packageName, pkg); 8492 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 8493 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 8494 createIdmapFailed = true; 8495 } 8496 } 8497 } else if (mOverlays.containsKey(pkg.packageName) && 8498 !pkg.packageName.equals("android")) { 8499 // This is a regular package, with one or more known overlay packages. 8500 createIdmapsForPackageLI(pkg); 8501 } 8502 } 8503 8504 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8505 8506 if (createIdmapFailed) { 8507 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8508 "scanPackageLI failed to createIdmap"); 8509 } 8510 return pkg; 8511 } 8512 8513 /** 8514 * Derive the ABI of a non-system package located at {@code scanFile}. This information 8515 * is derived purely on the basis of the contents of {@code scanFile} and 8516 * {@code cpuAbiOverride}. 8517 * 8518 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 8519 */ 8520 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 8521 String cpuAbiOverride, boolean extractLibs) 8522 throws PackageManagerException { 8523 // TODO: We can probably be smarter about this stuff. For installed apps, 8524 // we can calculate this information at install time once and for all. For 8525 // system apps, we can probably assume that this information doesn't change 8526 // after the first boot scan. As things stand, we do lots of unnecessary work. 8527 8528 // Give ourselves some initial paths; we'll come back for another 8529 // pass once we've determined ABI below. 8530 setNativeLibraryPaths(pkg); 8531 8532 // We would never need to extract libs for forward-locked and external packages, 8533 // since the container service will do it for us. We shouldn't attempt to 8534 // extract libs from system app when it was not updated. 8535 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 8536 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 8537 extractLibs = false; 8538 } 8539 8540 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 8541 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 8542 8543 NativeLibraryHelper.Handle handle = null; 8544 try { 8545 handle = NativeLibraryHelper.Handle.create(pkg); 8546 // TODO(multiArch): This can be null for apps that didn't go through the 8547 // usual installation process. We can calculate it again, like we 8548 // do during install time. 8549 // 8550 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 8551 // unnecessary. 8552 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 8553 8554 // Null out the abis so that they can be recalculated. 8555 pkg.applicationInfo.primaryCpuAbi = null; 8556 pkg.applicationInfo.secondaryCpuAbi = null; 8557 if (isMultiArch(pkg.applicationInfo)) { 8558 // Warn if we've set an abiOverride for multi-lib packages.. 8559 // By definition, we need to copy both 32 and 64 bit libraries for 8560 // such packages. 8561 if (pkg.cpuAbiOverride != null 8562 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 8563 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 8564 } 8565 8566 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 8567 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 8568 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 8569 if (extractLibs) { 8570 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8571 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 8572 useIsaSpecificSubdirs); 8573 } else { 8574 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 8575 } 8576 } 8577 8578 maybeThrowExceptionForMultiArchCopy( 8579 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 8580 8581 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 8582 if (extractLibs) { 8583 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8584 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 8585 useIsaSpecificSubdirs); 8586 } else { 8587 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 8588 } 8589 } 8590 8591 maybeThrowExceptionForMultiArchCopy( 8592 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 8593 8594 if (abi64 >= 0) { 8595 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 8596 } 8597 8598 if (abi32 >= 0) { 8599 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 8600 if (abi64 >= 0) { 8601 if (cpuAbiOverride == null && pkg.use32bitAbi) { 8602 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 8603 pkg.applicationInfo.primaryCpuAbi = abi; 8604 } else { 8605 pkg.applicationInfo.secondaryCpuAbi = abi; 8606 } 8607 } else { 8608 pkg.applicationInfo.primaryCpuAbi = abi; 8609 } 8610 } 8611 8612 } else { 8613 String[] abiList = (cpuAbiOverride != null) ? 8614 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 8615 8616 // Enable gross and lame hacks for apps that are built with old 8617 // SDK tools. We must scan their APKs for renderscript bitcode and 8618 // not launch them if it's present. Don't bother checking on devices 8619 // that don't have 64 bit support. 8620 boolean needsRenderScriptOverride = false; 8621 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 8622 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 8623 abiList = Build.SUPPORTED_32_BIT_ABIS; 8624 needsRenderScriptOverride = true; 8625 } 8626 8627 final int copyRet; 8628 if (extractLibs) { 8629 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8630 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 8631 } else { 8632 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 8633 } 8634 8635 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 8636 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 8637 "Error unpackaging native libs for app, errorCode=" + copyRet); 8638 } 8639 8640 if (copyRet >= 0) { 8641 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 8642 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 8643 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 8644 } else if (needsRenderScriptOverride) { 8645 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 8646 } 8647 } 8648 } catch (IOException ioe) { 8649 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 8650 } finally { 8651 IoUtils.closeQuietly(handle); 8652 } 8653 8654 // Now that we've calculated the ABIs and determined if it's an internal app, 8655 // we will go ahead and populate the nativeLibraryPath. 8656 setNativeLibraryPaths(pkg); 8657 } 8658 8659 /** 8660 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 8661 * i.e, so that all packages can be run inside a single process if required. 8662 * 8663 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 8664 * this function will either try and make the ABI for all packages in {@code packagesForUser} 8665 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 8666 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 8667 * updating a package that belongs to a shared user. 8668 * 8669 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 8670 * adds unnecessary complexity. 8671 */ 8672 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 8673 PackageParser.Package scannedPackage, boolean bootComplete) { 8674 String requiredInstructionSet = null; 8675 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 8676 requiredInstructionSet = VMRuntime.getInstructionSet( 8677 scannedPackage.applicationInfo.primaryCpuAbi); 8678 } 8679 8680 PackageSetting requirer = null; 8681 for (PackageSetting ps : packagesForUser) { 8682 // If packagesForUser contains scannedPackage, we skip it. This will happen 8683 // when scannedPackage is an update of an existing package. Without this check, 8684 // we will never be able to change the ABI of any package belonging to a shared 8685 // user, even if it's compatible with other packages. 8686 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8687 if (ps.primaryCpuAbiString == null) { 8688 continue; 8689 } 8690 8691 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 8692 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 8693 // We have a mismatch between instruction sets (say arm vs arm64) warn about 8694 // this but there's not much we can do. 8695 String errorMessage = "Instruction set mismatch, " 8696 + ((requirer == null) ? "[caller]" : requirer) 8697 + " requires " + requiredInstructionSet + " whereas " + ps 8698 + " requires " + instructionSet; 8699 Slog.w(TAG, errorMessage); 8700 } 8701 8702 if (requiredInstructionSet == null) { 8703 requiredInstructionSet = instructionSet; 8704 requirer = ps; 8705 } 8706 } 8707 } 8708 8709 if (requiredInstructionSet != null) { 8710 String adjustedAbi; 8711 if (requirer != null) { 8712 // requirer != null implies that either scannedPackage was null or that scannedPackage 8713 // did not require an ABI, in which case we have to adjust scannedPackage to match 8714 // the ABI of the set (which is the same as requirer's ABI) 8715 adjustedAbi = requirer.primaryCpuAbiString; 8716 if (scannedPackage != null) { 8717 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 8718 } 8719 } else { 8720 // requirer == null implies that we're updating all ABIs in the set to 8721 // match scannedPackage. 8722 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 8723 } 8724 8725 for (PackageSetting ps : packagesForUser) { 8726 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8727 if (ps.primaryCpuAbiString != null) { 8728 continue; 8729 } 8730 8731 ps.primaryCpuAbiString = adjustedAbi; 8732 if (ps.pkg != null && ps.pkg.applicationInfo != null && 8733 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 8734 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 8735 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 8736 + " (requirer=" 8737 + (requirer == null ? "null" : requirer.pkg.packageName) 8738 + ", scannedPackage=" 8739 + (scannedPackage != null ? scannedPackage.packageName : "null") 8740 + ")"); 8741 try { 8742 mInstaller.rmdex(ps.codePathString, 8743 getDexCodeInstructionSet(getPreferredInstructionSet())); 8744 } catch (InstallerException ignored) { 8745 } 8746 } 8747 } 8748 } 8749 } 8750 } 8751 8752 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 8753 synchronized (mPackages) { 8754 mResolverReplaced = true; 8755 // Set up information for custom user intent resolution activity. 8756 mResolveActivity.applicationInfo = pkg.applicationInfo; 8757 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 8758 mResolveActivity.packageName = pkg.applicationInfo.packageName; 8759 mResolveActivity.processName = pkg.applicationInfo.packageName; 8760 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8761 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8762 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8763 mResolveActivity.theme = 0; 8764 mResolveActivity.exported = true; 8765 mResolveActivity.enabled = true; 8766 mResolveInfo.activityInfo = mResolveActivity; 8767 mResolveInfo.priority = 0; 8768 mResolveInfo.preferredOrder = 0; 8769 mResolveInfo.match = 0; 8770 mResolveComponentName = mCustomResolverComponentName; 8771 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 8772 mResolveComponentName); 8773 } 8774 } 8775 8776 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 8777 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 8778 8779 // Set up information for ephemeral installer activity 8780 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 8781 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 8782 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 8783 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 8784 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8785 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8786 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8787 mEphemeralInstallerActivity.theme = 0; 8788 mEphemeralInstallerActivity.exported = true; 8789 mEphemeralInstallerActivity.enabled = true; 8790 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 8791 mEphemeralInstallerInfo.priority = 0; 8792 mEphemeralInstallerInfo.preferredOrder = 0; 8793 mEphemeralInstallerInfo.match = 0; 8794 8795 if (DEBUG_EPHEMERAL) { 8796 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 8797 } 8798 } 8799 8800 private static String calculateBundledApkRoot(final String codePathString) { 8801 final File codePath = new File(codePathString); 8802 final File codeRoot; 8803 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 8804 codeRoot = Environment.getRootDirectory(); 8805 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 8806 codeRoot = Environment.getOemDirectory(); 8807 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 8808 codeRoot = Environment.getVendorDirectory(); 8809 } else { 8810 // Unrecognized code path; take its top real segment as the apk root: 8811 // e.g. /something/app/blah.apk => /something 8812 try { 8813 File f = codePath.getCanonicalFile(); 8814 File parent = f.getParentFile(); // non-null because codePath is a file 8815 File tmp; 8816 while ((tmp = parent.getParentFile()) != null) { 8817 f = parent; 8818 parent = tmp; 8819 } 8820 codeRoot = f; 8821 Slog.w(TAG, "Unrecognized code path " 8822 + codePath + " - using " + codeRoot); 8823 } catch (IOException e) { 8824 // Can't canonicalize the code path -- shenanigans? 8825 Slog.w(TAG, "Can't canonicalize code path " + codePath); 8826 return Environment.getRootDirectory().getPath(); 8827 } 8828 } 8829 return codeRoot.getPath(); 8830 } 8831 8832 /** 8833 * Derive and set the location of native libraries for the given package, 8834 * which varies depending on where and how the package was installed. 8835 */ 8836 private void setNativeLibraryPaths(PackageParser.Package pkg) { 8837 final ApplicationInfo info = pkg.applicationInfo; 8838 final String codePath = pkg.codePath; 8839 final File codeFile = new File(codePath); 8840 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 8841 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 8842 8843 info.nativeLibraryRootDir = null; 8844 info.nativeLibraryRootRequiresIsa = false; 8845 info.nativeLibraryDir = null; 8846 info.secondaryNativeLibraryDir = null; 8847 8848 if (isApkFile(codeFile)) { 8849 // Monolithic install 8850 if (bundledApp) { 8851 // If "/system/lib64/apkname" exists, assume that is the per-package 8852 // native library directory to use; otherwise use "/system/lib/apkname". 8853 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 8854 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 8855 getPrimaryInstructionSet(info)); 8856 8857 // This is a bundled system app so choose the path based on the ABI. 8858 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 8859 // is just the default path. 8860 final String apkName = deriveCodePathName(codePath); 8861 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 8862 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 8863 apkName).getAbsolutePath(); 8864 8865 if (info.secondaryCpuAbi != null) { 8866 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 8867 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 8868 secondaryLibDir, apkName).getAbsolutePath(); 8869 } 8870 } else if (asecApp) { 8871 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 8872 .getAbsolutePath(); 8873 } else { 8874 final String apkName = deriveCodePathName(codePath); 8875 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 8876 .getAbsolutePath(); 8877 } 8878 8879 info.nativeLibraryRootRequiresIsa = false; 8880 info.nativeLibraryDir = info.nativeLibraryRootDir; 8881 } else { 8882 // Cluster install 8883 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 8884 info.nativeLibraryRootRequiresIsa = true; 8885 8886 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 8887 getPrimaryInstructionSet(info)).getAbsolutePath(); 8888 8889 if (info.secondaryCpuAbi != null) { 8890 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 8891 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 8892 } 8893 } 8894 } 8895 8896 /** 8897 * Calculate the abis and roots for a bundled app. These can uniquely 8898 * be determined from the contents of the system partition, i.e whether 8899 * it contains 64 or 32 bit shared libraries etc. We do not validate any 8900 * of this information, and instead assume that the system was built 8901 * sensibly. 8902 */ 8903 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 8904 PackageSetting pkgSetting) { 8905 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 8906 8907 // If "/system/lib64/apkname" exists, assume that is the per-package 8908 // native library directory to use; otherwise use "/system/lib/apkname". 8909 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 8910 setBundledAppAbi(pkg, apkRoot, apkName); 8911 // pkgSetting might be null during rescan following uninstall of updates 8912 // to a bundled app, so accommodate that possibility. The settings in 8913 // that case will be established later from the parsed package. 8914 // 8915 // If the settings aren't null, sync them up with what we've just derived. 8916 // note that apkRoot isn't stored in the package settings. 8917 if (pkgSetting != null) { 8918 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8919 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8920 } 8921 } 8922 8923 /** 8924 * Deduces the ABI of a bundled app and sets the relevant fields on the 8925 * parsed pkg object. 8926 * 8927 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 8928 * under which system libraries are installed. 8929 * @param apkName the name of the installed package. 8930 */ 8931 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 8932 final File codeFile = new File(pkg.codePath); 8933 8934 final boolean has64BitLibs; 8935 final boolean has32BitLibs; 8936 if (isApkFile(codeFile)) { 8937 // Monolithic install 8938 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 8939 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 8940 } else { 8941 // Cluster install 8942 final File rootDir = new File(codeFile, LIB_DIR_NAME); 8943 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 8944 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 8945 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 8946 has64BitLibs = (new File(rootDir, isa)).exists(); 8947 } else { 8948 has64BitLibs = false; 8949 } 8950 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 8951 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 8952 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 8953 has32BitLibs = (new File(rootDir, isa)).exists(); 8954 } else { 8955 has32BitLibs = false; 8956 } 8957 } 8958 8959 if (has64BitLibs && !has32BitLibs) { 8960 // The package has 64 bit libs, but not 32 bit libs. Its primary 8961 // ABI should be 64 bit. We can safely assume here that the bundled 8962 // native libraries correspond to the most preferred ABI in the list. 8963 8964 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8965 pkg.applicationInfo.secondaryCpuAbi = null; 8966 } else if (has32BitLibs && !has64BitLibs) { 8967 // The package has 32 bit libs but not 64 bit libs. Its primary 8968 // ABI should be 32 bit. 8969 8970 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8971 pkg.applicationInfo.secondaryCpuAbi = null; 8972 } else if (has32BitLibs && has64BitLibs) { 8973 // The application has both 64 and 32 bit bundled libraries. We check 8974 // here that the app declares multiArch support, and warn if it doesn't. 8975 // 8976 // We will be lenient here and record both ABIs. The primary will be the 8977 // ABI that's higher on the list, i.e, a device that's configured to prefer 8978 // 64 bit apps will see a 64 bit primary ABI, 8979 8980 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 8981 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 8982 } 8983 8984 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 8985 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8986 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8987 } else { 8988 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8989 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8990 } 8991 } else { 8992 pkg.applicationInfo.primaryCpuAbi = null; 8993 pkg.applicationInfo.secondaryCpuAbi = null; 8994 } 8995 } 8996 8997 private void killPackage(PackageParser.Package pkg, String reason) { 8998 // Kill the parent package 8999 killApplication(pkg.packageName, pkg.applicationInfo.uid, reason); 9000 // Kill the child packages 9001 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9002 for (int i = 0; i < childCount; i++) { 9003 PackageParser.Package childPkg = pkg.childPackages.get(i); 9004 killApplication(childPkg.packageName, childPkg.applicationInfo.uid, reason); 9005 } 9006 } 9007 9008 private void killApplication(String pkgName, int appId, String reason) { 9009 // Request the ActivityManager to kill the process(only for existing packages) 9010 // so that we do not end up in a confused state while the user is still using the older 9011 // version of the application while the new one gets installed. 9012 IActivityManager am = ActivityManagerNative.getDefault(); 9013 if (am != null) { 9014 try { 9015 am.killApplicationWithAppId(pkgName, appId, reason); 9016 } catch (RemoteException e) { 9017 } 9018 } 9019 } 9020 9021 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 9022 // Remove the parent package setting 9023 PackageSetting ps = (PackageSetting) pkg.mExtras; 9024 if (ps != null) { 9025 removePackageLI(ps, chatty); 9026 } 9027 // Remove the child package setting 9028 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9029 for (int i = 0; i < childCount; i++) { 9030 PackageParser.Package childPkg = pkg.childPackages.get(i); 9031 ps = (PackageSetting) childPkg.mExtras; 9032 if (ps != null) { 9033 removePackageLI(ps, chatty); 9034 } 9035 } 9036 } 9037 9038 void removePackageLI(PackageSetting ps, boolean chatty) { 9039 if (DEBUG_INSTALL) { 9040 if (chatty) 9041 Log.d(TAG, "Removing package " + ps.name); 9042 } 9043 9044 // writer 9045 synchronized (mPackages) { 9046 mPackages.remove(ps.name); 9047 final PackageParser.Package pkg = ps.pkg; 9048 if (pkg != null) { 9049 cleanPackageDataStructuresLILPw(pkg, chatty); 9050 } 9051 } 9052 } 9053 9054 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 9055 if (DEBUG_INSTALL) { 9056 if (chatty) 9057 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 9058 } 9059 9060 // writer 9061 synchronized (mPackages) { 9062 // Remove the parent package 9063 mPackages.remove(pkg.applicationInfo.packageName); 9064 cleanPackageDataStructuresLILPw(pkg, chatty); 9065 9066 // Remove the child packages 9067 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9068 for (int i = 0; i < childCount; i++) { 9069 PackageParser.Package childPkg = pkg.childPackages.get(i); 9070 mPackages.remove(childPkg.applicationInfo.packageName); 9071 cleanPackageDataStructuresLILPw(childPkg, chatty); 9072 } 9073 } 9074 } 9075 9076 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 9077 int N = pkg.providers.size(); 9078 StringBuilder r = null; 9079 int i; 9080 for (i=0; i<N; i++) { 9081 PackageParser.Provider p = pkg.providers.get(i); 9082 mProviders.removeProvider(p); 9083 if (p.info.authority == null) { 9084 9085 /* There was another ContentProvider with this authority when 9086 * this app was installed so this authority is null, 9087 * Ignore it as we don't have to unregister the provider. 9088 */ 9089 continue; 9090 } 9091 String names[] = p.info.authority.split(";"); 9092 for (int j = 0; j < names.length; j++) { 9093 if (mProvidersByAuthority.get(names[j]) == p) { 9094 mProvidersByAuthority.remove(names[j]); 9095 if (DEBUG_REMOVE) { 9096 if (chatty) 9097 Log.d(TAG, "Unregistered content provider: " + names[j] 9098 + ", className = " + p.info.name + ", isSyncable = " 9099 + p.info.isSyncable); 9100 } 9101 } 9102 } 9103 if (DEBUG_REMOVE && chatty) { 9104 if (r == null) { 9105 r = new StringBuilder(256); 9106 } else { 9107 r.append(' '); 9108 } 9109 r.append(p.info.name); 9110 } 9111 } 9112 if (r != null) { 9113 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 9114 } 9115 9116 N = pkg.services.size(); 9117 r = null; 9118 for (i=0; i<N; i++) { 9119 PackageParser.Service s = pkg.services.get(i); 9120 mServices.removeService(s); 9121 if (chatty) { 9122 if (r == null) { 9123 r = new StringBuilder(256); 9124 } else { 9125 r.append(' '); 9126 } 9127 r.append(s.info.name); 9128 } 9129 } 9130 if (r != null) { 9131 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 9132 } 9133 9134 N = pkg.receivers.size(); 9135 r = null; 9136 for (i=0; i<N; i++) { 9137 PackageParser.Activity a = pkg.receivers.get(i); 9138 mReceivers.removeActivity(a, "receiver"); 9139 if (DEBUG_REMOVE && chatty) { 9140 if (r == null) { 9141 r = new StringBuilder(256); 9142 } else { 9143 r.append(' '); 9144 } 9145 r.append(a.info.name); 9146 } 9147 } 9148 if (r != null) { 9149 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 9150 } 9151 9152 N = pkg.activities.size(); 9153 r = null; 9154 for (i=0; i<N; i++) { 9155 PackageParser.Activity a = pkg.activities.get(i); 9156 mActivities.removeActivity(a, "activity"); 9157 if (DEBUG_REMOVE && chatty) { 9158 if (r == null) { 9159 r = new StringBuilder(256); 9160 } else { 9161 r.append(' '); 9162 } 9163 r.append(a.info.name); 9164 } 9165 } 9166 if (r != null) { 9167 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 9168 } 9169 9170 N = pkg.permissions.size(); 9171 r = null; 9172 for (i=0; i<N; i++) { 9173 PackageParser.Permission p = pkg.permissions.get(i); 9174 BasePermission bp = mSettings.mPermissions.get(p.info.name); 9175 if (bp == null) { 9176 bp = mSettings.mPermissionTrees.get(p.info.name); 9177 } 9178 if (bp != null && bp.perm == p) { 9179 bp.perm = null; 9180 if (DEBUG_REMOVE && chatty) { 9181 if (r == null) { 9182 r = new StringBuilder(256); 9183 } else { 9184 r.append(' '); 9185 } 9186 r.append(p.info.name); 9187 } 9188 } 9189 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9190 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 9191 if (appOpPkgs != null) { 9192 appOpPkgs.remove(pkg.packageName); 9193 } 9194 } 9195 } 9196 if (r != null) { 9197 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9198 } 9199 9200 N = pkg.requestedPermissions.size(); 9201 r = null; 9202 for (i=0; i<N; i++) { 9203 String perm = pkg.requestedPermissions.get(i); 9204 BasePermission bp = mSettings.mPermissions.get(perm); 9205 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9206 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 9207 if (appOpPkgs != null) { 9208 appOpPkgs.remove(pkg.packageName); 9209 if (appOpPkgs.isEmpty()) { 9210 mAppOpPermissionPackages.remove(perm); 9211 } 9212 } 9213 } 9214 } 9215 if (r != null) { 9216 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9217 } 9218 9219 N = pkg.instrumentation.size(); 9220 r = null; 9221 for (i=0; i<N; i++) { 9222 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9223 mInstrumentation.remove(a.getComponentName()); 9224 if (DEBUG_REMOVE && chatty) { 9225 if (r == null) { 9226 r = new StringBuilder(256); 9227 } else { 9228 r.append(' '); 9229 } 9230 r.append(a.info.name); 9231 } 9232 } 9233 if (r != null) { 9234 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9235 } 9236 9237 r = null; 9238 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9239 // Only system apps can hold shared libraries. 9240 if (pkg.libraryNames != null) { 9241 for (i=0; i<pkg.libraryNames.size(); i++) { 9242 String name = pkg.libraryNames.get(i); 9243 SharedLibraryEntry cur = mSharedLibraries.get(name); 9244 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9245 mSharedLibraries.remove(name); 9246 if (DEBUG_REMOVE && chatty) { 9247 if (r == null) { 9248 r = new StringBuilder(256); 9249 } else { 9250 r.append(' '); 9251 } 9252 r.append(name); 9253 } 9254 } 9255 } 9256 } 9257 } 9258 if (r != null) { 9259 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9260 } 9261 } 9262 9263 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9264 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9265 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9266 return true; 9267 } 9268 } 9269 return false; 9270 } 9271 9272 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9273 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9274 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9275 9276 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9277 // Update the parent permissions 9278 updatePermissionsLPw(pkg.packageName, pkg, flags); 9279 // Update the child permissions 9280 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9281 for (int i = 0; i < childCount; i++) { 9282 PackageParser.Package childPkg = pkg.childPackages.get(i); 9283 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9284 } 9285 } 9286 9287 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9288 int flags) { 9289 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9290 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9291 } 9292 9293 private void updatePermissionsLPw(String changingPkg, 9294 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9295 // Make sure there are no dangling permission trees. 9296 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9297 while (it.hasNext()) { 9298 final BasePermission bp = it.next(); 9299 if (bp.packageSetting == null) { 9300 // We may not yet have parsed the package, so just see if 9301 // we still know about its settings. 9302 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9303 } 9304 if (bp.packageSetting == null) { 9305 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9306 + " from package " + bp.sourcePackage); 9307 it.remove(); 9308 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9309 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9310 Slog.i(TAG, "Removing old permission tree: " + bp.name 9311 + " from package " + bp.sourcePackage); 9312 flags |= UPDATE_PERMISSIONS_ALL; 9313 it.remove(); 9314 } 9315 } 9316 } 9317 9318 // Make sure all dynamic permissions have been assigned to a package, 9319 // and make sure there are no dangling permissions. 9320 it = mSettings.mPermissions.values().iterator(); 9321 while (it.hasNext()) { 9322 final BasePermission bp = it.next(); 9323 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9324 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9325 + bp.name + " pkg=" + bp.sourcePackage 9326 + " info=" + bp.pendingInfo); 9327 if (bp.packageSetting == null && bp.pendingInfo != null) { 9328 final BasePermission tree = findPermissionTreeLP(bp.name); 9329 if (tree != null && tree.perm != null) { 9330 bp.packageSetting = tree.packageSetting; 9331 bp.perm = new PackageParser.Permission(tree.perm.owner, 9332 new PermissionInfo(bp.pendingInfo)); 9333 bp.perm.info.packageName = tree.perm.info.packageName; 9334 bp.perm.info.name = bp.name; 9335 bp.uid = tree.uid; 9336 } 9337 } 9338 } 9339 if (bp.packageSetting == null) { 9340 // We may not yet have parsed the package, so just see if 9341 // we still know about its settings. 9342 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9343 } 9344 if (bp.packageSetting == null) { 9345 Slog.w(TAG, "Removing dangling permission: " + bp.name 9346 + " from package " + bp.sourcePackage); 9347 it.remove(); 9348 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9349 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9350 Slog.i(TAG, "Removing old permission: " + bp.name 9351 + " from package " + bp.sourcePackage); 9352 flags |= UPDATE_PERMISSIONS_ALL; 9353 it.remove(); 9354 } 9355 } 9356 } 9357 9358 // Now update the permissions for all packages, in particular 9359 // replace the granted permissions of the system packages. 9360 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9361 for (PackageParser.Package pkg : mPackages.values()) { 9362 if (pkg != pkgInfo) { 9363 // Only replace for packages on requested volume 9364 final String volumeUuid = getVolumeUuidForPackage(pkg); 9365 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9366 && Objects.equals(replaceVolumeUuid, volumeUuid); 9367 grantPermissionsLPw(pkg, replace, changingPkg); 9368 } 9369 } 9370 } 9371 9372 if (pkgInfo != null) { 9373 // Only replace for packages on requested volume 9374 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9375 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9376 && Objects.equals(replaceVolumeUuid, volumeUuid); 9377 grantPermissionsLPw(pkgInfo, replace, changingPkg); 9378 } 9379 } 9380 9381 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 9382 String packageOfInterest) { 9383 // IMPORTANT: There are two types of permissions: install and runtime. 9384 // Install time permissions are granted when the app is installed to 9385 // all device users and users added in the future. Runtime permissions 9386 // are granted at runtime explicitly to specific users. Normal and signature 9387 // protected permissions are install time permissions. Dangerous permissions 9388 // are install permissions if the app's target SDK is Lollipop MR1 or older, 9389 // otherwise they are runtime permissions. This function does not manage 9390 // runtime permissions except for the case an app targeting Lollipop MR1 9391 // being upgraded to target a newer SDK, in which case dangerous permissions 9392 // are transformed from install time to runtime ones. 9393 9394 final PackageSetting ps = (PackageSetting) pkg.mExtras; 9395 if (ps == null) { 9396 return; 9397 } 9398 9399 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 9400 9401 PermissionsState permissionsState = ps.getPermissionsState(); 9402 PermissionsState origPermissions = permissionsState; 9403 9404 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 9405 9406 boolean runtimePermissionsRevoked = false; 9407 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 9408 9409 boolean changedInstallPermission = false; 9410 9411 if (replace) { 9412 ps.installPermissionsFixed = false; 9413 if (!ps.isSharedUser()) { 9414 origPermissions = new PermissionsState(permissionsState); 9415 permissionsState.reset(); 9416 } else { 9417 // We need to know only about runtime permission changes since the 9418 // calling code always writes the install permissions state but 9419 // the runtime ones are written only if changed. The only cases of 9420 // changed runtime permissions here are promotion of an install to 9421 // runtime and revocation of a runtime from a shared user. 9422 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 9423 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 9424 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 9425 runtimePermissionsRevoked = true; 9426 } 9427 } 9428 } 9429 9430 permissionsState.setGlobalGids(mGlobalGids); 9431 9432 final int N = pkg.requestedPermissions.size(); 9433 for (int i=0; i<N; i++) { 9434 final String name = pkg.requestedPermissions.get(i); 9435 final BasePermission bp = mSettings.mPermissions.get(name); 9436 9437 if (DEBUG_INSTALL) { 9438 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 9439 } 9440 9441 if (bp == null || bp.packageSetting == null) { 9442 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9443 Slog.w(TAG, "Unknown permission " + name 9444 + " in package " + pkg.packageName); 9445 } 9446 continue; 9447 } 9448 9449 final String perm = bp.name; 9450 boolean allowedSig = false; 9451 int grant = GRANT_DENIED; 9452 9453 // Keep track of app op permissions. 9454 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9455 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 9456 if (pkgs == null) { 9457 pkgs = new ArraySet<>(); 9458 mAppOpPermissionPackages.put(bp.name, pkgs); 9459 } 9460 pkgs.add(pkg.packageName); 9461 } 9462 9463 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 9464 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 9465 >= Build.VERSION_CODES.M; 9466 switch (level) { 9467 case PermissionInfo.PROTECTION_NORMAL: { 9468 // For all apps normal permissions are install time ones. 9469 grant = GRANT_INSTALL; 9470 } break; 9471 9472 case PermissionInfo.PROTECTION_DANGEROUS: { 9473 // If a permission review is required for legacy apps we represent 9474 // their permissions as always granted runtime ones since we need 9475 // to keep the review required permission flag per user while an 9476 // install permission's state is shared across all users. 9477 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 9478 // For legacy apps dangerous permissions are install time ones. 9479 grant = GRANT_INSTALL; 9480 } else if (origPermissions.hasInstallPermission(bp.name)) { 9481 // For legacy apps that became modern, install becomes runtime. 9482 grant = GRANT_UPGRADE; 9483 } else if (mPromoteSystemApps 9484 && isSystemApp(ps) 9485 && mExistingSystemPackages.contains(ps.name)) { 9486 // For legacy system apps, install becomes runtime. 9487 // We cannot check hasInstallPermission() for system apps since those 9488 // permissions were granted implicitly and not persisted pre-M. 9489 grant = GRANT_UPGRADE; 9490 } else { 9491 // For modern apps keep runtime permissions unchanged. 9492 grant = GRANT_RUNTIME; 9493 } 9494 } break; 9495 9496 case PermissionInfo.PROTECTION_SIGNATURE: { 9497 // For all apps signature permissions are install time ones. 9498 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 9499 if (allowedSig) { 9500 grant = GRANT_INSTALL; 9501 } 9502 } break; 9503 } 9504 9505 if (DEBUG_INSTALL) { 9506 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 9507 } 9508 9509 if (grant != GRANT_DENIED) { 9510 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 9511 // If this is an existing, non-system package, then 9512 // we can't add any new permissions to it. 9513 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 9514 // Except... if this is a permission that was added 9515 // to the platform (note: need to only do this when 9516 // updating the platform). 9517 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 9518 grant = GRANT_DENIED; 9519 } 9520 } 9521 } 9522 9523 switch (grant) { 9524 case GRANT_INSTALL: { 9525 // Revoke this as runtime permission to handle the case of 9526 // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps 9527 for (int userId : UserManagerService.getInstance().getUserIds()) { 9528 if (origPermissions.getRuntimePermissionState( 9529 bp.name, userId) != null) { 9530 // Revoke the runtime permission and clear the flags. 9531 origPermissions.revokeRuntimePermission(bp, userId); 9532 origPermissions.updatePermissionFlags(bp, userId, 9533 PackageManager.MASK_PERMISSION_FLAGS, 0); 9534 // If we revoked a permission permission, we have to write. 9535 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9536 changedRuntimePermissionUserIds, userId); 9537 } 9538 } 9539 // Grant an install permission. 9540 if (permissionsState.grantInstallPermission(bp) != 9541 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9542 changedInstallPermission = true; 9543 } 9544 } break; 9545 9546 case GRANT_RUNTIME: { 9547 // Grant previously granted runtime permissions. 9548 for (int userId : UserManagerService.getInstance().getUserIds()) { 9549 PermissionState permissionState = origPermissions 9550 .getRuntimePermissionState(bp.name, userId); 9551 int flags = permissionState != null 9552 ? permissionState.getFlags() : 0; 9553 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 9554 if (permissionsState.grantRuntimePermission(bp, userId) == 9555 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9556 // If we cannot put the permission as it was, we have to write. 9557 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9558 changedRuntimePermissionUserIds, userId); 9559 } 9560 // If the app supports runtime permissions no need for a review. 9561 if (Build.PERMISSIONS_REVIEW_REQUIRED 9562 && appSupportsRuntimePermissions 9563 && (flags & PackageManager 9564 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 9565 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 9566 // Since we changed the flags, we have to write. 9567 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9568 changedRuntimePermissionUserIds, userId); 9569 } 9570 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 9571 && !appSupportsRuntimePermissions) { 9572 // For legacy apps that need a permission review, every new 9573 // runtime permission is granted but it is pending a review. 9574 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 9575 permissionsState.grantRuntimePermission(bp, userId); 9576 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 9577 // We changed the permission and flags, hence have to write. 9578 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9579 changedRuntimePermissionUserIds, userId); 9580 } 9581 } 9582 // Propagate the permission flags. 9583 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 9584 } 9585 } break; 9586 9587 case GRANT_UPGRADE: { 9588 // Grant runtime permissions for a previously held install permission. 9589 PermissionState permissionState = origPermissions 9590 .getInstallPermissionState(bp.name); 9591 final int flags = permissionState != null ? permissionState.getFlags() : 0; 9592 9593 if (origPermissions.revokeInstallPermission(bp) 9594 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 9595 // We will be transferring the permission flags, so clear them. 9596 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 9597 PackageManager.MASK_PERMISSION_FLAGS, 0); 9598 changedInstallPermission = true; 9599 } 9600 9601 // If the permission is not to be promoted to runtime we ignore it and 9602 // also its other flags as they are not applicable to install permissions. 9603 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 9604 for (int userId : currentUserIds) { 9605 if (permissionsState.grantRuntimePermission(bp, userId) != 9606 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9607 // Transfer the permission flags. 9608 permissionsState.updatePermissionFlags(bp, userId, 9609 flags, flags); 9610 // If we granted the permission, we have to write. 9611 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9612 changedRuntimePermissionUserIds, userId); 9613 } 9614 } 9615 } 9616 } break; 9617 9618 default: { 9619 if (packageOfInterest == null 9620 || packageOfInterest.equals(pkg.packageName)) { 9621 Slog.w(TAG, "Not granting permission " + perm 9622 + " to package " + pkg.packageName 9623 + " because it was previously installed without"); 9624 } 9625 } break; 9626 } 9627 } else { 9628 if (permissionsState.revokeInstallPermission(bp) != 9629 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9630 // Also drop the permission flags. 9631 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 9632 PackageManager.MASK_PERMISSION_FLAGS, 0); 9633 changedInstallPermission = true; 9634 Slog.i(TAG, "Un-granting permission " + perm 9635 + " from package " + pkg.packageName 9636 + " (protectionLevel=" + bp.protectionLevel 9637 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9638 + ")"); 9639 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 9640 // Don't print warning for app op permissions, since it is fine for them 9641 // not to be granted, there is a UI for the user to decide. 9642 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9643 Slog.w(TAG, "Not granting permission " + perm 9644 + " to package " + pkg.packageName 9645 + " (protectionLevel=" + bp.protectionLevel 9646 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9647 + ")"); 9648 } 9649 } 9650 } 9651 } 9652 9653 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 9654 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 9655 // This is the first that we have heard about this package, so the 9656 // permissions we have now selected are fixed until explicitly 9657 // changed. 9658 ps.installPermissionsFixed = true; 9659 } 9660 9661 // Persist the runtime permissions state for users with changes. If permissions 9662 // were revoked because no app in the shared user declares them we have to 9663 // write synchronously to avoid losing runtime permissions state. 9664 for (int userId : changedRuntimePermissionUserIds) { 9665 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 9666 } 9667 9668 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9669 } 9670 9671 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 9672 boolean allowed = false; 9673 final int NP = PackageParser.NEW_PERMISSIONS.length; 9674 for (int ip=0; ip<NP; ip++) { 9675 final PackageParser.NewPermissionInfo npi 9676 = PackageParser.NEW_PERMISSIONS[ip]; 9677 if (npi.name.equals(perm) 9678 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 9679 allowed = true; 9680 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 9681 + pkg.packageName); 9682 break; 9683 } 9684 } 9685 return allowed; 9686 } 9687 9688 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 9689 BasePermission bp, PermissionsState origPermissions) { 9690 boolean allowed; 9691 allowed = (compareSignatures( 9692 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 9693 == PackageManager.SIGNATURE_MATCH) 9694 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 9695 == PackageManager.SIGNATURE_MATCH); 9696 if (!allowed && (bp.protectionLevel 9697 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 9698 if (isSystemApp(pkg)) { 9699 // For updated system applications, a system permission 9700 // is granted only if it had been defined by the original application. 9701 if (pkg.isUpdatedSystemApp()) { 9702 final PackageSetting sysPs = mSettings 9703 .getDisabledSystemPkgLPr(pkg.packageName); 9704 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 9705 // If the original was granted this permission, we take 9706 // that grant decision as read and propagate it to the 9707 // update. 9708 if (sysPs.isPrivileged()) { 9709 allowed = true; 9710 } 9711 } else { 9712 // The system apk may have been updated with an older 9713 // version of the one on the data partition, but which 9714 // granted a new system permission that it didn't have 9715 // before. In this case we do want to allow the app to 9716 // now get the new permission if the ancestral apk is 9717 // privileged to get it. 9718 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 9719 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 9720 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 9721 allowed = true; 9722 break; 9723 } 9724 } 9725 } 9726 // Also if a privileged parent package on the system image or any of 9727 // its children requested a privileged permission, the updated child 9728 // packages can also get the permission. 9729 if (pkg.parentPackage != null) { 9730 final PackageSetting disabledSysParentPs = mSettings 9731 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 9732 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 9733 && disabledSysParentPs.isPrivileged()) { 9734 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 9735 allowed = true; 9736 } else if (disabledSysParentPs.pkg.childPackages != null) { 9737 final int count = disabledSysParentPs.pkg.childPackages.size(); 9738 for (int i = 0; i < count; i++) { 9739 PackageParser.Package disabledSysChildPkg = 9740 disabledSysParentPs.pkg.childPackages.get(i); 9741 if (isPackageRequestingPermission(disabledSysChildPkg, 9742 perm)) { 9743 allowed = true; 9744 break; 9745 } 9746 } 9747 } 9748 } 9749 } 9750 } 9751 } else { 9752 allowed = isPrivilegedApp(pkg); 9753 } 9754 } 9755 } 9756 if (!allowed) { 9757 if (!allowed && (bp.protectionLevel 9758 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 9759 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 9760 // If this was a previously normal/dangerous permission that got moved 9761 // to a system permission as part of the runtime permission redesign, then 9762 // we still want to blindly grant it to old apps. 9763 allowed = true; 9764 } 9765 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 9766 && pkg.packageName.equals(mRequiredInstallerPackage)) { 9767 // If this permission is to be granted to the system installer and 9768 // this app is an installer, then it gets the permission. 9769 allowed = true; 9770 } 9771 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 9772 && pkg.packageName.equals(mRequiredVerifierPackage)) { 9773 // If this permission is to be granted to the system verifier and 9774 // this app is a verifier, then it gets the permission. 9775 allowed = true; 9776 } 9777 if (!allowed && (bp.protectionLevel 9778 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 9779 && isSystemApp(pkg)) { 9780 // Any pre-installed system app is allowed to get this permission. 9781 allowed = true; 9782 } 9783 if (!allowed && (bp.protectionLevel 9784 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 9785 // For development permissions, a development permission 9786 // is granted only if it was already granted. 9787 allowed = origPermissions.hasInstallPermission(perm); 9788 } 9789 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 9790 && pkg.packageName.equals(mSetupWizardPackage)) { 9791 // If this permission is to be granted to the system setup wizard and 9792 // this app is a setup wizard, then it gets the permission. 9793 allowed = true; 9794 } 9795 } 9796 return allowed; 9797 } 9798 9799 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 9800 final int permCount = pkg.requestedPermissions.size(); 9801 for (int j = 0; j < permCount; j++) { 9802 String requestedPermission = pkg.requestedPermissions.get(j); 9803 if (permission.equals(requestedPermission)) { 9804 return true; 9805 } 9806 } 9807 return false; 9808 } 9809 9810 final class ActivityIntentResolver 9811 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 9812 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9813 boolean defaultOnly, int userId) { 9814 if (!sUserManager.exists(userId)) return null; 9815 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9816 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9817 } 9818 9819 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9820 int userId) { 9821 if (!sUserManager.exists(userId)) return null; 9822 mFlags = flags; 9823 return super.queryIntent(intent, resolvedType, 9824 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9825 } 9826 9827 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9828 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 9829 if (!sUserManager.exists(userId)) return null; 9830 if (packageActivities == null) { 9831 return null; 9832 } 9833 mFlags = flags; 9834 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9835 final int N = packageActivities.size(); 9836 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 9837 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 9838 9839 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 9840 for (int i = 0; i < N; ++i) { 9841 intentFilters = packageActivities.get(i).intents; 9842 if (intentFilters != null && intentFilters.size() > 0) { 9843 PackageParser.ActivityIntentInfo[] array = 9844 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 9845 intentFilters.toArray(array); 9846 listCut.add(array); 9847 } 9848 } 9849 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9850 } 9851 9852 /** 9853 * Finds a privileged activity that matches the specified activity names. 9854 */ 9855 private PackageParser.Activity findMatchingActivity( 9856 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 9857 for (PackageParser.Activity sysActivity : activityList) { 9858 if (sysActivity.info.name.equals(activityInfo.name)) { 9859 return sysActivity; 9860 } 9861 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 9862 return sysActivity; 9863 } 9864 if (sysActivity.info.targetActivity != null) { 9865 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 9866 return sysActivity; 9867 } 9868 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 9869 return sysActivity; 9870 } 9871 } 9872 } 9873 return null; 9874 } 9875 9876 public class IterGenerator<E> { 9877 public Iterator<E> generate(ActivityIntentInfo info) { 9878 return null; 9879 } 9880 } 9881 9882 public class ActionIterGenerator extends IterGenerator<String> { 9883 @Override 9884 public Iterator<String> generate(ActivityIntentInfo info) { 9885 return info.actionsIterator(); 9886 } 9887 } 9888 9889 public class CategoriesIterGenerator extends IterGenerator<String> { 9890 @Override 9891 public Iterator<String> generate(ActivityIntentInfo info) { 9892 return info.categoriesIterator(); 9893 } 9894 } 9895 9896 public class SchemesIterGenerator extends IterGenerator<String> { 9897 @Override 9898 public Iterator<String> generate(ActivityIntentInfo info) { 9899 return info.schemesIterator(); 9900 } 9901 } 9902 9903 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 9904 @Override 9905 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 9906 return info.authoritiesIterator(); 9907 } 9908 } 9909 9910 /** 9911 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 9912 * MODIFIED. Do not pass in a list that should not be changed. 9913 */ 9914 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 9915 IterGenerator<T> generator, Iterator<T> searchIterator) { 9916 // loop through the set of actions; every one must be found in the intent filter 9917 while (searchIterator.hasNext()) { 9918 // we must have at least one filter in the list to consider a match 9919 if (intentList.size() == 0) { 9920 break; 9921 } 9922 9923 final T searchAction = searchIterator.next(); 9924 9925 // loop through the set of intent filters 9926 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 9927 while (intentIter.hasNext()) { 9928 final ActivityIntentInfo intentInfo = intentIter.next(); 9929 boolean selectionFound = false; 9930 9931 // loop through the intent filter's selection criteria; at least one 9932 // of them must match the searched criteria 9933 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 9934 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 9935 final T intentSelection = intentSelectionIter.next(); 9936 if (intentSelection != null && intentSelection.equals(searchAction)) { 9937 selectionFound = true; 9938 break; 9939 } 9940 } 9941 9942 // the selection criteria wasn't found in this filter's set; this filter 9943 // is not a potential match 9944 if (!selectionFound) { 9945 intentIter.remove(); 9946 } 9947 } 9948 } 9949 } 9950 9951 private boolean isProtectedAction(ActivityIntentInfo filter) { 9952 final Iterator<String> actionsIter = filter.actionsIterator(); 9953 while (actionsIter != null && actionsIter.hasNext()) { 9954 final String filterAction = actionsIter.next(); 9955 if (PROTECTED_ACTIONS.contains(filterAction)) { 9956 return true; 9957 } 9958 } 9959 return false; 9960 } 9961 9962 /** 9963 * Adjusts the priority of the given intent filter according to policy. 9964 * <p> 9965 * <ul> 9966 * <li>The priority for non privileged applications is capped to '0'</li> 9967 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 9968 * <li>The priority for unbundled updates to privileged applications is capped to the 9969 * priority defined on the system partition</li> 9970 * </ul> 9971 * <p> 9972 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 9973 * allowed to obtain any priority on any action. 9974 */ 9975 private void adjustPriority( 9976 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 9977 // nothing to do; priority is fine as-is 9978 if (intent.getPriority() <= 0) { 9979 return; 9980 } 9981 9982 final ActivityInfo activityInfo = intent.activity.info; 9983 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 9984 9985 final boolean privilegedApp = 9986 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 9987 if (!privilegedApp) { 9988 // non-privileged applications can never define a priority >0 9989 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 9990 + " package: " + applicationInfo.packageName 9991 + " activity: " + intent.activity.className 9992 + " origPrio: " + intent.getPriority()); 9993 intent.setPriority(0); 9994 return; 9995 } 9996 9997 if (systemActivities == null) { 9998 // the system package is not disabled; we're parsing the system partition 9999 if (isProtectedAction(intent)) { 10000 if (mDeferProtectedFilters) { 10001 // We can't deal with these just yet. No component should ever obtain a 10002 // >0 priority for a protected actions, with ONE exception -- the setup 10003 // wizard. The setup wizard, however, cannot be known until we're able to 10004 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 10005 // until all intent filters have been processed. Chicken, meet egg. 10006 // Let the filter temporarily have a high priority and rectify the 10007 // priorities after all system packages have been scanned. 10008 mProtectedFilters.add(intent); 10009 if (DEBUG_FILTERS) { 10010 Slog.i(TAG, "Protected action; save for later;" 10011 + " package: " + applicationInfo.packageName 10012 + " activity: " + intent.activity.className 10013 + " origPrio: " + intent.getPriority()); 10014 } 10015 return; 10016 } else { 10017 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 10018 Slog.i(TAG, "No setup wizard;" 10019 + " All protected intents capped to priority 0"); 10020 } 10021 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 10022 if (DEBUG_FILTERS) { 10023 Slog.i(TAG, "Found setup wizard;" 10024 + " allow priority " + intent.getPriority() + ";" 10025 + " package: " + intent.activity.info.packageName 10026 + " activity: " + intent.activity.className 10027 + " priority: " + intent.getPriority()); 10028 } 10029 // setup wizard gets whatever it wants 10030 return; 10031 } 10032 Slog.w(TAG, "Protected action; cap priority to 0;" 10033 + " package: " + intent.activity.info.packageName 10034 + " activity: " + intent.activity.className 10035 + " origPrio: " + intent.getPriority()); 10036 intent.setPriority(0); 10037 return; 10038 } 10039 } 10040 // privileged apps on the system image get whatever priority they request 10041 return; 10042 } 10043 10044 // privileged app unbundled update ... try to find the same activity 10045 final PackageParser.Activity foundActivity = 10046 findMatchingActivity(systemActivities, activityInfo); 10047 if (foundActivity == null) { 10048 // this is a new activity; it cannot obtain >0 priority 10049 if (DEBUG_FILTERS) { 10050 Slog.i(TAG, "New activity; cap priority to 0;" 10051 + " package: " + applicationInfo.packageName 10052 + " activity: " + intent.activity.className 10053 + " origPrio: " + intent.getPriority()); 10054 } 10055 intent.setPriority(0); 10056 return; 10057 } 10058 10059 // found activity, now check for filter equivalence 10060 10061 // a shallow copy is enough; we modify the list, not its contents 10062 final List<ActivityIntentInfo> intentListCopy = 10063 new ArrayList<>(foundActivity.intents); 10064 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 10065 10066 // find matching action subsets 10067 final Iterator<String> actionsIterator = intent.actionsIterator(); 10068 if (actionsIterator != null) { 10069 getIntentListSubset( 10070 intentListCopy, new ActionIterGenerator(), actionsIterator); 10071 if (intentListCopy.size() == 0) { 10072 // no more intents to match; we're not equivalent 10073 if (DEBUG_FILTERS) { 10074 Slog.i(TAG, "Mismatched action; cap priority to 0;" 10075 + " package: " + applicationInfo.packageName 10076 + " activity: " + intent.activity.className 10077 + " origPrio: " + intent.getPriority()); 10078 } 10079 intent.setPriority(0); 10080 return; 10081 } 10082 } 10083 10084 // find matching category subsets 10085 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 10086 if (categoriesIterator != null) { 10087 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 10088 categoriesIterator); 10089 if (intentListCopy.size() == 0) { 10090 // no more intents to match; we're not equivalent 10091 if (DEBUG_FILTERS) { 10092 Slog.i(TAG, "Mismatched category; cap priority to 0;" 10093 + " package: " + applicationInfo.packageName 10094 + " activity: " + intent.activity.className 10095 + " origPrio: " + intent.getPriority()); 10096 } 10097 intent.setPriority(0); 10098 return; 10099 } 10100 } 10101 10102 // find matching schemes subsets 10103 final Iterator<String> schemesIterator = intent.schemesIterator(); 10104 if (schemesIterator != null) { 10105 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 10106 schemesIterator); 10107 if (intentListCopy.size() == 0) { 10108 // no more intents to match; we're not equivalent 10109 if (DEBUG_FILTERS) { 10110 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 10111 + " package: " + applicationInfo.packageName 10112 + " activity: " + intent.activity.className 10113 + " origPrio: " + intent.getPriority()); 10114 } 10115 intent.setPriority(0); 10116 return; 10117 } 10118 } 10119 10120 // find matching authorities subsets 10121 final Iterator<IntentFilter.AuthorityEntry> 10122 authoritiesIterator = intent.authoritiesIterator(); 10123 if (authoritiesIterator != null) { 10124 getIntentListSubset(intentListCopy, 10125 new AuthoritiesIterGenerator(), 10126 authoritiesIterator); 10127 if (intentListCopy.size() == 0) { 10128 // no more intents to match; we're not equivalent 10129 if (DEBUG_FILTERS) { 10130 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 10131 + " package: " + applicationInfo.packageName 10132 + " activity: " + intent.activity.className 10133 + " origPrio: " + intent.getPriority()); 10134 } 10135 intent.setPriority(0); 10136 return; 10137 } 10138 } 10139 10140 // we found matching filter(s); app gets the max priority of all intents 10141 int cappedPriority = 0; 10142 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 10143 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 10144 } 10145 if (intent.getPriority() > cappedPriority) { 10146 if (DEBUG_FILTERS) { 10147 Slog.i(TAG, "Found matching filter(s);" 10148 + " cap priority to " + cappedPriority + ";" 10149 + " package: " + applicationInfo.packageName 10150 + " activity: " + intent.activity.className 10151 + " origPrio: " + intent.getPriority()); 10152 } 10153 intent.setPriority(cappedPriority); 10154 return; 10155 } 10156 // all this for nothing; the requested priority was <= what was on the system 10157 } 10158 10159 public final void addActivity(PackageParser.Activity a, String type) { 10160 mActivities.put(a.getComponentName(), a); 10161 if (DEBUG_SHOW_INFO) 10162 Log.v( 10163 TAG, " " + type + " " + 10164 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 10165 if (DEBUG_SHOW_INFO) 10166 Log.v(TAG, " Class=" + a.info.name); 10167 final int NI = a.intents.size(); 10168 for (int j=0; j<NI; j++) { 10169 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10170 if ("activity".equals(type)) { 10171 final PackageSetting ps = 10172 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 10173 final List<PackageParser.Activity> systemActivities = 10174 ps != null && ps.pkg != null ? ps.pkg.activities : null; 10175 adjustPriority(systemActivities, intent); 10176 } 10177 if (DEBUG_SHOW_INFO) { 10178 Log.v(TAG, " IntentFilter:"); 10179 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10180 } 10181 if (!intent.debugCheck()) { 10182 Log.w(TAG, "==> For Activity " + a.info.name); 10183 } 10184 addFilter(intent); 10185 } 10186 } 10187 10188 public final void removeActivity(PackageParser.Activity a, String type) { 10189 mActivities.remove(a.getComponentName()); 10190 if (DEBUG_SHOW_INFO) { 10191 Log.v(TAG, " " + type + " " 10192 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 10193 : a.info.name) + ":"); 10194 Log.v(TAG, " Class=" + a.info.name); 10195 } 10196 final int NI = a.intents.size(); 10197 for (int j=0; j<NI; j++) { 10198 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10199 if (DEBUG_SHOW_INFO) { 10200 Log.v(TAG, " IntentFilter:"); 10201 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10202 } 10203 removeFilter(intent); 10204 } 10205 } 10206 10207 @Override 10208 protected boolean allowFilterResult( 10209 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 10210 ActivityInfo filterAi = filter.activity.info; 10211 for (int i=dest.size()-1; i>=0; i--) { 10212 ActivityInfo destAi = dest.get(i).activityInfo; 10213 if (destAi.name == filterAi.name 10214 && destAi.packageName == filterAi.packageName) { 10215 return false; 10216 } 10217 } 10218 return true; 10219 } 10220 10221 @Override 10222 protected ActivityIntentInfo[] newArray(int size) { 10223 return new ActivityIntentInfo[size]; 10224 } 10225 10226 @Override 10227 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 10228 if (!sUserManager.exists(userId)) return true; 10229 PackageParser.Package p = filter.activity.owner; 10230 if (p != null) { 10231 PackageSetting ps = (PackageSetting)p.mExtras; 10232 if (ps != null) { 10233 // System apps are never considered stopped for purposes of 10234 // filtering, because there may be no way for the user to 10235 // actually re-launch them. 10236 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 10237 && ps.getStopped(userId); 10238 } 10239 } 10240 return false; 10241 } 10242 10243 @Override 10244 protected boolean isPackageForFilter(String packageName, 10245 PackageParser.ActivityIntentInfo info) { 10246 return packageName.equals(info.activity.owner.packageName); 10247 } 10248 10249 @Override 10250 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 10251 int match, int userId) { 10252 if (!sUserManager.exists(userId)) return null; 10253 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 10254 return null; 10255 } 10256 final PackageParser.Activity activity = info.activity; 10257 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 10258 if (ps == null) { 10259 return null; 10260 } 10261 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 10262 ps.readUserState(userId), userId); 10263 if (ai == null) { 10264 return null; 10265 } 10266 final ResolveInfo res = new ResolveInfo(); 10267 res.activityInfo = ai; 10268 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10269 res.filter = info; 10270 } 10271 if (info != null) { 10272 res.handleAllWebDataURI = info.handleAllWebDataURI(); 10273 } 10274 res.priority = info.getPriority(); 10275 res.preferredOrder = activity.owner.mPreferredOrder; 10276 //System.out.println("Result: " + res.activityInfo.className + 10277 // " = " + res.priority); 10278 res.match = match; 10279 res.isDefault = info.hasDefault; 10280 res.labelRes = info.labelRes; 10281 res.nonLocalizedLabel = info.nonLocalizedLabel; 10282 if (userNeedsBadging(userId)) { 10283 res.noResourceId = true; 10284 } else { 10285 res.icon = info.icon; 10286 } 10287 res.iconResourceId = info.icon; 10288 res.system = res.activityInfo.applicationInfo.isSystemApp(); 10289 return res; 10290 } 10291 10292 @Override 10293 protected void sortResults(List<ResolveInfo> results) { 10294 Collections.sort(results, mResolvePrioritySorter); 10295 } 10296 10297 @Override 10298 protected void dumpFilter(PrintWriter out, String prefix, 10299 PackageParser.ActivityIntentInfo filter) { 10300 out.print(prefix); out.print( 10301 Integer.toHexString(System.identityHashCode(filter.activity))); 10302 out.print(' '); 10303 filter.activity.printComponentShortName(out); 10304 out.print(" filter "); 10305 out.println(Integer.toHexString(System.identityHashCode(filter))); 10306 } 10307 10308 @Override 10309 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 10310 return filter.activity; 10311 } 10312 10313 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10314 PackageParser.Activity activity = (PackageParser.Activity)label; 10315 out.print(prefix); out.print( 10316 Integer.toHexString(System.identityHashCode(activity))); 10317 out.print(' '); 10318 activity.printComponentShortName(out); 10319 if (count > 1) { 10320 out.print(" ("); out.print(count); out.print(" filters)"); 10321 } 10322 out.println(); 10323 } 10324 10325 // Keys are String (activity class name), values are Activity. 10326 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 10327 = new ArrayMap<ComponentName, PackageParser.Activity>(); 10328 private int mFlags; 10329 } 10330 10331 private final class ServiceIntentResolver 10332 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 10333 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10334 boolean defaultOnly, int userId) { 10335 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10336 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10337 } 10338 10339 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10340 int userId) { 10341 if (!sUserManager.exists(userId)) return null; 10342 mFlags = flags; 10343 return super.queryIntent(intent, resolvedType, 10344 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10345 } 10346 10347 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10348 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 10349 if (!sUserManager.exists(userId)) return null; 10350 if (packageServices == null) { 10351 return null; 10352 } 10353 mFlags = flags; 10354 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10355 final int N = packageServices.size(); 10356 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 10357 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 10358 10359 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 10360 for (int i = 0; i < N; ++i) { 10361 intentFilters = packageServices.get(i).intents; 10362 if (intentFilters != null && intentFilters.size() > 0) { 10363 PackageParser.ServiceIntentInfo[] array = 10364 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 10365 intentFilters.toArray(array); 10366 listCut.add(array); 10367 } 10368 } 10369 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10370 } 10371 10372 public final void addService(PackageParser.Service s) { 10373 mServices.put(s.getComponentName(), s); 10374 if (DEBUG_SHOW_INFO) { 10375 Log.v(TAG, " " 10376 + (s.info.nonLocalizedLabel != null 10377 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10378 Log.v(TAG, " Class=" + s.info.name); 10379 } 10380 final int NI = s.intents.size(); 10381 int j; 10382 for (j=0; j<NI; j++) { 10383 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10384 if (DEBUG_SHOW_INFO) { 10385 Log.v(TAG, " IntentFilter:"); 10386 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10387 } 10388 if (!intent.debugCheck()) { 10389 Log.w(TAG, "==> For Service " + s.info.name); 10390 } 10391 addFilter(intent); 10392 } 10393 } 10394 10395 public final void removeService(PackageParser.Service s) { 10396 mServices.remove(s.getComponentName()); 10397 if (DEBUG_SHOW_INFO) { 10398 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 10399 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10400 Log.v(TAG, " Class=" + s.info.name); 10401 } 10402 final int NI = s.intents.size(); 10403 int j; 10404 for (j=0; j<NI; j++) { 10405 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10406 if (DEBUG_SHOW_INFO) { 10407 Log.v(TAG, " IntentFilter:"); 10408 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10409 } 10410 removeFilter(intent); 10411 } 10412 } 10413 10414 @Override 10415 protected boolean allowFilterResult( 10416 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 10417 ServiceInfo filterSi = filter.service.info; 10418 for (int i=dest.size()-1; i>=0; i--) { 10419 ServiceInfo destAi = dest.get(i).serviceInfo; 10420 if (destAi.name == filterSi.name 10421 && destAi.packageName == filterSi.packageName) { 10422 return false; 10423 } 10424 } 10425 return true; 10426 } 10427 10428 @Override 10429 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 10430 return new PackageParser.ServiceIntentInfo[size]; 10431 } 10432 10433 @Override 10434 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 10435 if (!sUserManager.exists(userId)) return true; 10436 PackageParser.Package p = filter.service.owner; 10437 if (p != null) { 10438 PackageSetting ps = (PackageSetting)p.mExtras; 10439 if (ps != null) { 10440 // System apps are never considered stopped for purposes of 10441 // filtering, because there may be no way for the user to 10442 // actually re-launch them. 10443 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10444 && ps.getStopped(userId); 10445 } 10446 } 10447 return false; 10448 } 10449 10450 @Override 10451 protected boolean isPackageForFilter(String packageName, 10452 PackageParser.ServiceIntentInfo info) { 10453 return packageName.equals(info.service.owner.packageName); 10454 } 10455 10456 @Override 10457 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 10458 int match, int userId) { 10459 if (!sUserManager.exists(userId)) return null; 10460 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 10461 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 10462 return null; 10463 } 10464 final PackageParser.Service service = info.service; 10465 PackageSetting ps = (PackageSetting) service.owner.mExtras; 10466 if (ps == null) { 10467 return null; 10468 } 10469 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 10470 ps.readUserState(userId), userId); 10471 if (si == null) { 10472 return null; 10473 } 10474 final ResolveInfo res = new ResolveInfo(); 10475 res.serviceInfo = si; 10476 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10477 res.filter = filter; 10478 } 10479 res.priority = info.getPriority(); 10480 res.preferredOrder = service.owner.mPreferredOrder; 10481 res.match = match; 10482 res.isDefault = info.hasDefault; 10483 res.labelRes = info.labelRes; 10484 res.nonLocalizedLabel = info.nonLocalizedLabel; 10485 res.icon = info.icon; 10486 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 10487 return res; 10488 } 10489 10490 @Override 10491 protected void sortResults(List<ResolveInfo> results) { 10492 Collections.sort(results, mResolvePrioritySorter); 10493 } 10494 10495 @Override 10496 protected void dumpFilter(PrintWriter out, String prefix, 10497 PackageParser.ServiceIntentInfo filter) { 10498 out.print(prefix); out.print( 10499 Integer.toHexString(System.identityHashCode(filter.service))); 10500 out.print(' '); 10501 filter.service.printComponentShortName(out); 10502 out.print(" filter "); 10503 out.println(Integer.toHexString(System.identityHashCode(filter))); 10504 } 10505 10506 @Override 10507 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 10508 return filter.service; 10509 } 10510 10511 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10512 PackageParser.Service service = (PackageParser.Service)label; 10513 out.print(prefix); out.print( 10514 Integer.toHexString(System.identityHashCode(service))); 10515 out.print(' '); 10516 service.printComponentShortName(out); 10517 if (count > 1) { 10518 out.print(" ("); out.print(count); out.print(" filters)"); 10519 } 10520 out.println(); 10521 } 10522 10523// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 10524// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 10525// final List<ResolveInfo> retList = Lists.newArrayList(); 10526// while (i.hasNext()) { 10527// final ResolveInfo resolveInfo = (ResolveInfo) i; 10528// if (isEnabledLP(resolveInfo.serviceInfo)) { 10529// retList.add(resolveInfo); 10530// } 10531// } 10532// return retList; 10533// } 10534 10535 // Keys are String (activity class name), values are Activity. 10536 private final ArrayMap<ComponentName, PackageParser.Service> mServices 10537 = new ArrayMap<ComponentName, PackageParser.Service>(); 10538 private int mFlags; 10539 }; 10540 10541 private final class ProviderIntentResolver 10542 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 10543 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10544 boolean defaultOnly, int userId) { 10545 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10546 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10547 } 10548 10549 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10550 int userId) { 10551 if (!sUserManager.exists(userId)) 10552 return null; 10553 mFlags = flags; 10554 return super.queryIntent(intent, resolvedType, 10555 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10556 } 10557 10558 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10559 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 10560 if (!sUserManager.exists(userId)) 10561 return null; 10562 if (packageProviders == null) { 10563 return null; 10564 } 10565 mFlags = flags; 10566 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 10567 final int N = packageProviders.size(); 10568 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 10569 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 10570 10571 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 10572 for (int i = 0; i < N; ++i) { 10573 intentFilters = packageProviders.get(i).intents; 10574 if (intentFilters != null && intentFilters.size() > 0) { 10575 PackageParser.ProviderIntentInfo[] array = 10576 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 10577 intentFilters.toArray(array); 10578 listCut.add(array); 10579 } 10580 } 10581 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10582 } 10583 10584 public final void addProvider(PackageParser.Provider p) { 10585 if (mProviders.containsKey(p.getComponentName())) { 10586 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 10587 return; 10588 } 10589 10590 mProviders.put(p.getComponentName(), p); 10591 if (DEBUG_SHOW_INFO) { 10592 Log.v(TAG, " " 10593 + (p.info.nonLocalizedLabel != null 10594 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10595 Log.v(TAG, " Class=" + p.info.name); 10596 } 10597 final int NI = p.intents.size(); 10598 int j; 10599 for (j = 0; j < NI; j++) { 10600 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10601 if (DEBUG_SHOW_INFO) { 10602 Log.v(TAG, " IntentFilter:"); 10603 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10604 } 10605 if (!intent.debugCheck()) { 10606 Log.w(TAG, "==> For Provider " + p.info.name); 10607 } 10608 addFilter(intent); 10609 } 10610 } 10611 10612 public final void removeProvider(PackageParser.Provider p) { 10613 mProviders.remove(p.getComponentName()); 10614 if (DEBUG_SHOW_INFO) { 10615 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 10616 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10617 Log.v(TAG, " Class=" + p.info.name); 10618 } 10619 final int NI = p.intents.size(); 10620 int j; 10621 for (j = 0; j < NI; j++) { 10622 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10623 if (DEBUG_SHOW_INFO) { 10624 Log.v(TAG, " IntentFilter:"); 10625 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10626 } 10627 removeFilter(intent); 10628 } 10629 } 10630 10631 @Override 10632 protected boolean allowFilterResult( 10633 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 10634 ProviderInfo filterPi = filter.provider.info; 10635 for (int i = dest.size() - 1; i >= 0; i--) { 10636 ProviderInfo destPi = dest.get(i).providerInfo; 10637 if (destPi.name == filterPi.name 10638 && destPi.packageName == filterPi.packageName) { 10639 return false; 10640 } 10641 } 10642 return true; 10643 } 10644 10645 @Override 10646 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 10647 return new PackageParser.ProviderIntentInfo[size]; 10648 } 10649 10650 @Override 10651 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 10652 if (!sUserManager.exists(userId)) 10653 return true; 10654 PackageParser.Package p = filter.provider.owner; 10655 if (p != null) { 10656 PackageSetting ps = (PackageSetting) p.mExtras; 10657 if (ps != null) { 10658 // System apps are never considered stopped for purposes of 10659 // filtering, because there may be no way for the user to 10660 // actually re-launch them. 10661 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10662 && ps.getStopped(userId); 10663 } 10664 } 10665 return false; 10666 } 10667 10668 @Override 10669 protected boolean isPackageForFilter(String packageName, 10670 PackageParser.ProviderIntentInfo info) { 10671 return packageName.equals(info.provider.owner.packageName); 10672 } 10673 10674 @Override 10675 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 10676 int match, int userId) { 10677 if (!sUserManager.exists(userId)) 10678 return null; 10679 final PackageParser.ProviderIntentInfo info = filter; 10680 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 10681 return null; 10682 } 10683 final PackageParser.Provider provider = info.provider; 10684 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 10685 if (ps == null) { 10686 return null; 10687 } 10688 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 10689 ps.readUserState(userId), userId); 10690 if (pi == null) { 10691 return null; 10692 } 10693 final ResolveInfo res = new ResolveInfo(); 10694 res.providerInfo = pi; 10695 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 10696 res.filter = filter; 10697 } 10698 res.priority = info.getPriority(); 10699 res.preferredOrder = provider.owner.mPreferredOrder; 10700 res.match = match; 10701 res.isDefault = info.hasDefault; 10702 res.labelRes = info.labelRes; 10703 res.nonLocalizedLabel = info.nonLocalizedLabel; 10704 res.icon = info.icon; 10705 res.system = res.providerInfo.applicationInfo.isSystemApp(); 10706 return res; 10707 } 10708 10709 @Override 10710 protected void sortResults(List<ResolveInfo> results) { 10711 Collections.sort(results, mResolvePrioritySorter); 10712 } 10713 10714 @Override 10715 protected void dumpFilter(PrintWriter out, String prefix, 10716 PackageParser.ProviderIntentInfo filter) { 10717 out.print(prefix); 10718 out.print( 10719 Integer.toHexString(System.identityHashCode(filter.provider))); 10720 out.print(' '); 10721 filter.provider.printComponentShortName(out); 10722 out.print(" filter "); 10723 out.println(Integer.toHexString(System.identityHashCode(filter))); 10724 } 10725 10726 @Override 10727 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 10728 return filter.provider; 10729 } 10730 10731 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10732 PackageParser.Provider provider = (PackageParser.Provider)label; 10733 out.print(prefix); out.print( 10734 Integer.toHexString(System.identityHashCode(provider))); 10735 out.print(' '); 10736 provider.printComponentShortName(out); 10737 if (count > 1) { 10738 out.print(" ("); out.print(count); out.print(" filters)"); 10739 } 10740 out.println(); 10741 } 10742 10743 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 10744 = new ArrayMap<ComponentName, PackageParser.Provider>(); 10745 private int mFlags; 10746 } 10747 10748 private static final class EphemeralIntentResolver 10749 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 10750 @Override 10751 protected EphemeralResolveIntentInfo[] newArray(int size) { 10752 return new EphemeralResolveIntentInfo[size]; 10753 } 10754 10755 @Override 10756 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 10757 return true; 10758 } 10759 10760 @Override 10761 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 10762 int userId) { 10763 if (!sUserManager.exists(userId)) { 10764 return null; 10765 } 10766 return info.getEphemeralResolveInfo(); 10767 } 10768 } 10769 10770 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 10771 new Comparator<ResolveInfo>() { 10772 public int compare(ResolveInfo r1, ResolveInfo r2) { 10773 int v1 = r1.priority; 10774 int v2 = r2.priority; 10775 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 10776 if (v1 != v2) { 10777 return (v1 > v2) ? -1 : 1; 10778 } 10779 v1 = r1.preferredOrder; 10780 v2 = r2.preferredOrder; 10781 if (v1 != v2) { 10782 return (v1 > v2) ? -1 : 1; 10783 } 10784 if (r1.isDefault != r2.isDefault) { 10785 return r1.isDefault ? -1 : 1; 10786 } 10787 v1 = r1.match; 10788 v2 = r2.match; 10789 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 10790 if (v1 != v2) { 10791 return (v1 > v2) ? -1 : 1; 10792 } 10793 if (r1.system != r2.system) { 10794 return r1.system ? -1 : 1; 10795 } 10796 if (r1.activityInfo != null) { 10797 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 10798 } 10799 if (r1.serviceInfo != null) { 10800 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 10801 } 10802 if (r1.providerInfo != null) { 10803 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 10804 } 10805 return 0; 10806 } 10807 }; 10808 10809 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 10810 new Comparator<ProviderInfo>() { 10811 public int compare(ProviderInfo p1, ProviderInfo p2) { 10812 final int v1 = p1.initOrder; 10813 final int v2 = p2.initOrder; 10814 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 10815 } 10816 }; 10817 10818 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 10819 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 10820 final int[] userIds) { 10821 mHandler.post(new Runnable() { 10822 @Override 10823 public void run() { 10824 try { 10825 final IActivityManager am = ActivityManagerNative.getDefault(); 10826 if (am == null) return; 10827 final int[] resolvedUserIds; 10828 if (userIds == null) { 10829 resolvedUserIds = am.getRunningUserIds(); 10830 } else { 10831 resolvedUserIds = userIds; 10832 } 10833 for (int id : resolvedUserIds) { 10834 final Intent intent = new Intent(action, 10835 pkg != null ? Uri.fromParts("package", pkg, null) : null); 10836 if (extras != null) { 10837 intent.putExtras(extras); 10838 } 10839 if (targetPkg != null) { 10840 intent.setPackage(targetPkg); 10841 } 10842 // Modify the UID when posting to other users 10843 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 10844 if (uid > 0 && UserHandle.getUserId(uid) != id) { 10845 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 10846 intent.putExtra(Intent.EXTRA_UID, uid); 10847 } 10848 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 10849 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 10850 if (DEBUG_BROADCASTS) { 10851 RuntimeException here = new RuntimeException("here"); 10852 here.fillInStackTrace(); 10853 Slog.d(TAG, "Sending to user " + id + ": " 10854 + intent.toShortString(false, true, false, false) 10855 + " " + intent.getExtras(), here); 10856 } 10857 am.broadcastIntent(null, intent, null, finishedReceiver, 10858 0, null, null, null, android.app.AppOpsManager.OP_NONE, 10859 null, finishedReceiver != null, false, id); 10860 } 10861 } catch (RemoteException ex) { 10862 } 10863 } 10864 }); 10865 } 10866 10867 /** 10868 * Check if the external storage media is available. This is true if there 10869 * is a mounted external storage medium or if the external storage is 10870 * emulated. 10871 */ 10872 private boolean isExternalMediaAvailable() { 10873 return mMediaMounted || Environment.isExternalStorageEmulated(); 10874 } 10875 10876 @Override 10877 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 10878 // writer 10879 synchronized (mPackages) { 10880 if (!isExternalMediaAvailable()) { 10881 // If the external storage is no longer mounted at this point, 10882 // the caller may not have been able to delete all of this 10883 // packages files and can not delete any more. Bail. 10884 return null; 10885 } 10886 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 10887 if (lastPackage != null) { 10888 pkgs.remove(lastPackage); 10889 } 10890 if (pkgs.size() > 0) { 10891 return pkgs.get(0); 10892 } 10893 } 10894 return null; 10895 } 10896 10897 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 10898 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 10899 userId, andCode ? 1 : 0, packageName); 10900 if (mSystemReady) { 10901 msg.sendToTarget(); 10902 } else { 10903 if (mPostSystemReadyMessages == null) { 10904 mPostSystemReadyMessages = new ArrayList<>(); 10905 } 10906 mPostSystemReadyMessages.add(msg); 10907 } 10908 } 10909 10910 void startCleaningPackages() { 10911 // reader 10912 if (!isExternalMediaAvailable()) { 10913 return; 10914 } 10915 synchronized (mPackages) { 10916 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 10917 return; 10918 } 10919 } 10920 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 10921 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 10922 IActivityManager am = ActivityManagerNative.getDefault(); 10923 if (am != null) { 10924 try { 10925 am.startService(null, intent, null, mContext.getOpPackageName(), 10926 UserHandle.USER_SYSTEM); 10927 } catch (RemoteException e) { 10928 } 10929 } 10930 } 10931 10932 @Override 10933 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 10934 int installFlags, String installerPackageName, int userId) { 10935 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 10936 10937 final int callingUid = Binder.getCallingUid(); 10938 enforceCrossUserPermission(callingUid, userId, 10939 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 10940 10941 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 10942 try { 10943 if (observer != null) { 10944 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 10945 } 10946 } catch (RemoteException re) { 10947 } 10948 return; 10949 } 10950 10951 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 10952 installFlags |= PackageManager.INSTALL_FROM_ADB; 10953 10954 } else { 10955 // Caller holds INSTALL_PACKAGES permission, so we're less strict 10956 // about installerPackageName. 10957 10958 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 10959 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 10960 } 10961 10962 UserHandle user; 10963 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 10964 user = UserHandle.ALL; 10965 } else { 10966 user = new UserHandle(userId); 10967 } 10968 10969 // Only system components can circumvent runtime permissions when installing. 10970 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 10971 && mContext.checkCallingOrSelfPermission(Manifest.permission 10972 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 10973 throw new SecurityException("You need the " 10974 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 10975 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 10976 } 10977 10978 final File originFile = new File(originPath); 10979 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 10980 10981 final Message msg = mHandler.obtainMessage(INIT_COPY); 10982 final VerificationInfo verificationInfo = new VerificationInfo( 10983 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 10984 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 10985 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 10986 null /*packageAbiOverride*/, null /*grantedPermissions*/, 10987 null /*certificates*/); 10988 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 10989 msg.obj = params; 10990 10991 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 10992 System.identityHashCode(msg.obj)); 10993 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 10994 System.identityHashCode(msg.obj)); 10995 10996 mHandler.sendMessage(msg); 10997 } 10998 10999 void installStage(String packageName, File stagedDir, String stagedCid, 11000 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 11001 String installerPackageName, int installerUid, UserHandle user, 11002 Certificate[][] certificates) { 11003 if (DEBUG_EPHEMERAL) { 11004 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11005 Slog.d(TAG, "Ephemeral install of " + packageName); 11006 } 11007 } 11008 final VerificationInfo verificationInfo = new VerificationInfo( 11009 sessionParams.originatingUri, sessionParams.referrerUri, 11010 sessionParams.originatingUid, installerUid); 11011 11012 final OriginInfo origin; 11013 if (stagedDir != null) { 11014 origin = OriginInfo.fromStagedFile(stagedDir); 11015 } else { 11016 origin = OriginInfo.fromStagedContainer(stagedCid); 11017 } 11018 11019 final Message msg = mHandler.obtainMessage(INIT_COPY); 11020 final InstallParams params = new InstallParams(origin, null, observer, 11021 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 11022 verificationInfo, user, sessionParams.abiOverride, 11023 sessionParams.grantedRuntimePermissions, certificates); 11024 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 11025 msg.obj = params; 11026 11027 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 11028 System.identityHashCode(msg.obj)); 11029 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11030 System.identityHashCode(msg.obj)); 11031 11032 mHandler.sendMessage(msg); 11033 } 11034 11035 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 11036 int userId) { 11037 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 11038 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId); 11039 } 11040 11041 private void sendPackageAddedForUser(String packageName, boolean isSystem, 11042 int appId, int userId) { 11043 Bundle extras = new Bundle(1); 11044 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId)); 11045 11046 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 11047 packageName, extras, 0, null, null, new int[] {userId}); 11048 try { 11049 IActivityManager am = ActivityManagerNative.getDefault(); 11050 if (isSystem && am.isUserRunning(userId, 0)) { 11051 // The just-installed/enabled app is bundled on the system, so presumed 11052 // to be able to run automatically without needing an explicit launch. 11053 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 11054 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 11055 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 11056 .setPackage(packageName); 11057 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 11058 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 11059 } 11060 } catch (RemoteException e) { 11061 // shouldn't happen 11062 Slog.w(TAG, "Unable to bootstrap installed package", e); 11063 } 11064 } 11065 11066 @Override 11067 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 11068 int userId) { 11069 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11070 PackageSetting pkgSetting; 11071 final int uid = Binder.getCallingUid(); 11072 enforceCrossUserPermission(uid, userId, 11073 true /* requireFullPermission */, true /* checkShell */, 11074 "setApplicationHiddenSetting for user " + userId); 11075 11076 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 11077 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 11078 return false; 11079 } 11080 11081 long callingId = Binder.clearCallingIdentity(); 11082 try { 11083 boolean sendAdded = false; 11084 boolean sendRemoved = false; 11085 // writer 11086 synchronized (mPackages) { 11087 pkgSetting = mSettings.mPackages.get(packageName); 11088 if (pkgSetting == null) { 11089 return false; 11090 } 11091 if (pkgSetting.getHidden(userId) != hidden) { 11092 pkgSetting.setHidden(hidden, userId); 11093 mSettings.writePackageRestrictionsLPr(userId); 11094 if (hidden) { 11095 sendRemoved = true; 11096 } else { 11097 sendAdded = true; 11098 } 11099 } 11100 } 11101 if (sendAdded) { 11102 sendPackageAddedForUser(packageName, pkgSetting, userId); 11103 return true; 11104 } 11105 if (sendRemoved) { 11106 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 11107 "hiding pkg"); 11108 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 11109 return true; 11110 } 11111 } finally { 11112 Binder.restoreCallingIdentity(callingId); 11113 } 11114 return false; 11115 } 11116 11117 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 11118 int userId) { 11119 final PackageRemovedInfo info = new PackageRemovedInfo(); 11120 info.removedPackage = packageName; 11121 info.removedUsers = new int[] {userId}; 11122 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 11123 info.sendPackageRemovedBroadcasts(true /*killApp*/); 11124 } 11125 11126 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 11127 if (pkgList.length > 0) { 11128 Bundle extras = new Bundle(1); 11129 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 11130 11131 sendPackageBroadcast( 11132 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 11133 : Intent.ACTION_PACKAGES_UNSUSPENDED, 11134 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 11135 new int[] {userId}); 11136 } 11137 } 11138 11139 /** 11140 * Returns true if application is not found or there was an error. Otherwise it returns 11141 * the hidden state of the package for the given user. 11142 */ 11143 @Override 11144 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 11145 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11146 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11147 true /* requireFullPermission */, false /* checkShell */, 11148 "getApplicationHidden for user " + userId); 11149 PackageSetting pkgSetting; 11150 long callingId = Binder.clearCallingIdentity(); 11151 try { 11152 // writer 11153 synchronized (mPackages) { 11154 pkgSetting = mSettings.mPackages.get(packageName); 11155 if (pkgSetting == null) { 11156 return true; 11157 } 11158 return pkgSetting.getHidden(userId); 11159 } 11160 } finally { 11161 Binder.restoreCallingIdentity(callingId); 11162 } 11163 } 11164 11165 /** 11166 * @hide 11167 */ 11168 @Override 11169 public int installExistingPackageAsUser(String packageName, int userId) { 11170 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 11171 null); 11172 PackageSetting pkgSetting; 11173 final int uid = Binder.getCallingUid(); 11174 enforceCrossUserPermission(uid, userId, 11175 true /* requireFullPermission */, true /* checkShell */, 11176 "installExistingPackage for user " + userId); 11177 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11178 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 11179 } 11180 11181 long callingId = Binder.clearCallingIdentity(); 11182 try { 11183 boolean installed = false; 11184 11185 // writer 11186 synchronized (mPackages) { 11187 pkgSetting = mSettings.mPackages.get(packageName); 11188 if (pkgSetting == null) { 11189 return PackageManager.INSTALL_FAILED_INVALID_URI; 11190 } 11191 if (!pkgSetting.getInstalled(userId)) { 11192 pkgSetting.setInstalled(true, userId); 11193 pkgSetting.setHidden(false, userId); 11194 mSettings.writePackageRestrictionsLPr(userId); 11195 installed = true; 11196 } 11197 } 11198 11199 if (installed) { 11200 if (pkgSetting.pkg != null) { 11201 prepareAppDataAfterInstall(pkgSetting.pkg); 11202 } 11203 sendPackageAddedForUser(packageName, pkgSetting, userId); 11204 } 11205 } finally { 11206 Binder.restoreCallingIdentity(callingId); 11207 } 11208 11209 return PackageManager.INSTALL_SUCCEEDED; 11210 } 11211 11212 boolean isUserRestricted(int userId, String restrictionKey) { 11213 Bundle restrictions = sUserManager.getUserRestrictions(userId); 11214 if (restrictions.getBoolean(restrictionKey, false)) { 11215 Log.w(TAG, "User is restricted: " + restrictionKey); 11216 return true; 11217 } 11218 return false; 11219 } 11220 11221 @Override 11222 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 11223 int userId) { 11224 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11225 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11226 true /* requireFullPermission */, true /* checkShell */, 11227 "setPackagesSuspended for user " + userId); 11228 11229 if (ArrayUtils.isEmpty(packageNames)) { 11230 return packageNames; 11231 } 11232 11233 // List of package names for whom the suspended state has changed. 11234 List<String> changedPackages = new ArrayList<>(packageNames.length); 11235 // List of package names for whom the suspended state is not set as requested in this 11236 // method. 11237 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 11238 for (int i = 0; i < packageNames.length; i++) { 11239 String packageName = packageNames[i]; 11240 long callingId = Binder.clearCallingIdentity(); 11241 try { 11242 boolean changed = false; 11243 final int appId; 11244 synchronized (mPackages) { 11245 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11246 if (pkgSetting == null) { 11247 Slog.w(TAG, "Could not find package setting for package \"" + packageName 11248 + "\". Skipping suspending/un-suspending."); 11249 unactionedPackages.add(packageName); 11250 continue; 11251 } 11252 appId = pkgSetting.appId; 11253 if (pkgSetting.getSuspended(userId) != suspended) { 11254 if (!canSuspendPackageForUserLocked(packageName, userId)) { 11255 unactionedPackages.add(packageName); 11256 continue; 11257 } 11258 pkgSetting.setSuspended(suspended, userId); 11259 mSettings.writePackageRestrictionsLPr(userId); 11260 changed = true; 11261 changedPackages.add(packageName); 11262 } 11263 } 11264 11265 if (changed && suspended) { 11266 killApplication(packageName, UserHandle.getUid(userId, appId), 11267 "suspending package"); 11268 } 11269 } finally { 11270 Binder.restoreCallingIdentity(callingId); 11271 } 11272 } 11273 11274 if (!changedPackages.isEmpty()) { 11275 sendPackagesSuspendedForUser(changedPackages.toArray( 11276 new String[changedPackages.size()]), userId, suspended); 11277 } 11278 11279 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 11280 } 11281 11282 @Override 11283 public boolean isPackageSuspendedForUser(String packageName, int userId) { 11284 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11285 true /* requireFullPermission */, false /* checkShell */, 11286 "isPackageSuspendedForUser for user " + userId); 11287 synchronized (mPackages) { 11288 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11289 if (pkgSetting == null) { 11290 throw new IllegalArgumentException("Unknown target package: " + packageName); 11291 } 11292 return pkgSetting.getSuspended(userId); 11293 } 11294 } 11295 11296 /** 11297 * TODO: cache and disallow blocking the active dialer. 11298 * 11299 * @see also DefaultPermissionGrantPolicy#grantDefaultSystemHandlerPermissions 11300 */ 11301 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 11302 if (isPackageDeviceAdmin(packageName, userId)) { 11303 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11304 + "\": has an active device admin"); 11305 return false; 11306 } 11307 11308 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 11309 if (packageName.equals(activeLauncherPackageName)) { 11310 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11311 + "\": contains the active launcher"); 11312 return false; 11313 } 11314 11315 if (packageName.equals(mRequiredInstallerPackage)) { 11316 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11317 + "\": required for package installation"); 11318 return false; 11319 } 11320 11321 if (packageName.equals(mRequiredVerifierPackage)) { 11322 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11323 + "\": required for package verification"); 11324 return false; 11325 } 11326 11327 final PackageParser.Package pkg = mPackages.get(packageName); 11328 if (pkg != null && isPrivilegedApp(pkg)) { 11329 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11330 + "\": is a privileged app"); 11331 return false; 11332 } 11333 11334 return true; 11335 } 11336 11337 private String getActiveLauncherPackageName(int userId) { 11338 Intent intent = new Intent(Intent.ACTION_MAIN); 11339 intent.addCategory(Intent.CATEGORY_HOME); 11340 ResolveInfo resolveInfo = resolveIntent( 11341 intent, 11342 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 11343 PackageManager.MATCH_DEFAULT_ONLY, 11344 userId); 11345 11346 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 11347 } 11348 11349 @Override 11350 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 11351 mContext.enforceCallingOrSelfPermission( 11352 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11353 "Only package verification agents can verify applications"); 11354 11355 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11356 final PackageVerificationResponse response = new PackageVerificationResponse( 11357 verificationCode, Binder.getCallingUid()); 11358 msg.arg1 = id; 11359 msg.obj = response; 11360 mHandler.sendMessage(msg); 11361 } 11362 11363 @Override 11364 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 11365 long millisecondsToDelay) { 11366 mContext.enforceCallingOrSelfPermission( 11367 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11368 "Only package verification agents can extend verification timeouts"); 11369 11370 final PackageVerificationState state = mPendingVerification.get(id); 11371 final PackageVerificationResponse response = new PackageVerificationResponse( 11372 verificationCodeAtTimeout, Binder.getCallingUid()); 11373 11374 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 11375 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 11376 } 11377 if (millisecondsToDelay < 0) { 11378 millisecondsToDelay = 0; 11379 } 11380 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 11381 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 11382 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 11383 } 11384 11385 if ((state != null) && !state.timeoutExtended()) { 11386 state.extendTimeout(); 11387 11388 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11389 msg.arg1 = id; 11390 msg.obj = response; 11391 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 11392 } 11393 } 11394 11395 private void broadcastPackageVerified(int verificationId, Uri packageUri, 11396 int verificationCode, UserHandle user) { 11397 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 11398 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 11399 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11400 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11401 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 11402 11403 mContext.sendBroadcastAsUser(intent, user, 11404 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 11405 } 11406 11407 private ComponentName matchComponentForVerifier(String packageName, 11408 List<ResolveInfo> receivers) { 11409 ActivityInfo targetReceiver = null; 11410 11411 final int NR = receivers.size(); 11412 for (int i = 0; i < NR; i++) { 11413 final ResolveInfo info = receivers.get(i); 11414 if (info.activityInfo == null) { 11415 continue; 11416 } 11417 11418 if (packageName.equals(info.activityInfo.packageName)) { 11419 targetReceiver = info.activityInfo; 11420 break; 11421 } 11422 } 11423 11424 if (targetReceiver == null) { 11425 return null; 11426 } 11427 11428 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 11429 } 11430 11431 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 11432 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 11433 if (pkgInfo.verifiers.length == 0) { 11434 return null; 11435 } 11436 11437 final int N = pkgInfo.verifiers.length; 11438 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 11439 for (int i = 0; i < N; i++) { 11440 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 11441 11442 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 11443 receivers); 11444 if (comp == null) { 11445 continue; 11446 } 11447 11448 final int verifierUid = getUidForVerifier(verifierInfo); 11449 if (verifierUid == -1) { 11450 continue; 11451 } 11452 11453 if (DEBUG_VERIFY) { 11454 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 11455 + " with the correct signature"); 11456 } 11457 sufficientVerifiers.add(comp); 11458 verificationState.addSufficientVerifier(verifierUid); 11459 } 11460 11461 return sufficientVerifiers; 11462 } 11463 11464 private int getUidForVerifier(VerifierInfo verifierInfo) { 11465 synchronized (mPackages) { 11466 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 11467 if (pkg == null) { 11468 return -1; 11469 } else if (pkg.mSignatures.length != 1) { 11470 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11471 + " has more than one signature; ignoring"); 11472 return -1; 11473 } 11474 11475 /* 11476 * If the public key of the package's signature does not match 11477 * our expected public key, then this is a different package and 11478 * we should skip. 11479 */ 11480 11481 final byte[] expectedPublicKey; 11482 try { 11483 final Signature verifierSig = pkg.mSignatures[0]; 11484 final PublicKey publicKey = verifierSig.getPublicKey(); 11485 expectedPublicKey = publicKey.getEncoded(); 11486 } catch (CertificateException e) { 11487 return -1; 11488 } 11489 11490 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 11491 11492 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 11493 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11494 + " does not have the expected public key; ignoring"); 11495 return -1; 11496 } 11497 11498 return pkg.applicationInfo.uid; 11499 } 11500 } 11501 11502 @Override 11503 public void finishPackageInstall(int token) { 11504 enforceSystemOrRoot("Only the system is allowed to finish installs"); 11505 11506 if (DEBUG_INSTALL) { 11507 Slog.v(TAG, "BM finishing package install for " + token); 11508 } 11509 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 11510 11511 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 11512 mHandler.sendMessage(msg); 11513 } 11514 11515 /** 11516 * Get the verification agent timeout. 11517 * 11518 * @return verification timeout in milliseconds 11519 */ 11520 private long getVerificationTimeout() { 11521 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 11522 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 11523 DEFAULT_VERIFICATION_TIMEOUT); 11524 } 11525 11526 /** 11527 * Get the default verification agent response code. 11528 * 11529 * @return default verification response code 11530 */ 11531 private int getDefaultVerificationResponse() { 11532 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11533 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 11534 DEFAULT_VERIFICATION_RESPONSE); 11535 } 11536 11537 /** 11538 * Check whether or not package verification has been enabled. 11539 * 11540 * @return true if verification should be performed 11541 */ 11542 private boolean isVerificationEnabled(int userId, int installFlags) { 11543 if (!DEFAULT_VERIFY_ENABLE) { 11544 return false; 11545 } 11546 // Ephemeral apps don't get the full verification treatment 11547 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11548 if (DEBUG_EPHEMERAL) { 11549 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 11550 } 11551 return false; 11552 } 11553 11554 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 11555 11556 // Check if installing from ADB 11557 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 11558 // Do not run verification in a test harness environment 11559 if (ActivityManager.isRunningInTestHarness()) { 11560 return false; 11561 } 11562 if (ensureVerifyAppsEnabled) { 11563 return true; 11564 } 11565 // Check if the developer does not want package verification for ADB installs 11566 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11567 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 11568 return false; 11569 } 11570 } 11571 11572 if (ensureVerifyAppsEnabled) { 11573 return true; 11574 } 11575 11576 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11577 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 11578 } 11579 11580 @Override 11581 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 11582 throws RemoteException { 11583 mContext.enforceCallingOrSelfPermission( 11584 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 11585 "Only intentfilter verification agents can verify applications"); 11586 11587 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 11588 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 11589 Binder.getCallingUid(), verificationCode, failedDomains); 11590 msg.arg1 = id; 11591 msg.obj = response; 11592 mHandler.sendMessage(msg); 11593 } 11594 11595 @Override 11596 public int getIntentVerificationStatus(String packageName, int userId) { 11597 synchronized (mPackages) { 11598 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 11599 } 11600 } 11601 11602 @Override 11603 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 11604 mContext.enforceCallingOrSelfPermission( 11605 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11606 11607 boolean result = false; 11608 synchronized (mPackages) { 11609 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 11610 } 11611 if (result) { 11612 scheduleWritePackageRestrictionsLocked(userId); 11613 } 11614 return result; 11615 } 11616 11617 @Override 11618 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 11619 String packageName) { 11620 synchronized (mPackages) { 11621 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 11622 } 11623 } 11624 11625 @Override 11626 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 11627 if (TextUtils.isEmpty(packageName)) { 11628 return ParceledListSlice.emptyList(); 11629 } 11630 synchronized (mPackages) { 11631 PackageParser.Package pkg = mPackages.get(packageName); 11632 if (pkg == null || pkg.activities == null) { 11633 return ParceledListSlice.emptyList(); 11634 } 11635 final int count = pkg.activities.size(); 11636 ArrayList<IntentFilter> result = new ArrayList<>(); 11637 for (int n=0; n<count; n++) { 11638 PackageParser.Activity activity = pkg.activities.get(n); 11639 if (activity.intents != null && activity.intents.size() > 0) { 11640 result.addAll(activity.intents); 11641 } 11642 } 11643 return new ParceledListSlice<>(result); 11644 } 11645 } 11646 11647 @Override 11648 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 11649 mContext.enforceCallingOrSelfPermission( 11650 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11651 11652 synchronized (mPackages) { 11653 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 11654 if (packageName != null) { 11655 result |= updateIntentVerificationStatus(packageName, 11656 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 11657 userId); 11658 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 11659 packageName, userId); 11660 } 11661 return result; 11662 } 11663 } 11664 11665 @Override 11666 public String getDefaultBrowserPackageName(int userId) { 11667 synchronized (mPackages) { 11668 return mSettings.getDefaultBrowserPackageNameLPw(userId); 11669 } 11670 } 11671 11672 /** 11673 * Get the "allow unknown sources" setting. 11674 * 11675 * @return the current "allow unknown sources" setting 11676 */ 11677 private int getUnknownSourcesSettings() { 11678 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 11679 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 11680 -1); 11681 } 11682 11683 @Override 11684 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 11685 final int uid = Binder.getCallingUid(); 11686 // writer 11687 synchronized (mPackages) { 11688 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 11689 if (targetPackageSetting == null) { 11690 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 11691 } 11692 11693 PackageSetting installerPackageSetting; 11694 if (installerPackageName != null) { 11695 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 11696 if (installerPackageSetting == null) { 11697 throw new IllegalArgumentException("Unknown installer package: " 11698 + installerPackageName); 11699 } 11700 } else { 11701 installerPackageSetting = null; 11702 } 11703 11704 Signature[] callerSignature; 11705 Object obj = mSettings.getUserIdLPr(uid); 11706 if (obj != null) { 11707 if (obj instanceof SharedUserSetting) { 11708 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 11709 } else if (obj instanceof PackageSetting) { 11710 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 11711 } else { 11712 throw new SecurityException("Bad object " + obj + " for uid " + uid); 11713 } 11714 } else { 11715 throw new SecurityException("Unknown calling UID: " + uid); 11716 } 11717 11718 // Verify: can't set installerPackageName to a package that is 11719 // not signed with the same cert as the caller. 11720 if (installerPackageSetting != null) { 11721 if (compareSignatures(callerSignature, 11722 installerPackageSetting.signatures.mSignatures) 11723 != PackageManager.SIGNATURE_MATCH) { 11724 throw new SecurityException( 11725 "Caller does not have same cert as new installer package " 11726 + installerPackageName); 11727 } 11728 } 11729 11730 // Verify: if target already has an installer package, it must 11731 // be signed with the same cert as the caller. 11732 if (targetPackageSetting.installerPackageName != null) { 11733 PackageSetting setting = mSettings.mPackages.get( 11734 targetPackageSetting.installerPackageName); 11735 // If the currently set package isn't valid, then it's always 11736 // okay to change it. 11737 if (setting != null) { 11738 if (compareSignatures(callerSignature, 11739 setting.signatures.mSignatures) 11740 != PackageManager.SIGNATURE_MATCH) { 11741 throw new SecurityException( 11742 "Caller does not have same cert as old installer package " 11743 + targetPackageSetting.installerPackageName); 11744 } 11745 } 11746 } 11747 11748 // Okay! 11749 targetPackageSetting.installerPackageName = installerPackageName; 11750 scheduleWriteSettingsLocked(); 11751 } 11752 } 11753 11754 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 11755 // Queue up an async operation since the package installation may take a little while. 11756 mHandler.post(new Runnable() { 11757 public void run() { 11758 mHandler.removeCallbacks(this); 11759 // Result object to be returned 11760 PackageInstalledInfo res = new PackageInstalledInfo(); 11761 res.setReturnCode(currentStatus); 11762 res.uid = -1; 11763 res.pkg = null; 11764 res.removedInfo = null; 11765 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11766 args.doPreInstall(res.returnCode); 11767 synchronized (mInstallLock) { 11768 installPackageTracedLI(args, res); 11769 } 11770 args.doPostInstall(res.returnCode, res.uid); 11771 } 11772 11773 // A restore should be performed at this point if (a) the install 11774 // succeeded, (b) the operation is not an update, and (c) the new 11775 // package has not opted out of backup participation. 11776 final boolean update = res.removedInfo != null 11777 && res.removedInfo.removedPackage != null; 11778 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 11779 boolean doRestore = !update 11780 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 11781 11782 // Set up the post-install work request bookkeeping. This will be used 11783 // and cleaned up by the post-install event handling regardless of whether 11784 // there's a restore pass performed. Token values are >= 1. 11785 int token; 11786 if (mNextInstallToken < 0) mNextInstallToken = 1; 11787 token = mNextInstallToken++; 11788 11789 PostInstallData data = new PostInstallData(args, res); 11790 mRunningInstalls.put(token, data); 11791 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 11792 11793 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 11794 // Pass responsibility to the Backup Manager. It will perform a 11795 // restore if appropriate, then pass responsibility back to the 11796 // Package Manager to run the post-install observer callbacks 11797 // and broadcasts. 11798 IBackupManager bm = IBackupManager.Stub.asInterface( 11799 ServiceManager.getService(Context.BACKUP_SERVICE)); 11800 if (bm != null) { 11801 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 11802 + " to BM for possible restore"); 11803 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 11804 try { 11805 // TODO: http://b/22388012 11806 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 11807 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 11808 } else { 11809 doRestore = false; 11810 } 11811 } catch (RemoteException e) { 11812 // can't happen; the backup manager is local 11813 } catch (Exception e) { 11814 Slog.e(TAG, "Exception trying to enqueue restore", e); 11815 doRestore = false; 11816 } 11817 } else { 11818 Slog.e(TAG, "Backup Manager not found!"); 11819 doRestore = false; 11820 } 11821 } 11822 11823 if (!doRestore) { 11824 // No restore possible, or the Backup Manager was mysteriously not 11825 // available -- just fire the post-install work request directly. 11826 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 11827 11828 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 11829 11830 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 11831 mHandler.sendMessage(msg); 11832 } 11833 } 11834 }); 11835 } 11836 11837 private abstract class HandlerParams { 11838 private static final int MAX_RETRIES = 4; 11839 11840 /** 11841 * Number of times startCopy() has been attempted and had a non-fatal 11842 * error. 11843 */ 11844 private int mRetries = 0; 11845 11846 /** User handle for the user requesting the information or installation. */ 11847 private final UserHandle mUser; 11848 String traceMethod; 11849 int traceCookie; 11850 11851 HandlerParams(UserHandle user) { 11852 mUser = user; 11853 } 11854 11855 UserHandle getUser() { 11856 return mUser; 11857 } 11858 11859 HandlerParams setTraceMethod(String traceMethod) { 11860 this.traceMethod = traceMethod; 11861 return this; 11862 } 11863 11864 HandlerParams setTraceCookie(int traceCookie) { 11865 this.traceCookie = traceCookie; 11866 return this; 11867 } 11868 11869 final boolean startCopy() { 11870 boolean res; 11871 try { 11872 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 11873 11874 if (++mRetries > MAX_RETRIES) { 11875 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 11876 mHandler.sendEmptyMessage(MCS_GIVE_UP); 11877 handleServiceError(); 11878 return false; 11879 } else { 11880 handleStartCopy(); 11881 res = true; 11882 } 11883 } catch (RemoteException e) { 11884 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 11885 mHandler.sendEmptyMessage(MCS_RECONNECT); 11886 res = false; 11887 } 11888 handleReturnCode(); 11889 return res; 11890 } 11891 11892 final void serviceError() { 11893 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 11894 handleServiceError(); 11895 handleReturnCode(); 11896 } 11897 11898 abstract void handleStartCopy() throws RemoteException; 11899 abstract void handleServiceError(); 11900 abstract void handleReturnCode(); 11901 } 11902 11903 class MeasureParams extends HandlerParams { 11904 private final PackageStats mStats; 11905 private boolean mSuccess; 11906 11907 private final IPackageStatsObserver mObserver; 11908 11909 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 11910 super(new UserHandle(stats.userHandle)); 11911 mObserver = observer; 11912 mStats = stats; 11913 } 11914 11915 @Override 11916 public String toString() { 11917 return "MeasureParams{" 11918 + Integer.toHexString(System.identityHashCode(this)) 11919 + " " + mStats.packageName + "}"; 11920 } 11921 11922 @Override 11923 void handleStartCopy() throws RemoteException { 11924 synchronized (mInstallLock) { 11925 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 11926 } 11927 11928 if (mSuccess) { 11929 final boolean mounted; 11930 if (Environment.isExternalStorageEmulated()) { 11931 mounted = true; 11932 } else { 11933 final String status = Environment.getExternalStorageState(); 11934 mounted = (Environment.MEDIA_MOUNTED.equals(status) 11935 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 11936 } 11937 11938 if (mounted) { 11939 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 11940 11941 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 11942 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 11943 11944 mStats.externalDataSize = calculateDirectorySize(mContainerService, 11945 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 11946 11947 // Always subtract cache size, since it's a subdirectory 11948 mStats.externalDataSize -= mStats.externalCacheSize; 11949 11950 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 11951 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 11952 11953 mStats.externalObbSize = calculateDirectorySize(mContainerService, 11954 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 11955 } 11956 } 11957 } 11958 11959 @Override 11960 void handleReturnCode() { 11961 if (mObserver != null) { 11962 try { 11963 mObserver.onGetStatsCompleted(mStats, mSuccess); 11964 } catch (RemoteException e) { 11965 Slog.i(TAG, "Observer no longer exists."); 11966 } 11967 } 11968 } 11969 11970 @Override 11971 void handleServiceError() { 11972 Slog.e(TAG, "Could not measure application " + mStats.packageName 11973 + " external storage"); 11974 } 11975 } 11976 11977 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 11978 throws RemoteException { 11979 long result = 0; 11980 for (File path : paths) { 11981 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 11982 } 11983 return result; 11984 } 11985 11986 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 11987 for (File path : paths) { 11988 try { 11989 mcs.clearDirectory(path.getAbsolutePath()); 11990 } catch (RemoteException e) { 11991 } 11992 } 11993 } 11994 11995 static class OriginInfo { 11996 /** 11997 * Location where install is coming from, before it has been 11998 * copied/renamed into place. This could be a single monolithic APK 11999 * file, or a cluster directory. This location may be untrusted. 12000 */ 12001 final File file; 12002 final String cid; 12003 12004 /** 12005 * Flag indicating that {@link #file} or {@link #cid} has already been 12006 * staged, meaning downstream users don't need to defensively copy the 12007 * contents. 12008 */ 12009 final boolean staged; 12010 12011 /** 12012 * Flag indicating that {@link #file} or {@link #cid} is an already 12013 * installed app that is being moved. 12014 */ 12015 final boolean existing; 12016 12017 final String resolvedPath; 12018 final File resolvedFile; 12019 12020 static OriginInfo fromNothing() { 12021 return new OriginInfo(null, null, false, false); 12022 } 12023 12024 static OriginInfo fromUntrustedFile(File file) { 12025 return new OriginInfo(file, null, false, false); 12026 } 12027 12028 static OriginInfo fromExistingFile(File file) { 12029 return new OriginInfo(file, null, false, true); 12030 } 12031 12032 static OriginInfo fromStagedFile(File file) { 12033 return new OriginInfo(file, null, true, false); 12034 } 12035 12036 static OriginInfo fromStagedContainer(String cid) { 12037 return new OriginInfo(null, cid, true, false); 12038 } 12039 12040 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 12041 this.file = file; 12042 this.cid = cid; 12043 this.staged = staged; 12044 this.existing = existing; 12045 12046 if (cid != null) { 12047 resolvedPath = PackageHelper.getSdDir(cid); 12048 resolvedFile = new File(resolvedPath); 12049 } else if (file != null) { 12050 resolvedPath = file.getAbsolutePath(); 12051 resolvedFile = file; 12052 } else { 12053 resolvedPath = null; 12054 resolvedFile = null; 12055 } 12056 } 12057 } 12058 12059 static class MoveInfo { 12060 final int moveId; 12061 final String fromUuid; 12062 final String toUuid; 12063 final String packageName; 12064 final String dataAppName; 12065 final int appId; 12066 final String seinfo; 12067 final int targetSdkVersion; 12068 12069 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 12070 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 12071 this.moveId = moveId; 12072 this.fromUuid = fromUuid; 12073 this.toUuid = toUuid; 12074 this.packageName = packageName; 12075 this.dataAppName = dataAppName; 12076 this.appId = appId; 12077 this.seinfo = seinfo; 12078 this.targetSdkVersion = targetSdkVersion; 12079 } 12080 } 12081 12082 static class VerificationInfo { 12083 /** A constant used to indicate that a uid value is not present. */ 12084 public static final int NO_UID = -1; 12085 12086 /** URI referencing where the package was downloaded from. */ 12087 final Uri originatingUri; 12088 12089 /** HTTP referrer URI associated with the originatingURI. */ 12090 final Uri referrer; 12091 12092 /** UID of the application that the install request originated from. */ 12093 final int originatingUid; 12094 12095 /** UID of application requesting the install */ 12096 final int installerUid; 12097 12098 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 12099 this.originatingUri = originatingUri; 12100 this.referrer = referrer; 12101 this.originatingUid = originatingUid; 12102 this.installerUid = installerUid; 12103 } 12104 } 12105 12106 class InstallParams extends HandlerParams { 12107 final OriginInfo origin; 12108 final MoveInfo move; 12109 final IPackageInstallObserver2 observer; 12110 int installFlags; 12111 final String installerPackageName; 12112 final String volumeUuid; 12113 private InstallArgs mArgs; 12114 private int mRet; 12115 final String packageAbiOverride; 12116 final String[] grantedRuntimePermissions; 12117 final VerificationInfo verificationInfo; 12118 final Certificate[][] certificates; 12119 12120 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12121 int installFlags, String installerPackageName, String volumeUuid, 12122 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 12123 String[] grantedPermissions, Certificate[][] certificates) { 12124 super(user); 12125 this.origin = origin; 12126 this.move = move; 12127 this.observer = observer; 12128 this.installFlags = installFlags; 12129 this.installerPackageName = installerPackageName; 12130 this.volumeUuid = volumeUuid; 12131 this.verificationInfo = verificationInfo; 12132 this.packageAbiOverride = packageAbiOverride; 12133 this.grantedRuntimePermissions = grantedPermissions; 12134 this.certificates = certificates; 12135 } 12136 12137 @Override 12138 public String toString() { 12139 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 12140 + " file=" + origin.file + " cid=" + origin.cid + "}"; 12141 } 12142 12143 private int installLocationPolicy(PackageInfoLite pkgLite) { 12144 String packageName = pkgLite.packageName; 12145 int installLocation = pkgLite.installLocation; 12146 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12147 // reader 12148 synchronized (mPackages) { 12149 // Currently installed package which the new package is attempting to replace or 12150 // null if no such package is installed. 12151 PackageParser.Package installedPkg = mPackages.get(packageName); 12152 // Package which currently owns the data which the new package will own if installed. 12153 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 12154 // will be null whereas dataOwnerPkg will contain information about the package 12155 // which was uninstalled while keeping its data. 12156 PackageParser.Package dataOwnerPkg = installedPkg; 12157 if (dataOwnerPkg == null) { 12158 PackageSetting ps = mSettings.mPackages.get(packageName); 12159 if (ps != null) { 12160 dataOwnerPkg = ps.pkg; 12161 } 12162 } 12163 12164 if (dataOwnerPkg != null) { 12165 // If installed, the package will get access to data left on the device by its 12166 // predecessor. As a security measure, this is permited only if this is not a 12167 // version downgrade or if the predecessor package is marked as debuggable and 12168 // a downgrade is explicitly requested. 12169 // 12170 // On debuggable platform builds, downgrades are permitted even for 12171 // non-debuggable packages to make testing easier. Debuggable platform builds do 12172 // not offer security guarantees and thus it's OK to disable some security 12173 // mechanisms to make debugging/testing easier on those builds. However, even on 12174 // debuggable builds downgrades of packages are permitted only if requested via 12175 // installFlags. This is because we aim to keep the behavior of debuggable 12176 // platform builds as close as possible to the behavior of non-debuggable 12177 // platform builds. 12178 final boolean downgradeRequested = 12179 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 12180 final boolean packageDebuggable = 12181 (dataOwnerPkg.applicationInfo.flags 12182 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 12183 final boolean downgradePermitted = 12184 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 12185 if (!downgradePermitted) { 12186 try { 12187 checkDowngrade(dataOwnerPkg, pkgLite); 12188 } catch (PackageManagerException e) { 12189 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 12190 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 12191 } 12192 } 12193 } 12194 12195 if (installedPkg != null) { 12196 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12197 // Check for updated system application. 12198 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 12199 if (onSd) { 12200 Slog.w(TAG, "Cannot install update to system app on sdcard"); 12201 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 12202 } 12203 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12204 } else { 12205 if (onSd) { 12206 // Install flag overrides everything. 12207 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12208 } 12209 // If current upgrade specifies particular preference 12210 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 12211 // Application explicitly specified internal. 12212 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12213 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 12214 // App explictly prefers external. Let policy decide 12215 } else { 12216 // Prefer previous location 12217 if (isExternal(installedPkg)) { 12218 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12219 } 12220 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12221 } 12222 } 12223 } else { 12224 // Invalid install. Return error code 12225 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 12226 } 12227 } 12228 } 12229 // All the special cases have been taken care of. 12230 // Return result based on recommended install location. 12231 if (onSd) { 12232 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12233 } 12234 return pkgLite.recommendedInstallLocation; 12235 } 12236 12237 /* 12238 * Invoke remote method to get package information and install 12239 * location values. Override install location based on default 12240 * policy if needed and then create install arguments based 12241 * on the install location. 12242 */ 12243 public void handleStartCopy() throws RemoteException { 12244 int ret = PackageManager.INSTALL_SUCCEEDED; 12245 12246 // If we're already staged, we've firmly committed to an install location 12247 if (origin.staged) { 12248 if (origin.file != null) { 12249 installFlags |= PackageManager.INSTALL_INTERNAL; 12250 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12251 } else if (origin.cid != null) { 12252 installFlags |= PackageManager.INSTALL_EXTERNAL; 12253 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12254 } else { 12255 throw new IllegalStateException("Invalid stage location"); 12256 } 12257 } 12258 12259 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12260 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 12261 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12262 PackageInfoLite pkgLite = null; 12263 12264 if (onInt && onSd) { 12265 // Check if both bits are set. 12266 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 12267 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12268 } else if (onSd && ephemeral) { 12269 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 12270 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12271 } else { 12272 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 12273 packageAbiOverride); 12274 12275 if (DEBUG_EPHEMERAL && ephemeral) { 12276 Slog.v(TAG, "pkgLite for install: " + pkgLite); 12277 } 12278 12279 /* 12280 * If we have too little free space, try to free cache 12281 * before giving up. 12282 */ 12283 if (!origin.staged && pkgLite.recommendedInstallLocation 12284 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12285 // TODO: focus freeing disk space on the target device 12286 final StorageManager storage = StorageManager.from(mContext); 12287 final long lowThreshold = storage.getStorageLowBytes( 12288 Environment.getDataDirectory()); 12289 12290 final long sizeBytes = mContainerService.calculateInstalledSize( 12291 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 12292 12293 try { 12294 mInstaller.freeCache(null, sizeBytes + lowThreshold); 12295 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 12296 installFlags, packageAbiOverride); 12297 } catch (InstallerException e) { 12298 Slog.w(TAG, "Failed to free cache", e); 12299 } 12300 12301 /* 12302 * The cache free must have deleted the file we 12303 * downloaded to install. 12304 * 12305 * TODO: fix the "freeCache" call to not delete 12306 * the file we care about. 12307 */ 12308 if (pkgLite.recommendedInstallLocation 12309 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12310 pkgLite.recommendedInstallLocation 12311 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 12312 } 12313 } 12314 } 12315 12316 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12317 int loc = pkgLite.recommendedInstallLocation; 12318 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 12319 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12320 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 12321 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 12322 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12323 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12324 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 12325 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 12326 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12327 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 12328 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 12329 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 12330 } else { 12331 // Override with defaults if needed. 12332 loc = installLocationPolicy(pkgLite); 12333 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 12334 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 12335 } else if (!onSd && !onInt) { 12336 // Override install location with flags 12337 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 12338 // Set the flag to install on external media. 12339 installFlags |= PackageManager.INSTALL_EXTERNAL; 12340 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12341 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 12342 if (DEBUG_EPHEMERAL) { 12343 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 12344 } 12345 installFlags |= PackageManager.INSTALL_EPHEMERAL; 12346 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 12347 |PackageManager.INSTALL_INTERNAL); 12348 } else { 12349 // Make sure the flag for installing on external 12350 // media is unset 12351 installFlags |= PackageManager.INSTALL_INTERNAL; 12352 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12353 } 12354 } 12355 } 12356 } 12357 12358 final InstallArgs args = createInstallArgs(this); 12359 mArgs = args; 12360 12361 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12362 // TODO: http://b/22976637 12363 // Apps installed for "all" users use the device owner to verify the app 12364 UserHandle verifierUser = getUser(); 12365 if (verifierUser == UserHandle.ALL) { 12366 verifierUser = UserHandle.SYSTEM; 12367 } 12368 12369 /* 12370 * Determine if we have any installed package verifiers. If we 12371 * do, then we'll defer to them to verify the packages. 12372 */ 12373 final int requiredUid = mRequiredVerifierPackage == null ? -1 12374 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 12375 verifierUser.getIdentifier()); 12376 if (!origin.existing && requiredUid != -1 12377 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 12378 final Intent verification = new Intent( 12379 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 12380 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 12381 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 12382 PACKAGE_MIME_TYPE); 12383 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 12384 12385 // Query all live verifiers based on current user state 12386 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 12387 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 12388 12389 if (DEBUG_VERIFY) { 12390 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 12391 + verification.toString() + " with " + pkgLite.verifiers.length 12392 + " optional verifiers"); 12393 } 12394 12395 final int verificationId = mPendingVerificationToken++; 12396 12397 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 12398 12399 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 12400 installerPackageName); 12401 12402 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 12403 installFlags); 12404 12405 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 12406 pkgLite.packageName); 12407 12408 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 12409 pkgLite.versionCode); 12410 12411 if (verificationInfo != null) { 12412 if (verificationInfo.originatingUri != null) { 12413 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 12414 verificationInfo.originatingUri); 12415 } 12416 if (verificationInfo.referrer != null) { 12417 verification.putExtra(Intent.EXTRA_REFERRER, 12418 verificationInfo.referrer); 12419 } 12420 if (verificationInfo.originatingUid >= 0) { 12421 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 12422 verificationInfo.originatingUid); 12423 } 12424 if (verificationInfo.installerUid >= 0) { 12425 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 12426 verificationInfo.installerUid); 12427 } 12428 } 12429 12430 final PackageVerificationState verificationState = new PackageVerificationState( 12431 requiredUid, args); 12432 12433 mPendingVerification.append(verificationId, verificationState); 12434 12435 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 12436 receivers, verificationState); 12437 12438 /* 12439 * If any sufficient verifiers were listed in the package 12440 * manifest, attempt to ask them. 12441 */ 12442 if (sufficientVerifiers != null) { 12443 final int N = sufficientVerifiers.size(); 12444 if (N == 0) { 12445 Slog.i(TAG, "Additional verifiers required, but none installed."); 12446 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 12447 } else { 12448 for (int i = 0; i < N; i++) { 12449 final ComponentName verifierComponent = sufficientVerifiers.get(i); 12450 12451 final Intent sufficientIntent = new Intent(verification); 12452 sufficientIntent.setComponent(verifierComponent); 12453 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 12454 } 12455 } 12456 } 12457 12458 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 12459 mRequiredVerifierPackage, receivers); 12460 if (ret == PackageManager.INSTALL_SUCCEEDED 12461 && mRequiredVerifierPackage != null) { 12462 Trace.asyncTraceBegin( 12463 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 12464 /* 12465 * Send the intent to the required verification agent, 12466 * but only start the verification timeout after the 12467 * target BroadcastReceivers have run. 12468 */ 12469 verification.setComponent(requiredVerifierComponent); 12470 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 12471 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12472 new BroadcastReceiver() { 12473 @Override 12474 public void onReceive(Context context, Intent intent) { 12475 final Message msg = mHandler 12476 .obtainMessage(CHECK_PENDING_VERIFICATION); 12477 msg.arg1 = verificationId; 12478 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 12479 } 12480 }, null, 0, null, null); 12481 12482 /* 12483 * We don't want the copy to proceed until verification 12484 * succeeds, so null out this field. 12485 */ 12486 mArgs = null; 12487 } 12488 } else { 12489 /* 12490 * No package verification is enabled, so immediately start 12491 * the remote call to initiate copy using temporary file. 12492 */ 12493 ret = args.copyApk(mContainerService, true); 12494 } 12495 } 12496 12497 mRet = ret; 12498 } 12499 12500 @Override 12501 void handleReturnCode() { 12502 // If mArgs is null, then MCS couldn't be reached. When it 12503 // reconnects, it will try again to install. At that point, this 12504 // will succeed. 12505 if (mArgs != null) { 12506 processPendingInstall(mArgs, mRet); 12507 } 12508 } 12509 12510 @Override 12511 void handleServiceError() { 12512 mArgs = createInstallArgs(this); 12513 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12514 } 12515 12516 public boolean isForwardLocked() { 12517 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12518 } 12519 } 12520 12521 /** 12522 * Used during creation of InstallArgs 12523 * 12524 * @param installFlags package installation flags 12525 * @return true if should be installed on external storage 12526 */ 12527 private static boolean installOnExternalAsec(int installFlags) { 12528 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 12529 return false; 12530 } 12531 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 12532 return true; 12533 } 12534 return false; 12535 } 12536 12537 /** 12538 * Used during creation of InstallArgs 12539 * 12540 * @param installFlags package installation flags 12541 * @return true if should be installed as forward locked 12542 */ 12543 private static boolean installForwardLocked(int installFlags) { 12544 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12545 } 12546 12547 private InstallArgs createInstallArgs(InstallParams params) { 12548 if (params.move != null) { 12549 return new MoveInstallArgs(params); 12550 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 12551 return new AsecInstallArgs(params); 12552 } else { 12553 return new FileInstallArgs(params); 12554 } 12555 } 12556 12557 /** 12558 * Create args that describe an existing installed package. Typically used 12559 * when cleaning up old installs, or used as a move source. 12560 */ 12561 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 12562 String resourcePath, String[] instructionSets) { 12563 final boolean isInAsec; 12564 if (installOnExternalAsec(installFlags)) { 12565 /* Apps on SD card are always in ASEC containers. */ 12566 isInAsec = true; 12567 } else if (installForwardLocked(installFlags) 12568 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 12569 /* 12570 * Forward-locked apps are only in ASEC containers if they're the 12571 * new style 12572 */ 12573 isInAsec = true; 12574 } else { 12575 isInAsec = false; 12576 } 12577 12578 if (isInAsec) { 12579 return new AsecInstallArgs(codePath, instructionSets, 12580 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 12581 } else { 12582 return new FileInstallArgs(codePath, resourcePath, instructionSets); 12583 } 12584 } 12585 12586 static abstract class InstallArgs { 12587 /** @see InstallParams#origin */ 12588 final OriginInfo origin; 12589 /** @see InstallParams#move */ 12590 final MoveInfo move; 12591 12592 final IPackageInstallObserver2 observer; 12593 // Always refers to PackageManager flags only 12594 final int installFlags; 12595 final String installerPackageName; 12596 final String volumeUuid; 12597 final UserHandle user; 12598 final String abiOverride; 12599 final String[] installGrantPermissions; 12600 /** If non-null, drop an async trace when the install completes */ 12601 final String traceMethod; 12602 final int traceCookie; 12603 final Certificate[][] certificates; 12604 12605 // The list of instruction sets supported by this app. This is currently 12606 // only used during the rmdex() phase to clean up resources. We can get rid of this 12607 // if we move dex files under the common app path. 12608 /* nullable */ String[] instructionSets; 12609 12610 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12611 int installFlags, String installerPackageName, String volumeUuid, 12612 UserHandle user, String[] instructionSets, 12613 String abiOverride, String[] installGrantPermissions, 12614 String traceMethod, int traceCookie, Certificate[][] certificates) { 12615 this.origin = origin; 12616 this.move = move; 12617 this.installFlags = installFlags; 12618 this.observer = observer; 12619 this.installerPackageName = installerPackageName; 12620 this.volumeUuid = volumeUuid; 12621 this.user = user; 12622 this.instructionSets = instructionSets; 12623 this.abiOverride = abiOverride; 12624 this.installGrantPermissions = installGrantPermissions; 12625 this.traceMethod = traceMethod; 12626 this.traceCookie = traceCookie; 12627 this.certificates = certificates; 12628 } 12629 12630 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 12631 abstract int doPreInstall(int status); 12632 12633 /** 12634 * Rename package into final resting place. All paths on the given 12635 * scanned package should be updated to reflect the rename. 12636 */ 12637 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 12638 abstract int doPostInstall(int status, int uid); 12639 12640 /** @see PackageSettingBase#codePathString */ 12641 abstract String getCodePath(); 12642 /** @see PackageSettingBase#resourcePathString */ 12643 abstract String getResourcePath(); 12644 12645 // Need installer lock especially for dex file removal. 12646 abstract void cleanUpResourcesLI(); 12647 abstract boolean doPostDeleteLI(boolean delete); 12648 12649 /** 12650 * Called before the source arguments are copied. This is used mostly 12651 * for MoveParams when it needs to read the source file to put it in the 12652 * destination. 12653 */ 12654 int doPreCopy() { 12655 return PackageManager.INSTALL_SUCCEEDED; 12656 } 12657 12658 /** 12659 * Called after the source arguments are copied. This is used mostly for 12660 * MoveParams when it needs to read the source file to put it in the 12661 * destination. 12662 */ 12663 int doPostCopy(int uid) { 12664 return PackageManager.INSTALL_SUCCEEDED; 12665 } 12666 12667 protected boolean isFwdLocked() { 12668 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12669 } 12670 12671 protected boolean isExternalAsec() { 12672 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12673 } 12674 12675 protected boolean isEphemeral() { 12676 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12677 } 12678 12679 UserHandle getUser() { 12680 return user; 12681 } 12682 } 12683 12684 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 12685 if (!allCodePaths.isEmpty()) { 12686 if (instructionSets == null) { 12687 throw new IllegalStateException("instructionSet == null"); 12688 } 12689 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 12690 for (String codePath : allCodePaths) { 12691 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 12692 try { 12693 mInstaller.rmdex(codePath, dexCodeInstructionSet); 12694 } catch (InstallerException ignored) { 12695 } 12696 } 12697 } 12698 } 12699 } 12700 12701 /** 12702 * Logic to handle installation of non-ASEC applications, including copying 12703 * and renaming logic. 12704 */ 12705 class FileInstallArgs extends InstallArgs { 12706 private File codeFile; 12707 private File resourceFile; 12708 12709 // Example topology: 12710 // /data/app/com.example/base.apk 12711 // /data/app/com.example/split_foo.apk 12712 // /data/app/com.example/lib/arm/libfoo.so 12713 // /data/app/com.example/lib/arm64/libfoo.so 12714 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 12715 12716 /** New install */ 12717 FileInstallArgs(InstallParams params) { 12718 super(params.origin, params.move, params.observer, params.installFlags, 12719 params.installerPackageName, params.volumeUuid, 12720 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 12721 params.grantedRuntimePermissions, 12722 params.traceMethod, params.traceCookie, params.certificates); 12723 if (isFwdLocked()) { 12724 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 12725 } 12726 } 12727 12728 /** Existing install */ 12729 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 12730 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 12731 null, null, null, 0, null /*certificates*/); 12732 this.codeFile = (codePath != null) ? new File(codePath) : null; 12733 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 12734 } 12735 12736 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12737 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 12738 try { 12739 return doCopyApk(imcs, temp); 12740 } finally { 12741 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12742 } 12743 } 12744 12745 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12746 if (origin.staged) { 12747 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 12748 codeFile = origin.file; 12749 resourceFile = origin.file; 12750 return PackageManager.INSTALL_SUCCEEDED; 12751 } 12752 12753 try { 12754 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12755 final File tempDir = 12756 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 12757 codeFile = tempDir; 12758 resourceFile = tempDir; 12759 } catch (IOException e) { 12760 Slog.w(TAG, "Failed to create copy file: " + e); 12761 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12762 } 12763 12764 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 12765 @Override 12766 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 12767 if (!FileUtils.isValidExtFilename(name)) { 12768 throw new IllegalArgumentException("Invalid filename: " + name); 12769 } 12770 try { 12771 final File file = new File(codeFile, name); 12772 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 12773 O_RDWR | O_CREAT, 0644); 12774 Os.chmod(file.getAbsolutePath(), 0644); 12775 return new ParcelFileDescriptor(fd); 12776 } catch (ErrnoException e) { 12777 throw new RemoteException("Failed to open: " + e.getMessage()); 12778 } 12779 } 12780 }; 12781 12782 int ret = PackageManager.INSTALL_SUCCEEDED; 12783 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 12784 if (ret != PackageManager.INSTALL_SUCCEEDED) { 12785 Slog.e(TAG, "Failed to copy package"); 12786 return ret; 12787 } 12788 12789 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 12790 NativeLibraryHelper.Handle handle = null; 12791 try { 12792 handle = NativeLibraryHelper.Handle.create(codeFile); 12793 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 12794 abiOverride); 12795 } catch (IOException e) { 12796 Slog.e(TAG, "Copying native libraries failed", e); 12797 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12798 } finally { 12799 IoUtils.closeQuietly(handle); 12800 } 12801 12802 return ret; 12803 } 12804 12805 int doPreInstall(int status) { 12806 if (status != PackageManager.INSTALL_SUCCEEDED) { 12807 cleanUp(); 12808 } 12809 return status; 12810 } 12811 12812 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 12813 if (status != PackageManager.INSTALL_SUCCEEDED) { 12814 cleanUp(); 12815 return false; 12816 } 12817 12818 final File targetDir = codeFile.getParentFile(); 12819 final File beforeCodeFile = codeFile; 12820 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 12821 12822 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 12823 try { 12824 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 12825 } catch (ErrnoException e) { 12826 Slog.w(TAG, "Failed to rename", e); 12827 return false; 12828 } 12829 12830 if (!SELinux.restoreconRecursive(afterCodeFile)) { 12831 Slog.w(TAG, "Failed to restorecon"); 12832 return false; 12833 } 12834 12835 // Reflect the rename internally 12836 codeFile = afterCodeFile; 12837 resourceFile = afterCodeFile; 12838 12839 // Reflect the rename in scanned details 12840 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 12841 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 12842 afterCodeFile, pkg.baseCodePath)); 12843 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 12844 afterCodeFile, pkg.splitCodePaths)); 12845 12846 // Reflect the rename in app info 12847 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 12848 pkg.setApplicationInfoCodePath(pkg.codePath); 12849 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 12850 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 12851 pkg.setApplicationInfoResourcePath(pkg.codePath); 12852 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 12853 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 12854 12855 return true; 12856 } 12857 12858 int doPostInstall(int status, int uid) { 12859 if (status != PackageManager.INSTALL_SUCCEEDED) { 12860 cleanUp(); 12861 } 12862 return status; 12863 } 12864 12865 @Override 12866 String getCodePath() { 12867 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 12868 } 12869 12870 @Override 12871 String getResourcePath() { 12872 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 12873 } 12874 12875 private boolean cleanUp() { 12876 if (codeFile == null || !codeFile.exists()) { 12877 return false; 12878 } 12879 12880 removeCodePathLI(codeFile); 12881 12882 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 12883 resourceFile.delete(); 12884 } 12885 12886 return true; 12887 } 12888 12889 void cleanUpResourcesLI() { 12890 // Try enumerating all code paths before deleting 12891 List<String> allCodePaths = Collections.EMPTY_LIST; 12892 if (codeFile != null && codeFile.exists()) { 12893 try { 12894 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 12895 allCodePaths = pkg.getAllCodePaths(); 12896 } catch (PackageParserException e) { 12897 // Ignored; we tried our best 12898 } 12899 } 12900 12901 cleanUp(); 12902 removeDexFiles(allCodePaths, instructionSets); 12903 } 12904 12905 boolean doPostDeleteLI(boolean delete) { 12906 // XXX err, shouldn't we respect the delete flag? 12907 cleanUpResourcesLI(); 12908 return true; 12909 } 12910 } 12911 12912 private boolean isAsecExternal(String cid) { 12913 final String asecPath = PackageHelper.getSdFilesystem(cid); 12914 return !asecPath.startsWith(mAsecInternalPath); 12915 } 12916 12917 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 12918 PackageManagerException { 12919 if (copyRet < 0) { 12920 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 12921 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 12922 throw new PackageManagerException(copyRet, message); 12923 } 12924 } 12925 } 12926 12927 /** 12928 * Extract the MountService "container ID" from the full code path of an 12929 * .apk. 12930 */ 12931 static String cidFromCodePath(String fullCodePath) { 12932 int eidx = fullCodePath.lastIndexOf("/"); 12933 String subStr1 = fullCodePath.substring(0, eidx); 12934 int sidx = subStr1.lastIndexOf("/"); 12935 return subStr1.substring(sidx+1, eidx); 12936 } 12937 12938 /** 12939 * Logic to handle installation of ASEC applications, including copying and 12940 * renaming logic. 12941 */ 12942 class AsecInstallArgs extends InstallArgs { 12943 static final String RES_FILE_NAME = "pkg.apk"; 12944 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 12945 12946 String cid; 12947 String packagePath; 12948 String resourcePath; 12949 12950 /** New install */ 12951 AsecInstallArgs(InstallParams params) { 12952 super(params.origin, params.move, params.observer, params.installFlags, 12953 params.installerPackageName, params.volumeUuid, 12954 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 12955 params.grantedRuntimePermissions, 12956 params.traceMethod, params.traceCookie, params.certificates); 12957 } 12958 12959 /** Existing install */ 12960 AsecInstallArgs(String fullCodePath, String[] instructionSets, 12961 boolean isExternal, boolean isForwardLocked) { 12962 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 12963 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 12964 instructionSets, null, null, null, 0, null /*certificates*/); 12965 // Hackily pretend we're still looking at a full code path 12966 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 12967 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 12968 } 12969 12970 // Extract cid from fullCodePath 12971 int eidx = fullCodePath.lastIndexOf("/"); 12972 String subStr1 = fullCodePath.substring(0, eidx); 12973 int sidx = subStr1.lastIndexOf("/"); 12974 cid = subStr1.substring(sidx+1, eidx); 12975 setMountPath(subStr1); 12976 } 12977 12978 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 12979 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 12980 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 12981 instructionSets, null, null, null, 0, null /*certificates*/); 12982 this.cid = cid; 12983 setMountPath(PackageHelper.getSdDir(cid)); 12984 } 12985 12986 void createCopyFile() { 12987 cid = mInstallerService.allocateExternalStageCidLegacy(); 12988 } 12989 12990 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12991 if (origin.staged && origin.cid != null) { 12992 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 12993 cid = origin.cid; 12994 setMountPath(PackageHelper.getSdDir(cid)); 12995 return PackageManager.INSTALL_SUCCEEDED; 12996 } 12997 12998 if (temp) { 12999 createCopyFile(); 13000 } else { 13001 /* 13002 * Pre-emptively destroy the container since it's destroyed if 13003 * copying fails due to it existing anyway. 13004 */ 13005 PackageHelper.destroySdDir(cid); 13006 } 13007 13008 final String newMountPath = imcs.copyPackageToContainer( 13009 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 13010 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 13011 13012 if (newMountPath != null) { 13013 setMountPath(newMountPath); 13014 return PackageManager.INSTALL_SUCCEEDED; 13015 } else { 13016 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13017 } 13018 } 13019 13020 @Override 13021 String getCodePath() { 13022 return packagePath; 13023 } 13024 13025 @Override 13026 String getResourcePath() { 13027 return resourcePath; 13028 } 13029 13030 int doPreInstall(int status) { 13031 if (status != PackageManager.INSTALL_SUCCEEDED) { 13032 // Destroy container 13033 PackageHelper.destroySdDir(cid); 13034 } else { 13035 boolean mounted = PackageHelper.isContainerMounted(cid); 13036 if (!mounted) { 13037 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 13038 Process.SYSTEM_UID); 13039 if (newMountPath != null) { 13040 setMountPath(newMountPath); 13041 } else { 13042 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13043 } 13044 } 13045 } 13046 return status; 13047 } 13048 13049 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13050 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 13051 String newMountPath = null; 13052 if (PackageHelper.isContainerMounted(cid)) { 13053 // Unmount the container 13054 if (!PackageHelper.unMountSdDir(cid)) { 13055 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 13056 return false; 13057 } 13058 } 13059 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13060 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 13061 " which might be stale. Will try to clean up."); 13062 // Clean up the stale container and proceed to recreate. 13063 if (!PackageHelper.destroySdDir(newCacheId)) { 13064 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 13065 return false; 13066 } 13067 // Successfully cleaned up stale container. Try to rename again. 13068 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13069 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 13070 + " inspite of cleaning it up."); 13071 return false; 13072 } 13073 } 13074 if (!PackageHelper.isContainerMounted(newCacheId)) { 13075 Slog.w(TAG, "Mounting container " + newCacheId); 13076 newMountPath = PackageHelper.mountSdDir(newCacheId, 13077 getEncryptKey(), Process.SYSTEM_UID); 13078 } else { 13079 newMountPath = PackageHelper.getSdDir(newCacheId); 13080 } 13081 if (newMountPath == null) { 13082 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 13083 return false; 13084 } 13085 Log.i(TAG, "Succesfully renamed " + cid + 13086 " to " + newCacheId + 13087 " at new path: " + newMountPath); 13088 cid = newCacheId; 13089 13090 final File beforeCodeFile = new File(packagePath); 13091 setMountPath(newMountPath); 13092 final File afterCodeFile = new File(packagePath); 13093 13094 // Reflect the rename in scanned details 13095 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13096 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13097 afterCodeFile, pkg.baseCodePath)); 13098 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13099 afterCodeFile, pkg.splitCodePaths)); 13100 13101 // Reflect the rename in app info 13102 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13103 pkg.setApplicationInfoCodePath(pkg.codePath); 13104 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13105 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13106 pkg.setApplicationInfoResourcePath(pkg.codePath); 13107 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13108 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13109 13110 return true; 13111 } 13112 13113 private void setMountPath(String mountPath) { 13114 final File mountFile = new File(mountPath); 13115 13116 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 13117 if (monolithicFile.exists()) { 13118 packagePath = monolithicFile.getAbsolutePath(); 13119 if (isFwdLocked()) { 13120 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 13121 } else { 13122 resourcePath = packagePath; 13123 } 13124 } else { 13125 packagePath = mountFile.getAbsolutePath(); 13126 resourcePath = packagePath; 13127 } 13128 } 13129 13130 int doPostInstall(int status, int uid) { 13131 if (status != PackageManager.INSTALL_SUCCEEDED) { 13132 cleanUp(); 13133 } else { 13134 final int groupOwner; 13135 final String protectedFile; 13136 if (isFwdLocked()) { 13137 groupOwner = UserHandle.getSharedAppGid(uid); 13138 protectedFile = RES_FILE_NAME; 13139 } else { 13140 groupOwner = -1; 13141 protectedFile = null; 13142 } 13143 13144 if (uid < Process.FIRST_APPLICATION_UID 13145 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 13146 Slog.e(TAG, "Failed to finalize " + cid); 13147 PackageHelper.destroySdDir(cid); 13148 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13149 } 13150 13151 boolean mounted = PackageHelper.isContainerMounted(cid); 13152 if (!mounted) { 13153 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 13154 } 13155 } 13156 return status; 13157 } 13158 13159 private void cleanUp() { 13160 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 13161 13162 // Destroy secure container 13163 PackageHelper.destroySdDir(cid); 13164 } 13165 13166 private List<String> getAllCodePaths() { 13167 final File codeFile = new File(getCodePath()); 13168 if (codeFile != null && codeFile.exists()) { 13169 try { 13170 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13171 return pkg.getAllCodePaths(); 13172 } catch (PackageParserException e) { 13173 // Ignored; we tried our best 13174 } 13175 } 13176 return Collections.EMPTY_LIST; 13177 } 13178 13179 void cleanUpResourcesLI() { 13180 // Enumerate all code paths before deleting 13181 cleanUpResourcesLI(getAllCodePaths()); 13182 } 13183 13184 private void cleanUpResourcesLI(List<String> allCodePaths) { 13185 cleanUp(); 13186 removeDexFiles(allCodePaths, instructionSets); 13187 } 13188 13189 String getPackageName() { 13190 return getAsecPackageName(cid); 13191 } 13192 13193 boolean doPostDeleteLI(boolean delete) { 13194 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 13195 final List<String> allCodePaths = getAllCodePaths(); 13196 boolean mounted = PackageHelper.isContainerMounted(cid); 13197 if (mounted) { 13198 // Unmount first 13199 if (PackageHelper.unMountSdDir(cid)) { 13200 mounted = false; 13201 } 13202 } 13203 if (!mounted && delete) { 13204 cleanUpResourcesLI(allCodePaths); 13205 } 13206 return !mounted; 13207 } 13208 13209 @Override 13210 int doPreCopy() { 13211 if (isFwdLocked()) { 13212 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 13213 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 13214 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13215 } 13216 } 13217 13218 return PackageManager.INSTALL_SUCCEEDED; 13219 } 13220 13221 @Override 13222 int doPostCopy(int uid) { 13223 if (isFwdLocked()) { 13224 if (uid < Process.FIRST_APPLICATION_UID 13225 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 13226 RES_FILE_NAME)) { 13227 Slog.e(TAG, "Failed to finalize " + cid); 13228 PackageHelper.destroySdDir(cid); 13229 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13230 } 13231 } 13232 13233 return PackageManager.INSTALL_SUCCEEDED; 13234 } 13235 } 13236 13237 /** 13238 * Logic to handle movement of existing installed applications. 13239 */ 13240 class MoveInstallArgs extends InstallArgs { 13241 private File codeFile; 13242 private File resourceFile; 13243 13244 /** New install */ 13245 MoveInstallArgs(InstallParams params) { 13246 super(params.origin, params.move, params.observer, params.installFlags, 13247 params.installerPackageName, params.volumeUuid, 13248 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13249 params.grantedRuntimePermissions, 13250 params.traceMethod, params.traceCookie, params.certificates); 13251 } 13252 13253 int copyApk(IMediaContainerService imcs, boolean temp) { 13254 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 13255 + move.fromUuid + " to " + move.toUuid); 13256 synchronized (mInstaller) { 13257 try { 13258 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 13259 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 13260 } catch (InstallerException e) { 13261 Slog.w(TAG, "Failed to move app", e); 13262 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13263 } 13264 } 13265 13266 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 13267 resourceFile = codeFile; 13268 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 13269 13270 return PackageManager.INSTALL_SUCCEEDED; 13271 } 13272 13273 int doPreInstall(int status) { 13274 if (status != PackageManager.INSTALL_SUCCEEDED) { 13275 cleanUp(move.toUuid); 13276 } 13277 return status; 13278 } 13279 13280 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13281 if (status != PackageManager.INSTALL_SUCCEEDED) { 13282 cleanUp(move.toUuid); 13283 return false; 13284 } 13285 13286 // Reflect the move in app info 13287 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13288 pkg.setApplicationInfoCodePath(pkg.codePath); 13289 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13290 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13291 pkg.setApplicationInfoResourcePath(pkg.codePath); 13292 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13293 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13294 13295 return true; 13296 } 13297 13298 int doPostInstall(int status, int uid) { 13299 if (status == PackageManager.INSTALL_SUCCEEDED) { 13300 cleanUp(move.fromUuid); 13301 } else { 13302 cleanUp(move.toUuid); 13303 } 13304 return status; 13305 } 13306 13307 @Override 13308 String getCodePath() { 13309 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13310 } 13311 13312 @Override 13313 String getResourcePath() { 13314 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13315 } 13316 13317 private boolean cleanUp(String volumeUuid) { 13318 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 13319 move.dataAppName); 13320 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 13321 synchronized (mInstallLock) { 13322 // Clean up both app data and code 13323 removeDataDirsLI(volumeUuid, move.packageName); 13324 removeCodePathLI(codeFile); 13325 } 13326 return true; 13327 } 13328 13329 void cleanUpResourcesLI() { 13330 throw new UnsupportedOperationException(); 13331 } 13332 13333 boolean doPostDeleteLI(boolean delete) { 13334 throw new UnsupportedOperationException(); 13335 } 13336 } 13337 13338 static String getAsecPackageName(String packageCid) { 13339 int idx = packageCid.lastIndexOf("-"); 13340 if (idx == -1) { 13341 return packageCid; 13342 } 13343 return packageCid.substring(0, idx); 13344 } 13345 13346 // Utility method used to create code paths based on package name and available index. 13347 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 13348 String idxStr = ""; 13349 int idx = 1; 13350 // Fall back to default value of idx=1 if prefix is not 13351 // part of oldCodePath 13352 if (oldCodePath != null) { 13353 String subStr = oldCodePath; 13354 // Drop the suffix right away 13355 if (suffix != null && subStr.endsWith(suffix)) { 13356 subStr = subStr.substring(0, subStr.length() - suffix.length()); 13357 } 13358 // If oldCodePath already contains prefix find out the 13359 // ending index to either increment or decrement. 13360 int sidx = subStr.lastIndexOf(prefix); 13361 if (sidx != -1) { 13362 subStr = subStr.substring(sidx + prefix.length()); 13363 if (subStr != null) { 13364 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 13365 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 13366 } 13367 try { 13368 idx = Integer.parseInt(subStr); 13369 if (idx <= 1) { 13370 idx++; 13371 } else { 13372 idx--; 13373 } 13374 } catch(NumberFormatException e) { 13375 } 13376 } 13377 } 13378 } 13379 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 13380 return prefix + idxStr; 13381 } 13382 13383 private File getNextCodePath(File targetDir, String packageName) { 13384 int suffix = 1; 13385 File result; 13386 do { 13387 result = new File(targetDir, packageName + "-" + suffix); 13388 suffix++; 13389 } while (result.exists()); 13390 return result; 13391 } 13392 13393 // Utility method that returns the relative package path with respect 13394 // to the installation directory. Like say for /data/data/com.test-1.apk 13395 // string com.test-1 is returned. 13396 static String deriveCodePathName(String codePath) { 13397 if (codePath == null) { 13398 return null; 13399 } 13400 final File codeFile = new File(codePath); 13401 final String name = codeFile.getName(); 13402 if (codeFile.isDirectory()) { 13403 return name; 13404 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 13405 final int lastDot = name.lastIndexOf('.'); 13406 return name.substring(0, lastDot); 13407 } else { 13408 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 13409 return null; 13410 } 13411 } 13412 13413 static class PackageInstalledInfo { 13414 String name; 13415 int uid; 13416 // The set of users that originally had this package installed. 13417 int[] origUsers; 13418 // The set of users that now have this package installed. 13419 int[] newUsers; 13420 PackageParser.Package pkg; 13421 int returnCode; 13422 String returnMsg; 13423 PackageRemovedInfo removedInfo; 13424 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 13425 13426 public void setError(int code, String msg) { 13427 setReturnCode(code); 13428 setReturnMessage(msg); 13429 Slog.w(TAG, msg); 13430 } 13431 13432 public void setError(String msg, PackageParserException e) { 13433 setReturnCode(e.error); 13434 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13435 Slog.w(TAG, msg, e); 13436 } 13437 13438 public void setError(String msg, PackageManagerException e) { 13439 returnCode = e.error; 13440 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13441 Slog.w(TAG, msg, e); 13442 } 13443 13444 public void setReturnCode(int returnCode) { 13445 this.returnCode = returnCode; 13446 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13447 for (int i = 0; i < childCount; i++) { 13448 addedChildPackages.valueAt(i).returnCode = returnCode; 13449 } 13450 } 13451 13452 private void setReturnMessage(String returnMsg) { 13453 this.returnMsg = returnMsg; 13454 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13455 for (int i = 0; i < childCount; i++) { 13456 addedChildPackages.valueAt(i).returnMsg = returnMsg; 13457 } 13458 } 13459 13460 // In some error cases we want to convey more info back to the observer 13461 String origPackage; 13462 String origPermission; 13463 } 13464 13465 /* 13466 * Install a non-existing package. 13467 */ 13468 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 13469 UserHandle user, String installerPackageName, String volumeUuid, 13470 PackageInstalledInfo res) { 13471 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 13472 13473 // Remember this for later, in case we need to rollback this install 13474 String pkgName = pkg.packageName; 13475 13476 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 13477 13478 synchronized(mPackages) { 13479 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 13480 // A package with the same name is already installed, though 13481 // it has been renamed to an older name. The package we 13482 // are trying to install should be installed as an update to 13483 // the existing one, but that has not been requested, so bail. 13484 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13485 + " without first uninstalling package running as " 13486 + mSettings.mRenamedPackages.get(pkgName)); 13487 return; 13488 } 13489 if (mPackages.containsKey(pkgName)) { 13490 // Don't allow installation over an existing package with the same name. 13491 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13492 + " without first uninstalling."); 13493 return; 13494 } 13495 } 13496 13497 try { 13498 PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 13499 System.currentTimeMillis(), user); 13500 13501 updateSettingsLI(newPackage, installerPackageName, null, res, user); 13502 13503 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13504 prepareAppDataAfterInstall(newPackage); 13505 13506 } else { 13507 // Remove package from internal structures, but keep around any 13508 // data that might have already existed 13509 deletePackageLI(pkgName, UserHandle.ALL, false, null, 13510 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 13511 } 13512 } catch (PackageManagerException e) { 13513 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13514 } 13515 13516 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13517 } 13518 13519 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 13520 // Can't rotate keys during boot or if sharedUser. 13521 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 13522 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 13523 return false; 13524 } 13525 // app is using upgradeKeySets; make sure all are valid 13526 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13527 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 13528 for (int i = 0; i < upgradeKeySets.length; i++) { 13529 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 13530 Slog.wtf(TAG, "Package " 13531 + (oldPs.name != null ? oldPs.name : "<null>") 13532 + " contains upgrade-key-set reference to unknown key-set: " 13533 + upgradeKeySets[i] 13534 + " reverting to signatures check."); 13535 return false; 13536 } 13537 } 13538 return true; 13539 } 13540 13541 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 13542 // Upgrade keysets are being used. Determine if new package has a superset of the 13543 // required keys. 13544 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 13545 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13546 for (int i = 0; i < upgradeKeySets.length; i++) { 13547 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 13548 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 13549 return true; 13550 } 13551 } 13552 return false; 13553 } 13554 13555 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 13556 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 13557 final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 13558 13559 final PackageParser.Package oldPackage; 13560 final String pkgName = pkg.packageName; 13561 final int[] allUsers; 13562 final boolean weFroze; 13563 13564 // First find the old package info and check signatures 13565 synchronized(mPackages) { 13566 oldPackage = mPackages.get(pkgName); 13567 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 13568 if (isEphemeral && !oldIsEphemeral) { 13569 // can't downgrade from full to ephemeral 13570 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 13571 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 13572 return; 13573 } 13574 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 13575 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13576 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 13577 if (!checkUpgradeKeySetLP(ps, pkg)) { 13578 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13579 "New package not signed by keys specified by upgrade-keysets: " 13580 + pkgName); 13581 return; 13582 } 13583 } else { 13584 // default to original signature matching 13585 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 13586 != PackageManager.SIGNATURE_MATCH) { 13587 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13588 "New package has a different signature: " + pkgName); 13589 return; 13590 } 13591 } 13592 13593 // In case of rollback, remember per-user/profile install state 13594 allUsers = sUserManager.getUserIds(); 13595 13596 // Mark the app as frozen to prevent launching during the upgrade 13597 // process, and then kill all running instances 13598 if (!ps.frozen) { 13599 ps.frozen = true; 13600 weFroze = true; 13601 } else { 13602 weFroze = false; 13603 } 13604 } 13605 13606 try { 13607 replacePackageDirtyLI(pkg, oldPackage, parseFlags, scanFlags, user, allUsers, 13608 installerPackageName, res); 13609 } finally { 13610 // Regardless of success or failure of upgrade steps above, always 13611 // unfreeze the package if we froze it 13612 if (weFroze) { 13613 unfreezePackage(pkgName); 13614 } 13615 } 13616 } 13617 13618 private void replacePackageDirtyLI(PackageParser.Package pkg, PackageParser.Package oldPackage, 13619 int parseFlags, int scanFlags, UserHandle user, int[] allUsers, 13620 String installerPackageName, PackageInstalledInfo res) { 13621 // Update what is removed 13622 res.removedInfo = new PackageRemovedInfo(); 13623 res.removedInfo.uid = oldPackage.applicationInfo.uid; 13624 res.removedInfo.removedPackage = oldPackage.packageName; 13625 res.removedInfo.isUpdate = true; 13626 final int childCount = (oldPackage.childPackages != null) 13627 ? oldPackage.childPackages.size() : 0; 13628 for (int i = 0; i < childCount; i++) { 13629 boolean childPackageUpdated = false; 13630 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 13631 if (res.addedChildPackages != null) { 13632 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 13633 if (childRes != null) { 13634 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 13635 childRes.removedInfo.removedPackage = childPkg.packageName; 13636 childRes.removedInfo.isUpdate = true; 13637 childPackageUpdated = true; 13638 } 13639 } 13640 if (!childPackageUpdated) { 13641 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 13642 childRemovedRes.removedPackage = childPkg.packageName; 13643 childRemovedRes.isUpdate = false; 13644 childRemovedRes.dataRemoved = true; 13645 synchronized (mPackages) { 13646 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 13647 if (childPs != null) { 13648 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 13649 } 13650 } 13651 if (res.removedInfo.removedChildPackages == null) { 13652 res.removedInfo.removedChildPackages = new ArrayMap<>(); 13653 } 13654 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 13655 } 13656 } 13657 13658 boolean sysPkg = (isSystemApp(oldPackage)); 13659 if (sysPkg) { 13660 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 13661 user, allUsers, installerPackageName, res); 13662 } else { 13663 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 13664 user, allUsers, installerPackageName, res); 13665 } 13666 } 13667 13668 public List<String> getPreviousCodePaths(String packageName) { 13669 final PackageSetting ps = mSettings.mPackages.get(packageName); 13670 final List<String> result = new ArrayList<String>(); 13671 if (ps != null && ps.oldCodePaths != null) { 13672 result.addAll(ps.oldCodePaths); 13673 } 13674 return result; 13675 } 13676 13677 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 13678 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 13679 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 13680 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 13681 + deletedPackage); 13682 13683 String pkgName = deletedPackage.packageName; 13684 boolean deletedPkg = true; 13685 boolean addedPkg = false; 13686 boolean updatedSettings = false; 13687 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 13688 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 13689 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 13690 13691 final long origUpdateTime = (pkg.mExtras != null) 13692 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 13693 13694 // First delete the existing package while retaining the data directory 13695 if (!deletePackageLI(pkgName, null, true, allUsers, deleteFlags, 13696 res.removedInfo, true, pkg)) { 13697 // If the existing package wasn't successfully deleted 13698 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 13699 deletedPkg = false; 13700 } else { 13701 // Successfully deleted the old package; proceed with replace. 13702 13703 // If deleted package lived in a container, give users a chance to 13704 // relinquish resources before killing. 13705 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 13706 if (DEBUG_INSTALL) { 13707 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 13708 } 13709 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 13710 final ArrayList<String> pkgList = new ArrayList<String>(1); 13711 pkgList.add(deletedPackage.applicationInfo.packageName); 13712 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 13713 } 13714 13715 deleteCodeCacheDirsLI(pkg); 13716 deleteProfilesLI(pkg, /*destroy*/ false); 13717 13718 try { 13719 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, 13720 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 13721 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 13722 13723 // Update the in-memory copy of the previous code paths. 13724 PackageSetting ps = mSettings.mPackages.get(pkgName); 13725 if (!killApp) { 13726 if (ps.oldCodePaths == null) { 13727 ps.oldCodePaths = new ArraySet<>(); 13728 } 13729 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 13730 if (deletedPackage.splitCodePaths != null) { 13731 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 13732 } 13733 } else { 13734 ps.oldCodePaths = null; 13735 } 13736 if (ps.childPackageNames != null) { 13737 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 13738 final String childPkgName = ps.childPackageNames.get(i); 13739 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 13740 childPs.oldCodePaths = ps.oldCodePaths; 13741 } 13742 } 13743 prepareAppDataAfterInstall(newPackage); 13744 addedPkg = true; 13745 } catch (PackageManagerException e) { 13746 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13747 } 13748 } 13749 13750 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 13751 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 13752 13753 // Revert all internal state mutations and added folders for the failed install 13754 if (addedPkg) { 13755 deletePackageLI(pkgName, null, true, allUsers, deleteFlags, 13756 res.removedInfo, true, null); 13757 } 13758 13759 // Restore the old package 13760 if (deletedPkg) { 13761 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 13762 File restoreFile = new File(deletedPackage.codePath); 13763 // Parse old package 13764 boolean oldExternal = isExternal(deletedPackage); 13765 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 13766 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 13767 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 13768 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 13769 try { 13770 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 13771 null); 13772 } catch (PackageManagerException e) { 13773 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 13774 + e.getMessage()); 13775 return; 13776 } 13777 13778 synchronized (mPackages) { 13779 // Ensure the installer package name up to date 13780 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 13781 13782 // Update permissions for restored package 13783 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 13784 13785 mSettings.writeLPr(); 13786 } 13787 13788 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 13789 } 13790 } else { 13791 synchronized (mPackages) { 13792 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 13793 if (ps != null) { 13794 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 13795 if (res.removedInfo.removedChildPackages != null) { 13796 final int childCount = res.removedInfo.removedChildPackages.size(); 13797 // Iterate in reverse as we may modify the collection 13798 for (int i = childCount - 1; i >= 0; i--) { 13799 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 13800 if (res.addedChildPackages.containsKey(childPackageName)) { 13801 res.removedInfo.removedChildPackages.removeAt(i); 13802 } else { 13803 PackageRemovedInfo childInfo = res.removedInfo 13804 .removedChildPackages.valueAt(i); 13805 childInfo.removedForAllUsers = mPackages.get( 13806 childInfo.removedPackage) == null; 13807 } 13808 } 13809 } 13810 } 13811 } 13812 } 13813 } 13814 13815 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 13816 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 13817 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 13818 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 13819 + ", old=" + deletedPackage); 13820 13821 final boolean disabledSystem; 13822 13823 // Set the system/privileged flags as needed 13824 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 13825 if ((deletedPackage.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 13826 != 0) { 13827 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 13828 } 13829 13830 // Kill package processes including services, providers, etc. 13831 killPackage(deletedPackage, "replace sys pkg"); 13832 13833 // Remove existing system package 13834 removePackageLI(deletedPackage, true); 13835 13836 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 13837 if (!disabledSystem) { 13838 // We didn't need to disable the .apk as a current system package, 13839 // which means we are replacing another update that is already 13840 // installed. We need to make sure to delete the older one's .apk. 13841 res.removedInfo.args = createInstallArgsForExisting(0, 13842 deletedPackage.applicationInfo.getCodePath(), 13843 deletedPackage.applicationInfo.getResourcePath(), 13844 getAppDexInstructionSets(deletedPackage.applicationInfo)); 13845 } else { 13846 res.removedInfo.args = null; 13847 } 13848 13849 // Successfully disabled the old package. Now proceed with re-installation 13850 deleteCodeCacheDirsLI(pkg); 13851 deleteProfilesLI(pkg, /*destroy*/ false); 13852 13853 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 13854 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 13855 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 13856 13857 PackageParser.Package newPackage = null; 13858 try { 13859 // Add the package to the internal data structures 13860 newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user); 13861 13862 // Set the update and install times 13863 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 13864 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 13865 System.currentTimeMillis()); 13866 13867 // Check for shared user id changes 13868 String invalidPackageName = getParentOrChildPackageChangedSharedUser( 13869 deletedPackage, newPackage); 13870 if (invalidPackageName != null) { 13871 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 13872 "Forbidding shared user change from " + deletedPkgSetting.sharedUser 13873 + " to " + invalidPackageName); 13874 } 13875 13876 // Update the package dynamic state if succeeded 13877 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13878 // Now that the install succeeded make sure we remove data 13879 // directories for any child package the update removed. 13880 final int deletedChildCount = (deletedPackage.childPackages != null) 13881 ? deletedPackage.childPackages.size() : 0; 13882 final int newChildCount = (newPackage.childPackages != null) 13883 ? newPackage.childPackages.size() : 0; 13884 for (int i = 0; i < deletedChildCount; i++) { 13885 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 13886 boolean childPackageDeleted = true; 13887 for (int j = 0; j < newChildCount; j++) { 13888 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 13889 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 13890 childPackageDeleted = false; 13891 break; 13892 } 13893 } 13894 if (childPackageDeleted) { 13895 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 13896 deletedChildPkg.packageName); 13897 if (ps != null && res.removedInfo.removedChildPackages != null) { 13898 PackageRemovedInfo removedChildRes = res.removedInfo 13899 .removedChildPackages.get(deletedChildPkg.packageName); 13900 removePackageDataLI(ps, allUsers, removedChildRes, 0, false); 13901 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 13902 } 13903 } 13904 } 13905 13906 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 13907 prepareAppDataAfterInstall(newPackage); 13908 } 13909 } catch (PackageManagerException e) { 13910 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 13911 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13912 } 13913 13914 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 13915 // Re installation failed. Restore old information 13916 // Remove new pkg information 13917 if (newPackage != null) { 13918 removeInstalledPackageLI(newPackage, true); 13919 } 13920 // Add back the old system package 13921 try { 13922 scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 13923 } catch (PackageManagerException e) { 13924 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 13925 } 13926 13927 synchronized (mPackages) { 13928 if (disabledSystem) { 13929 enableSystemPackageLPw(deletedPackage); 13930 } 13931 13932 // Ensure the installer package name up to date 13933 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 13934 13935 // Update permissions for restored package 13936 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 13937 13938 mSettings.writeLPr(); 13939 } 13940 13941 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 13942 + " after failed upgrade"); 13943 } 13944 } 13945 13946 /** 13947 * Checks whether the parent or any of the child packages have a change shared 13948 * user. For a package to be a valid update the shred users of the parent and 13949 * the children should match. We may later support changing child shared users. 13950 * @param oldPkg The updated package. 13951 * @param newPkg The update package. 13952 * @return The shared user that change between the versions. 13953 */ 13954 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 13955 PackageParser.Package newPkg) { 13956 // Check parent shared user 13957 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 13958 return newPkg.packageName; 13959 } 13960 // Check child shared users 13961 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 13962 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 13963 for (int i = 0; i < newChildCount; i++) { 13964 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 13965 // If this child was present, did it have the same shared user? 13966 for (int j = 0; j < oldChildCount; j++) { 13967 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 13968 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 13969 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 13970 return newChildPkg.packageName; 13971 } 13972 } 13973 } 13974 return null; 13975 } 13976 13977 private void removeNativeBinariesLI(PackageSetting ps) { 13978 // Remove the lib path for the parent package 13979 if (ps != null) { 13980 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 13981 // Remove the lib path for the child packages 13982 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 13983 for (int i = 0; i < childCount; i++) { 13984 PackageSetting childPs = null; 13985 synchronized (mPackages) { 13986 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 13987 } 13988 if (childPs != null) { 13989 NativeLibraryHelper.removeNativeBinariesLI(childPs 13990 .legacyNativeLibraryPathString); 13991 } 13992 } 13993 } 13994 } 13995 13996 private void enableSystemPackageLPw(PackageParser.Package pkg) { 13997 // Enable the parent package 13998 mSettings.enableSystemPackageLPw(pkg.packageName); 13999 // Enable the child packages 14000 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14001 for (int i = 0; i < childCount; i++) { 14002 PackageParser.Package childPkg = pkg.childPackages.get(i); 14003 mSettings.enableSystemPackageLPw(childPkg.packageName); 14004 } 14005 } 14006 14007 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 14008 PackageParser.Package newPkg) { 14009 // Disable the parent package (parent always replaced) 14010 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 14011 // Disable the child packages 14012 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14013 for (int i = 0; i < childCount; i++) { 14014 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 14015 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 14016 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 14017 } 14018 return disabled; 14019 } 14020 14021 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 14022 String installerPackageName) { 14023 // Enable the parent package 14024 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 14025 // Enable the child packages 14026 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14027 for (int i = 0; i < childCount; i++) { 14028 PackageParser.Package childPkg = pkg.childPackages.get(i); 14029 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 14030 } 14031 } 14032 14033 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 14034 // Collect all used permissions in the UID 14035 ArraySet<String> usedPermissions = new ArraySet<>(); 14036 final int packageCount = su.packages.size(); 14037 for (int i = 0; i < packageCount; i++) { 14038 PackageSetting ps = su.packages.valueAt(i); 14039 if (ps.pkg == null) { 14040 continue; 14041 } 14042 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 14043 for (int j = 0; j < requestedPermCount; j++) { 14044 String permission = ps.pkg.requestedPermissions.get(j); 14045 BasePermission bp = mSettings.mPermissions.get(permission); 14046 if (bp != null) { 14047 usedPermissions.add(permission); 14048 } 14049 } 14050 } 14051 14052 PermissionsState permissionsState = su.getPermissionsState(); 14053 // Prune install permissions 14054 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 14055 final int installPermCount = installPermStates.size(); 14056 for (int i = installPermCount - 1; i >= 0; i--) { 14057 PermissionState permissionState = installPermStates.get(i); 14058 if (!usedPermissions.contains(permissionState.getName())) { 14059 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14060 if (bp != null) { 14061 permissionsState.revokeInstallPermission(bp); 14062 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 14063 PackageManager.MASK_PERMISSION_FLAGS, 0); 14064 } 14065 } 14066 } 14067 14068 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 14069 14070 // Prune runtime permissions 14071 for (int userId : allUserIds) { 14072 List<PermissionState> runtimePermStates = permissionsState 14073 .getRuntimePermissionStates(userId); 14074 final int runtimePermCount = runtimePermStates.size(); 14075 for (int i = runtimePermCount - 1; i >= 0; i--) { 14076 PermissionState permissionState = runtimePermStates.get(i); 14077 if (!usedPermissions.contains(permissionState.getName())) { 14078 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14079 if (bp != null) { 14080 permissionsState.revokeRuntimePermission(bp, userId); 14081 permissionsState.updatePermissionFlags(bp, userId, 14082 PackageManager.MASK_PERMISSION_FLAGS, 0); 14083 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 14084 runtimePermissionChangedUserIds, userId); 14085 } 14086 } 14087 } 14088 } 14089 14090 return runtimePermissionChangedUserIds; 14091 } 14092 14093 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 14094 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 14095 // Update the parent package setting 14096 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 14097 res, user); 14098 // Update the child packages setting 14099 final int childCount = (newPackage.childPackages != null) 14100 ? newPackage.childPackages.size() : 0; 14101 for (int i = 0; i < childCount; i++) { 14102 PackageParser.Package childPackage = newPackage.childPackages.get(i); 14103 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 14104 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 14105 childRes.origUsers, childRes, user); 14106 } 14107 } 14108 14109 private void updateSettingsInternalLI(PackageParser.Package newPackage, 14110 String installerPackageName, int[] allUsers, int[] installedForUsers, 14111 PackageInstalledInfo res, UserHandle user) { 14112 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 14113 14114 String pkgName = newPackage.packageName; 14115 synchronized (mPackages) { 14116 //write settings. the installStatus will be incomplete at this stage. 14117 //note that the new package setting would have already been 14118 //added to mPackages. It hasn't been persisted yet. 14119 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 14120 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14121 mSettings.writeLPr(); 14122 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14123 } 14124 14125 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 14126 synchronized (mPackages) { 14127 updatePermissionsLPw(newPackage.packageName, newPackage, 14128 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 14129 ? UPDATE_PERMISSIONS_ALL : 0)); 14130 // For system-bundled packages, we assume that installing an upgraded version 14131 // of the package implies that the user actually wants to run that new code, 14132 // so we enable the package. 14133 PackageSetting ps = mSettings.mPackages.get(pkgName); 14134 final int userId = user.getIdentifier(); 14135 if (ps != null) { 14136 if (isSystemApp(newPackage)) { 14137 if (DEBUG_INSTALL) { 14138 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 14139 } 14140 // Enable system package for requested users 14141 if (res.origUsers != null) { 14142 for (int origUserId : res.origUsers) { 14143 if (userId == UserHandle.USER_ALL || userId == origUserId) { 14144 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 14145 origUserId, installerPackageName); 14146 } 14147 } 14148 } 14149 // Also convey the prior install/uninstall state 14150 if (allUsers != null && installedForUsers != null) { 14151 for (int currentUserId : allUsers) { 14152 final boolean installed = ArrayUtils.contains( 14153 installedForUsers, currentUserId); 14154 if (DEBUG_INSTALL) { 14155 Slog.d(TAG, " user " + currentUserId + " => " + installed); 14156 } 14157 ps.setInstalled(installed, currentUserId); 14158 } 14159 // these install state changes will be persisted in the 14160 // upcoming call to mSettings.writeLPr(). 14161 } 14162 } 14163 // It's implied that when a user requests installation, they want the app to be 14164 // installed and enabled. 14165 if (userId != UserHandle.USER_ALL) { 14166 ps.setInstalled(true, userId); 14167 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 14168 } 14169 } 14170 res.name = pkgName; 14171 res.uid = newPackage.applicationInfo.uid; 14172 res.pkg = newPackage; 14173 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 14174 mSettings.setInstallerPackageName(pkgName, installerPackageName); 14175 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14176 //to update install status 14177 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14178 mSettings.writeLPr(); 14179 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14180 } 14181 14182 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14183 } 14184 14185 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 14186 try { 14187 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 14188 installPackageLI(args, res); 14189 } finally { 14190 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14191 } 14192 } 14193 14194 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 14195 final int installFlags = args.installFlags; 14196 final String installerPackageName = args.installerPackageName; 14197 final String volumeUuid = args.volumeUuid; 14198 final File tmpPackageFile = new File(args.getCodePath()); 14199 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 14200 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 14201 || (args.volumeUuid != null)); 14202 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 14203 boolean replace = false; 14204 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 14205 if (args.move != null) { 14206 // moving a complete application; perform an initial scan on the new install location 14207 scanFlags |= SCAN_INITIAL; 14208 } 14209 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 14210 scanFlags |= SCAN_DONT_KILL_APP; 14211 } 14212 14213 // Result object to be returned 14214 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14215 14216 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 14217 14218 // Sanity check 14219 if (ephemeral && (forwardLocked || onExternal)) { 14220 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 14221 + " external=" + onExternal); 14222 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14223 return; 14224 } 14225 14226 // Retrieve PackageSettings and parse package 14227 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 14228 | PackageParser.PARSE_ENFORCE_CODE 14229 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 14230 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 14231 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0); 14232 PackageParser pp = new PackageParser(); 14233 pp.setSeparateProcesses(mSeparateProcesses); 14234 pp.setDisplayMetrics(mMetrics); 14235 14236 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 14237 final PackageParser.Package pkg; 14238 try { 14239 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 14240 } catch (PackageParserException e) { 14241 res.setError("Failed parse during installPackageLI", e); 14242 return; 14243 } finally { 14244 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14245 } 14246 14247 // If we are installing a clustered package add results for the children 14248 if (pkg.childPackages != null) { 14249 synchronized (mPackages) { 14250 final int childCount = pkg.childPackages.size(); 14251 for (int i = 0; i < childCount; i++) { 14252 PackageParser.Package childPkg = pkg.childPackages.get(i); 14253 PackageInstalledInfo childRes = new PackageInstalledInfo(); 14254 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14255 childRes.pkg = childPkg; 14256 childRes.name = childPkg.packageName; 14257 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14258 if (childPs != null) { 14259 childRes.origUsers = childPs.queryInstalledUsers( 14260 sUserManager.getUserIds(), true); 14261 } 14262 if ((mPackages.containsKey(childPkg.packageName))) { 14263 childRes.removedInfo = new PackageRemovedInfo(); 14264 childRes.removedInfo.removedPackage = childPkg.packageName; 14265 } 14266 if (res.addedChildPackages == null) { 14267 res.addedChildPackages = new ArrayMap<>(); 14268 } 14269 res.addedChildPackages.put(childPkg.packageName, childRes); 14270 } 14271 } 14272 } 14273 14274 // If package doesn't declare API override, mark that we have an install 14275 // time CPU ABI override. 14276 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 14277 pkg.cpuAbiOverride = args.abiOverride; 14278 } 14279 14280 String pkgName = res.name = pkg.packageName; 14281 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 14282 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 14283 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 14284 return; 14285 } 14286 } 14287 14288 try { 14289 // either use what we've been given or parse directly from the APK 14290 if (args.certificates != null) { 14291 try { 14292 PackageParser.populateCertificates(pkg, args.certificates); 14293 } catch (PackageParserException e) { 14294 // there was something wrong with the certificates we were given; 14295 // try to pull them from the APK 14296 PackageParser.collectCertificates(pkg, parseFlags); 14297 } 14298 } else { 14299 PackageParser.collectCertificates(pkg, parseFlags); 14300 } 14301 } catch (PackageParserException e) { 14302 res.setError("Failed collect during installPackageLI", e); 14303 return; 14304 } 14305 14306 // Get rid of all references to package scan path via parser. 14307 pp = null; 14308 String oldCodePath = null; 14309 boolean systemApp = false; 14310 synchronized (mPackages) { 14311 // Check if installing already existing package 14312 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14313 String oldName = mSettings.mRenamedPackages.get(pkgName); 14314 if (pkg.mOriginalPackages != null 14315 && pkg.mOriginalPackages.contains(oldName) 14316 && mPackages.containsKey(oldName)) { 14317 // This package is derived from an original package, 14318 // and this device has been updating from that original 14319 // name. We must continue using the original name, so 14320 // rename the new package here. 14321 pkg.setPackageName(oldName); 14322 pkgName = pkg.packageName; 14323 replace = true; 14324 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 14325 + oldName + " pkgName=" + pkgName); 14326 } else if (mPackages.containsKey(pkgName)) { 14327 // This package, under its official name, already exists 14328 // on the device; we should replace it. 14329 replace = true; 14330 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 14331 } 14332 14333 // Child packages are installed through the parent package 14334 if (pkg.parentPackage != null) { 14335 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14336 "Package " + pkg.packageName + " is child of package " 14337 + pkg.parentPackage.parentPackage + ". Child packages " 14338 + "can be updated only through the parent package."); 14339 return; 14340 } 14341 14342 if (replace) { 14343 // Prevent apps opting out from runtime permissions 14344 PackageParser.Package oldPackage = mPackages.get(pkgName); 14345 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 14346 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 14347 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 14348 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 14349 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 14350 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 14351 + " doesn't support runtime permissions but the old" 14352 + " target SDK " + oldTargetSdk + " does."); 14353 return; 14354 } 14355 14356 // Prevent installing of child packages 14357 if (oldPackage.parentPackage != null) { 14358 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14359 "Package " + pkg.packageName + " is child of package " 14360 + oldPackage.parentPackage + ". Child packages " 14361 + "can be updated only through the parent package."); 14362 return; 14363 } 14364 } 14365 } 14366 14367 PackageSetting ps = mSettings.mPackages.get(pkgName); 14368 if (ps != null) { 14369 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 14370 14371 // Quick sanity check that we're signed correctly if updating; 14372 // we'll check this again later when scanning, but we want to 14373 // bail early here before tripping over redefined permissions. 14374 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14375 if (!checkUpgradeKeySetLP(ps, pkg)) { 14376 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 14377 + pkg.packageName + " upgrade keys do not match the " 14378 + "previously installed version"); 14379 return; 14380 } 14381 } else { 14382 try { 14383 verifySignaturesLP(ps, pkg); 14384 } catch (PackageManagerException e) { 14385 res.setError(e.error, e.getMessage()); 14386 return; 14387 } 14388 } 14389 14390 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 14391 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 14392 systemApp = (ps.pkg.applicationInfo.flags & 14393 ApplicationInfo.FLAG_SYSTEM) != 0; 14394 } 14395 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14396 } 14397 14398 // Check whether the newly-scanned package wants to define an already-defined perm 14399 int N = pkg.permissions.size(); 14400 for (int i = N-1; i >= 0; i--) { 14401 PackageParser.Permission perm = pkg.permissions.get(i); 14402 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 14403 if (bp != null) { 14404 // If the defining package is signed with our cert, it's okay. This 14405 // also includes the "updating the same package" case, of course. 14406 // "updating same package" could also involve key-rotation. 14407 final boolean sigsOk; 14408 if (bp.sourcePackage.equals(pkg.packageName) 14409 && (bp.packageSetting instanceof PackageSetting) 14410 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 14411 scanFlags))) { 14412 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 14413 } else { 14414 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 14415 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 14416 } 14417 if (!sigsOk) { 14418 // If the owning package is the system itself, we log but allow 14419 // install to proceed; we fail the install on all other permission 14420 // redefinitions. 14421 if (!bp.sourcePackage.equals("android")) { 14422 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 14423 + pkg.packageName + " attempting to redeclare permission " 14424 + perm.info.name + " already owned by " + bp.sourcePackage); 14425 res.origPermission = perm.info.name; 14426 res.origPackage = bp.sourcePackage; 14427 return; 14428 } else { 14429 Slog.w(TAG, "Package " + pkg.packageName 14430 + " attempting to redeclare system permission " 14431 + perm.info.name + "; ignoring new declaration"); 14432 pkg.permissions.remove(i); 14433 } 14434 } 14435 } 14436 } 14437 } 14438 14439 if (systemApp) { 14440 if (onExternal) { 14441 // Abort update; system app can't be replaced with app on sdcard 14442 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 14443 "Cannot install updates to system apps on sdcard"); 14444 return; 14445 } else if (ephemeral) { 14446 // Abort update; system app can't be replaced with an ephemeral app 14447 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 14448 "Cannot update a system app with an ephemeral app"); 14449 return; 14450 } 14451 } 14452 14453 if (args.move != null) { 14454 // We did an in-place move, so dex is ready to roll 14455 scanFlags |= SCAN_NO_DEX; 14456 scanFlags |= SCAN_MOVE; 14457 14458 synchronized (mPackages) { 14459 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14460 if (ps == null) { 14461 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 14462 "Missing settings for moved package " + pkgName); 14463 } 14464 14465 // We moved the entire application as-is, so bring over the 14466 // previously derived ABI information. 14467 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 14468 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 14469 } 14470 14471 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 14472 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 14473 scanFlags |= SCAN_NO_DEX; 14474 14475 try { 14476 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 14477 args.abiOverride : pkg.cpuAbiOverride); 14478 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 14479 true /* extract libs */); 14480 } catch (PackageManagerException pme) { 14481 Slog.e(TAG, "Error deriving application ABI", pme); 14482 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 14483 return; 14484 } 14485 14486 14487 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 14488 // Do not run PackageDexOptimizer through the local performDexOpt 14489 // method because `pkg` is not in `mPackages` yet. 14490 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instructionSets */, 14491 false /* checkProfiles */, getCompilerFilterForReason(REASON_INSTALL)); 14492 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14493 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 14494 String msg = "Extracking package failed for " + pkgName; 14495 res.setError(INSTALL_FAILED_DEXOPT, msg); 14496 return; 14497 } 14498 } 14499 14500 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 14501 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 14502 return; 14503 } 14504 14505 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 14506 14507 if (replace) { 14508 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 14509 installerPackageName, res); 14510 } else { 14511 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 14512 args.user, installerPackageName, volumeUuid, res); 14513 } 14514 synchronized (mPackages) { 14515 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14516 if (ps != null) { 14517 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14518 } 14519 14520 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14521 for (int i = 0; i < childCount; i++) { 14522 PackageParser.Package childPkg = pkg.childPackages.get(i); 14523 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14524 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14525 if (childPs != null) { 14526 childRes.newUsers = childPs.queryInstalledUsers( 14527 sUserManager.getUserIds(), true); 14528 } 14529 } 14530 } 14531 } 14532 14533 private void startIntentFilterVerifications(int userId, boolean replacing, 14534 PackageParser.Package pkg) { 14535 if (mIntentFilterVerifierComponent == null) { 14536 Slog.w(TAG, "No IntentFilter verification will not be done as " 14537 + "there is no IntentFilterVerifier available!"); 14538 return; 14539 } 14540 14541 final int verifierUid = getPackageUid( 14542 mIntentFilterVerifierComponent.getPackageName(), 14543 MATCH_DEBUG_TRIAGED_MISSING, 14544 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 14545 14546 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14547 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 14548 mHandler.sendMessage(msg); 14549 14550 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14551 for (int i = 0; i < childCount; i++) { 14552 PackageParser.Package childPkg = pkg.childPackages.get(i); 14553 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14554 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 14555 mHandler.sendMessage(msg); 14556 } 14557 } 14558 14559 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 14560 PackageParser.Package pkg) { 14561 int size = pkg.activities.size(); 14562 if (size == 0) { 14563 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14564 "No activity, so no need to verify any IntentFilter!"); 14565 return; 14566 } 14567 14568 final boolean hasDomainURLs = hasDomainURLs(pkg); 14569 if (!hasDomainURLs) { 14570 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14571 "No domain URLs, so no need to verify any IntentFilter!"); 14572 return; 14573 } 14574 14575 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 14576 + " if any IntentFilter from the " + size 14577 + " Activities needs verification ..."); 14578 14579 int count = 0; 14580 final String packageName = pkg.packageName; 14581 14582 synchronized (mPackages) { 14583 // If this is a new install and we see that we've already run verification for this 14584 // package, we have nothing to do: it means the state was restored from backup. 14585 if (!replacing) { 14586 IntentFilterVerificationInfo ivi = 14587 mSettings.getIntentFilterVerificationLPr(packageName); 14588 if (ivi != null) { 14589 if (DEBUG_DOMAIN_VERIFICATION) { 14590 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 14591 + ivi.getStatusString()); 14592 } 14593 return; 14594 } 14595 } 14596 14597 // If any filters need to be verified, then all need to be. 14598 boolean needToVerify = false; 14599 for (PackageParser.Activity a : pkg.activities) { 14600 for (ActivityIntentInfo filter : a.intents) { 14601 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 14602 if (DEBUG_DOMAIN_VERIFICATION) { 14603 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 14604 } 14605 needToVerify = true; 14606 break; 14607 } 14608 } 14609 } 14610 14611 if (needToVerify) { 14612 final int verificationId = mIntentFilterVerificationToken++; 14613 for (PackageParser.Activity a : pkg.activities) { 14614 for (ActivityIntentInfo filter : a.intents) { 14615 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 14616 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14617 "Verification needed for IntentFilter:" + filter.toString()); 14618 mIntentFilterVerifier.addOneIntentFilterVerification( 14619 verifierUid, userId, verificationId, filter, packageName); 14620 count++; 14621 } 14622 } 14623 } 14624 } 14625 } 14626 14627 if (count > 0) { 14628 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 14629 + " IntentFilter verification" + (count > 1 ? "s" : "") 14630 + " for userId:" + userId); 14631 mIntentFilterVerifier.startVerifications(userId); 14632 } else { 14633 if (DEBUG_DOMAIN_VERIFICATION) { 14634 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 14635 } 14636 } 14637 } 14638 14639 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 14640 final ComponentName cn = filter.activity.getComponentName(); 14641 final String packageName = cn.getPackageName(); 14642 14643 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 14644 packageName); 14645 if (ivi == null) { 14646 return true; 14647 } 14648 int status = ivi.getStatus(); 14649 switch (status) { 14650 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 14651 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 14652 return true; 14653 14654 default: 14655 // Nothing to do 14656 return false; 14657 } 14658 } 14659 14660 private static boolean isMultiArch(ApplicationInfo info) { 14661 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 14662 } 14663 14664 private static boolean isExternal(PackageParser.Package pkg) { 14665 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 14666 } 14667 14668 private static boolean isExternal(PackageSetting ps) { 14669 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 14670 } 14671 14672 private static boolean isEphemeral(PackageParser.Package pkg) { 14673 return pkg.applicationInfo.isEphemeralApp(); 14674 } 14675 14676 private static boolean isEphemeral(PackageSetting ps) { 14677 return ps.pkg != null && isEphemeral(ps.pkg); 14678 } 14679 14680 private static boolean isSystemApp(PackageParser.Package pkg) { 14681 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 14682 } 14683 14684 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 14685 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14686 } 14687 14688 private static boolean hasDomainURLs(PackageParser.Package pkg) { 14689 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 14690 } 14691 14692 private static boolean isSystemApp(PackageSetting ps) { 14693 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 14694 } 14695 14696 private static boolean isUpdatedSystemApp(PackageSetting ps) { 14697 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 14698 } 14699 14700 private int packageFlagsToInstallFlags(PackageSetting ps) { 14701 int installFlags = 0; 14702 if (isEphemeral(ps)) { 14703 installFlags |= PackageManager.INSTALL_EPHEMERAL; 14704 } 14705 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 14706 // This existing package was an external ASEC install when we have 14707 // the external flag without a UUID 14708 installFlags |= PackageManager.INSTALL_EXTERNAL; 14709 } 14710 if (ps.isForwardLocked()) { 14711 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 14712 } 14713 return installFlags; 14714 } 14715 14716 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 14717 if (isExternal(pkg)) { 14718 if (TextUtils.isEmpty(pkg.volumeUuid)) { 14719 return StorageManager.UUID_PRIMARY_PHYSICAL; 14720 } else { 14721 return pkg.volumeUuid; 14722 } 14723 } else { 14724 return StorageManager.UUID_PRIVATE_INTERNAL; 14725 } 14726 } 14727 14728 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 14729 if (isExternal(pkg)) { 14730 if (TextUtils.isEmpty(pkg.volumeUuid)) { 14731 return mSettings.getExternalVersion(); 14732 } else { 14733 return mSettings.findOrCreateVersion(pkg.volumeUuid); 14734 } 14735 } else { 14736 return mSettings.getInternalVersion(); 14737 } 14738 } 14739 14740 private void deleteTempPackageFiles() { 14741 final FilenameFilter filter = new FilenameFilter() { 14742 public boolean accept(File dir, String name) { 14743 return name.startsWith("vmdl") && name.endsWith(".tmp"); 14744 } 14745 }; 14746 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 14747 file.delete(); 14748 } 14749 } 14750 14751 @Override 14752 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 14753 int flags) { 14754 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 14755 flags); 14756 } 14757 14758 @Override 14759 public void deletePackage(final String packageName, 14760 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 14761 mContext.enforceCallingOrSelfPermission( 14762 android.Manifest.permission.DELETE_PACKAGES, null); 14763 Preconditions.checkNotNull(packageName); 14764 Preconditions.checkNotNull(observer); 14765 final int uid = Binder.getCallingUid(); 14766 final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0; 14767 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 14768 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 14769 mContext.enforceCallingOrSelfPermission( 14770 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 14771 "deletePackage for user " + userId); 14772 } 14773 14774 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 14775 try { 14776 observer.onPackageDeleted(packageName, 14777 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 14778 } catch (RemoteException re) { 14779 } 14780 return; 14781 } 14782 14783 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 14784 try { 14785 observer.onPackageDeleted(packageName, 14786 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 14787 } catch (RemoteException re) { 14788 } 14789 return; 14790 } 14791 14792 if (DEBUG_REMOVE) { 14793 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 14794 + " deleteAllUsers: " + deleteAllUsers ); 14795 } 14796 // Queue up an async operation since the package deletion may take a little while. 14797 mHandler.post(new Runnable() { 14798 public void run() { 14799 mHandler.removeCallbacks(this); 14800 int returnCode; 14801 if (!deleteAllUsers) { 14802 returnCode = deletePackageX(packageName, userId, flags); 14803 } else { 14804 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 14805 // If nobody is blocking uninstall, proceed with delete for all users 14806 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 14807 returnCode = deletePackageX(packageName, userId, flags); 14808 } else { 14809 // Otherwise uninstall individually for users with blockUninstalls=false 14810 final int userFlags = flags & ~PackageManager.DELETE_ALL_USERS; 14811 for (int userId : users) { 14812 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 14813 returnCode = deletePackageX(packageName, userId, userFlags); 14814 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 14815 Slog.w(TAG, "Package delete failed for user " + userId 14816 + ", returnCode " + returnCode); 14817 } 14818 } 14819 } 14820 // The app has only been marked uninstalled for certain users. 14821 // We still need to report that delete was blocked 14822 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 14823 } 14824 } 14825 try { 14826 observer.onPackageDeleted(packageName, returnCode, null); 14827 } catch (RemoteException e) { 14828 Log.i(TAG, "Observer no longer exists."); 14829 } //end catch 14830 } //end run 14831 }); 14832 } 14833 14834 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 14835 int[] result = EMPTY_INT_ARRAY; 14836 for (int userId : userIds) { 14837 if (getBlockUninstallForUser(packageName, userId)) { 14838 result = ArrayUtils.appendInt(result, userId); 14839 } 14840 } 14841 return result; 14842 } 14843 14844 @Override 14845 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 14846 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 14847 } 14848 14849 private boolean isPackageDeviceAdmin(String packageName, int userId) { 14850 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 14851 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 14852 try { 14853 if (dpm != null) { 14854 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 14855 /* callingUserOnly =*/ false); 14856 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 14857 : deviceOwnerComponentName.getPackageName(); 14858 // Does the package contains the device owner? 14859 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 14860 // this check is probably not needed, since DO should be registered as a device 14861 // admin on some user too. (Original bug for this: b/17657954) 14862 if (packageName.equals(deviceOwnerPackageName)) { 14863 return true; 14864 } 14865 // Does it contain a device admin for any user? 14866 int[] users; 14867 if (userId == UserHandle.USER_ALL) { 14868 users = sUserManager.getUserIds(); 14869 } else { 14870 users = new int[]{userId}; 14871 } 14872 for (int i = 0; i < users.length; ++i) { 14873 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 14874 return true; 14875 } 14876 } 14877 } 14878 } catch (RemoteException e) { 14879 } 14880 return false; 14881 } 14882 14883 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 14884 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 14885 } 14886 14887 /** 14888 * This method is an internal method that could be get invoked either 14889 * to delete an installed package or to clean up a failed installation. 14890 * After deleting an installed package, a broadcast is sent to notify any 14891 * listeners that the package has been installed. For cleaning up a failed 14892 * installation, the broadcast is not necessary since the package's 14893 * installation wouldn't have sent the initial broadcast either 14894 * The key steps in deleting a package are 14895 * deleting the package information in internal structures like mPackages, 14896 * deleting the packages base directories through installd 14897 * updating mSettings to reflect current status 14898 * persisting settings for later use 14899 * sending a broadcast if necessary 14900 */ 14901 private int deletePackageX(String packageName, int userId, int flags) { 14902 final PackageRemovedInfo info = new PackageRemovedInfo(); 14903 final boolean res; 14904 14905 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 14906 ? UserHandle.ALL : new UserHandle(userId); 14907 14908 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 14909 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 14910 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 14911 } 14912 14913 PackageSetting uninstalledPs = null; 14914 14915 // for the uninstall-updates case and restricted profiles, remember the per- 14916 // user handle installed state 14917 int[] allUsers; 14918 synchronized (mPackages) { 14919 uninstalledPs = mSettings.mPackages.get(packageName); 14920 if (uninstalledPs == null) { 14921 Slog.w(TAG, "Not removing non-existent package " + packageName); 14922 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 14923 } 14924 allUsers = sUserManager.getUserIds(); 14925 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 14926 } 14927 14928 synchronized (mInstallLock) { 14929 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 14930 res = deletePackageLI(packageName, removeForUser, true, allUsers, 14931 flags | REMOVE_CHATTY, info, true, null); 14932 synchronized (mPackages) { 14933 if (res) { 14934 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 14935 } 14936 } 14937 } 14938 14939 if (res) { 14940 final boolean killApp = (flags & PackageManager.INSTALL_DONT_KILL_APP) == 0; 14941 info.sendPackageRemovedBroadcasts(killApp); 14942 info.sendSystemPackageUpdatedBroadcasts(); 14943 info.sendSystemPackageAppearedBroadcasts(); 14944 } 14945 // Force a gc here. 14946 Runtime.getRuntime().gc(); 14947 // Delete the resources here after sending the broadcast to let 14948 // other processes clean up before deleting resources. 14949 if (info.args != null) { 14950 synchronized (mInstallLock) { 14951 info.args.doPostDeleteLI(true); 14952 } 14953 } 14954 14955 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 14956 } 14957 14958 class PackageRemovedInfo { 14959 String removedPackage; 14960 int uid = -1; 14961 int removedAppId = -1; 14962 int[] origUsers; 14963 int[] removedUsers = null; 14964 boolean isRemovedPackageSystemUpdate = false; 14965 boolean isUpdate; 14966 boolean dataRemoved; 14967 boolean removedForAllUsers; 14968 // Clean up resources deleted packages. 14969 InstallArgs args = null; 14970 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 14971 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 14972 14973 void sendPackageRemovedBroadcasts(boolean killApp) { 14974 sendPackageRemovedBroadcastInternal(killApp); 14975 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 14976 for (int i = 0; i < childCount; i++) { 14977 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 14978 childInfo.sendPackageRemovedBroadcastInternal(killApp); 14979 } 14980 } 14981 14982 void sendSystemPackageUpdatedBroadcasts() { 14983 if (isRemovedPackageSystemUpdate) { 14984 sendSystemPackageUpdatedBroadcastsInternal(); 14985 final int childCount = (removedChildPackages != null) 14986 ? removedChildPackages.size() : 0; 14987 for (int i = 0; i < childCount; i++) { 14988 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 14989 if (childInfo.isRemovedPackageSystemUpdate) { 14990 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 14991 } 14992 } 14993 } 14994 } 14995 14996 void sendSystemPackageAppearedBroadcasts() { 14997 final int packageCount = (appearedChildPackages != null) 14998 ? appearedChildPackages.size() : 0; 14999 for (int i = 0; i < packageCount; i++) { 15000 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 15001 for (int userId : installedInfo.newUsers) { 15002 sendPackageAddedForUser(installedInfo.name, true, 15003 UserHandle.getAppId(installedInfo.uid), userId); 15004 } 15005 } 15006 } 15007 15008 private void sendSystemPackageUpdatedBroadcastsInternal() { 15009 Bundle extras = new Bundle(2); 15010 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15011 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15012 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 15013 extras, 0, null, null, null); 15014 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 15015 extras, 0, null, null, null); 15016 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 15017 null, 0, removedPackage, null, null); 15018 } 15019 15020 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 15021 Bundle extras = new Bundle(2); 15022 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15023 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 15024 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 15025 if (isUpdate || isRemovedPackageSystemUpdate) { 15026 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15027 } 15028 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 15029 if (removedPackage != null) { 15030 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 15031 extras, 0, null, null, removedUsers); 15032 if (dataRemoved && !isRemovedPackageSystemUpdate) { 15033 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 15034 removedPackage, extras, 0, null, null, removedUsers); 15035 } 15036 } 15037 if (removedAppId >= 0) { 15038 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 15039 removedUsers); 15040 } 15041 } 15042 } 15043 15044 /* 15045 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 15046 * flag is not set, the data directory is removed as well. 15047 * make sure this flag is set for partially installed apps. If not its meaningless to 15048 * delete a partially installed application. 15049 */ 15050 private void removePackageDataLI(PackageSetting ps, int[] allUserHandles, 15051 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 15052 String packageName = ps.name; 15053 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 15054 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 15055 // Retrieve object to delete permissions for shared user later on 15056 final PackageSetting deletedPs; 15057 // reader 15058 synchronized (mPackages) { 15059 deletedPs = mSettings.mPackages.get(packageName); 15060 if (outInfo != null) { 15061 outInfo.removedPackage = packageName; 15062 outInfo.removedUsers = deletedPs != null 15063 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 15064 : null; 15065 } 15066 } 15067 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 15068 removeDataDirsLI(ps.volumeUuid, packageName); 15069 if (outInfo != null) { 15070 outInfo.dataRemoved = true; 15071 } 15072 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 15073 } 15074 // writer 15075 synchronized (mPackages) { 15076 if (deletedPs != null) { 15077 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 15078 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 15079 clearDefaultBrowserIfNeeded(packageName); 15080 if (outInfo != null) { 15081 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 15082 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 15083 } 15084 updatePermissionsLPw(deletedPs.name, null, 0); 15085 if (deletedPs.sharedUser != null) { 15086 // Remove permissions associated with package. Since runtime 15087 // permissions are per user we have to kill the removed package 15088 // or packages running under the shared user of the removed 15089 // package if revoking the permissions requested only by the removed 15090 // package is successful and this causes a change in gids. 15091 for (int userId : UserManagerService.getInstance().getUserIds()) { 15092 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 15093 userId); 15094 if (userIdToKill == UserHandle.USER_ALL 15095 || userIdToKill >= UserHandle.USER_SYSTEM) { 15096 // If gids changed for this user, kill all affected packages. 15097 mHandler.post(new Runnable() { 15098 @Override 15099 public void run() { 15100 // This has to happen with no lock held. 15101 killApplication(deletedPs.name, deletedPs.appId, 15102 KILL_APP_REASON_GIDS_CHANGED); 15103 } 15104 }); 15105 break; 15106 } 15107 } 15108 } 15109 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 15110 } 15111 // make sure to preserve per-user disabled state if this removal was just 15112 // a downgrade of a system app to the factory package 15113 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 15114 if (DEBUG_REMOVE) { 15115 Slog.d(TAG, "Propagating install state across downgrade"); 15116 } 15117 for (int userId : allUserHandles) { 15118 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15119 if (DEBUG_REMOVE) { 15120 Slog.d(TAG, " user " + userId + " => " + installed); 15121 } 15122 ps.setInstalled(installed, userId); 15123 } 15124 } 15125 } 15126 // can downgrade to reader 15127 if (writeSettings) { 15128 // Save settings now 15129 mSettings.writeLPr(); 15130 } 15131 } 15132 if (outInfo != null) { 15133 // A user ID was deleted here. Go through all users and remove it 15134 // from KeyStore. 15135 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 15136 } 15137 } 15138 15139 static boolean locationIsPrivileged(File path) { 15140 try { 15141 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 15142 .getCanonicalPath(); 15143 return path.getCanonicalPath().startsWith(privilegedAppDir); 15144 } catch (IOException e) { 15145 Slog.e(TAG, "Unable to access code path " + path); 15146 } 15147 return false; 15148 } 15149 15150 /* 15151 * Tries to delete system package. 15152 */ 15153 private boolean deleteSystemPackageLI(PackageParser.Package deletedPkg, 15154 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 15155 boolean writeSettings) { 15156 if (deletedPs.parentPackageName != null) { 15157 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 15158 return false; 15159 } 15160 15161 final boolean applyUserRestrictions 15162 = (allUserHandles != null) && (outInfo.origUsers != null); 15163 final PackageSetting disabledPs; 15164 // Confirm if the system package has been updated 15165 // An updated system app can be deleted. This will also have to restore 15166 // the system pkg from system partition 15167 // reader 15168 synchronized (mPackages) { 15169 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 15170 } 15171 15172 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 15173 + " disabledPs=" + disabledPs); 15174 15175 if (disabledPs == null) { 15176 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 15177 return false; 15178 } else if (DEBUG_REMOVE) { 15179 Slog.d(TAG, "Deleting system pkg from data partition"); 15180 } 15181 15182 if (DEBUG_REMOVE) { 15183 if (applyUserRestrictions) { 15184 Slog.d(TAG, "Remembering install states:"); 15185 for (int userId : allUserHandles) { 15186 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 15187 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 15188 } 15189 } 15190 } 15191 15192 // Delete the updated package 15193 outInfo.isRemovedPackageSystemUpdate = true; 15194 if (outInfo.removedChildPackages != null) { 15195 final int childCount = (deletedPs.childPackageNames != null) 15196 ? deletedPs.childPackageNames.size() : 0; 15197 for (int i = 0; i < childCount; i++) { 15198 String childPackageName = deletedPs.childPackageNames.get(i); 15199 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 15200 .contains(childPackageName)) { 15201 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15202 childPackageName); 15203 if (childInfo != null) { 15204 childInfo.isRemovedPackageSystemUpdate = true; 15205 } 15206 } 15207 } 15208 } 15209 15210 if (disabledPs.versionCode < deletedPs.versionCode) { 15211 // Delete data for downgrades 15212 flags &= ~PackageManager.DELETE_KEEP_DATA; 15213 } else { 15214 // Preserve data by setting flag 15215 flags |= PackageManager.DELETE_KEEP_DATA; 15216 } 15217 15218 boolean ret = deleteInstalledPackageLI(deletedPs, true, flags, allUserHandles, 15219 outInfo, writeSettings, disabledPs.pkg); 15220 if (!ret) { 15221 return false; 15222 } 15223 15224 // writer 15225 synchronized (mPackages) { 15226 // Reinstate the old system package 15227 enableSystemPackageLPw(disabledPs.pkg); 15228 // Remove any native libraries from the upgraded package. 15229 removeNativeBinariesLI(deletedPs); 15230 } 15231 15232 // Install the system package 15233 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 15234 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 15235 if (locationIsPrivileged(disabledPs.codePath)) { 15236 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 15237 } 15238 15239 final PackageParser.Package newPkg; 15240 try { 15241 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 15242 } catch (PackageManagerException e) { 15243 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 15244 + e.getMessage()); 15245 return false; 15246 } 15247 15248 prepareAppDataAfterInstall(newPkg); 15249 15250 // writer 15251 synchronized (mPackages) { 15252 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 15253 15254 // Propagate the permissions state as we do not want to drop on the floor 15255 // runtime permissions. The update permissions method below will take 15256 // care of removing obsolete permissions and grant install permissions. 15257 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 15258 updatePermissionsLPw(newPkg.packageName, newPkg, 15259 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 15260 15261 if (applyUserRestrictions) { 15262 if (DEBUG_REMOVE) { 15263 Slog.d(TAG, "Propagating install state across reinstall"); 15264 } 15265 for (int userId : allUserHandles) { 15266 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15267 if (DEBUG_REMOVE) { 15268 Slog.d(TAG, " user " + userId + " => " + installed); 15269 } 15270 ps.setInstalled(installed, userId); 15271 15272 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 15273 } 15274 // Regardless of writeSettings we need to ensure that this restriction 15275 // state propagation is persisted 15276 mSettings.writeAllUsersPackageRestrictionsLPr(); 15277 } 15278 // can downgrade to reader here 15279 if (writeSettings) { 15280 mSettings.writeLPr(); 15281 } 15282 } 15283 return true; 15284 } 15285 15286 private boolean deleteInstalledPackageLI(PackageSetting ps, 15287 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 15288 PackageRemovedInfo outInfo, boolean writeSettings, 15289 PackageParser.Package replacingPackage) { 15290 synchronized (mPackages) { 15291 if (outInfo != null) { 15292 outInfo.uid = ps.appId; 15293 } 15294 15295 if (outInfo != null && outInfo.removedChildPackages != null) { 15296 final int childCount = (ps.childPackageNames != null) 15297 ? ps.childPackageNames.size() : 0; 15298 for (int i = 0; i < childCount; i++) { 15299 String childPackageName = ps.childPackageNames.get(i); 15300 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 15301 if (childPs == null) { 15302 return false; 15303 } 15304 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15305 childPackageName); 15306 if (childInfo != null) { 15307 childInfo.uid = childPs.appId; 15308 } 15309 } 15310 } 15311 } 15312 15313 // Delete package data from internal structures and also remove data if flag is set 15314 removePackageDataLI(ps, allUserHandles, outInfo, flags, writeSettings); 15315 15316 // Delete the child packages data 15317 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 15318 for (int i = 0; i < childCount; i++) { 15319 PackageSetting childPs; 15320 synchronized (mPackages) { 15321 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 15322 } 15323 if (childPs != null) { 15324 PackageRemovedInfo childOutInfo = (outInfo != null 15325 && outInfo.removedChildPackages != null) 15326 ? outInfo.removedChildPackages.get(childPs.name) : null; 15327 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 15328 && (replacingPackage != null 15329 && !replacingPackage.hasChildPackage(childPs.name)) 15330 ? flags & ~DELETE_KEEP_DATA : flags; 15331 removePackageDataLI(childPs, allUserHandles, childOutInfo, 15332 deleteFlags, writeSettings); 15333 } 15334 } 15335 15336 // Delete application code and resources only for parent packages 15337 if (ps.parentPackageName == null) { 15338 if (deleteCodeAndResources && (outInfo != null)) { 15339 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 15340 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 15341 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 15342 } 15343 } 15344 15345 return true; 15346 } 15347 15348 @Override 15349 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 15350 int userId) { 15351 mContext.enforceCallingOrSelfPermission( 15352 android.Manifest.permission.DELETE_PACKAGES, null); 15353 synchronized (mPackages) { 15354 PackageSetting ps = mSettings.mPackages.get(packageName); 15355 if (ps == null) { 15356 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 15357 return false; 15358 } 15359 if (!ps.getInstalled(userId)) { 15360 // Can't block uninstall for an app that is not installed or enabled. 15361 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 15362 return false; 15363 } 15364 ps.setBlockUninstall(blockUninstall, userId); 15365 mSettings.writePackageRestrictionsLPr(userId); 15366 } 15367 return true; 15368 } 15369 15370 @Override 15371 public boolean getBlockUninstallForUser(String packageName, int userId) { 15372 synchronized (mPackages) { 15373 PackageSetting ps = mSettings.mPackages.get(packageName); 15374 if (ps == null) { 15375 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 15376 return false; 15377 } 15378 return ps.getBlockUninstall(userId); 15379 } 15380 } 15381 15382 @Override 15383 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 15384 int callingUid = Binder.getCallingUid(); 15385 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 15386 throw new SecurityException( 15387 "setRequiredForSystemUser can only be run by the system or root"); 15388 } 15389 synchronized (mPackages) { 15390 PackageSetting ps = mSettings.mPackages.get(packageName); 15391 if (ps == null) { 15392 Log.w(TAG, "Package doesn't exist: " + packageName); 15393 return false; 15394 } 15395 if (systemUserApp) { 15396 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15397 } else { 15398 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15399 } 15400 mSettings.writeLPr(); 15401 } 15402 return true; 15403 } 15404 15405 /* 15406 * This method handles package deletion in general 15407 */ 15408 private boolean deletePackageLI(String packageName, UserHandle user, 15409 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 15410 PackageRemovedInfo outInfo, boolean writeSettings, 15411 PackageParser.Package replacingPackage) { 15412 if (packageName == null) { 15413 Slog.w(TAG, "Attempt to delete null packageName."); 15414 return false; 15415 } 15416 15417 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 15418 15419 PackageSetting ps; 15420 15421 synchronized (mPackages) { 15422 ps = mSettings.mPackages.get(packageName); 15423 if (ps == null) { 15424 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 15425 return false; 15426 } 15427 15428 if (ps.parentPackageName != null && (!isSystemApp(ps) 15429 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 15430 if (DEBUG_REMOVE) { 15431 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 15432 + ((user == null) ? UserHandle.USER_ALL : user)); 15433 } 15434 final int removedUserId = (user != null) ? user.getIdentifier() 15435 : UserHandle.USER_ALL; 15436 if (!clearPackageStateForUser(ps, removedUserId, outInfo)) { 15437 return false; 15438 } 15439 markPackageUninstalledForUserLPw(ps, user); 15440 scheduleWritePackageRestrictionsLocked(user); 15441 return true; 15442 } 15443 } 15444 15445 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 15446 && user.getIdentifier() != UserHandle.USER_ALL)) { 15447 // The caller is asking that the package only be deleted for a single 15448 // user. To do this, we just mark its uninstalled state and delete 15449 // its data. If this is a system app, we only allow this to happen if 15450 // they have set the special DELETE_SYSTEM_APP which requests different 15451 // semantics than normal for uninstalling system apps. 15452 markPackageUninstalledForUserLPw(ps, user); 15453 15454 if (!isSystemApp(ps)) { 15455 // Do not uninstall the APK if an app should be cached 15456 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 15457 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 15458 // Other user still have this package installed, so all 15459 // we need to do is clear this user's data and save that 15460 // it is uninstalled. 15461 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 15462 if (!clearPackageStateForUser(ps, user.getIdentifier(), outInfo)) { 15463 return false; 15464 } 15465 scheduleWritePackageRestrictionsLocked(user); 15466 return true; 15467 } else { 15468 // We need to set it back to 'installed' so the uninstall 15469 // broadcasts will be sent correctly. 15470 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 15471 ps.setInstalled(true, user.getIdentifier()); 15472 } 15473 } else { 15474 // This is a system app, so we assume that the 15475 // other users still have this package installed, so all 15476 // we need to do is clear this user's data and save that 15477 // it is uninstalled. 15478 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 15479 if (!clearPackageStateForUser(ps, user.getIdentifier(), outInfo)) { 15480 return false; 15481 } 15482 scheduleWritePackageRestrictionsLocked(user); 15483 return true; 15484 } 15485 } 15486 15487 // If we are deleting a composite package for all users, keep track 15488 // of result for each child. 15489 if (ps.childPackageNames != null && outInfo != null) { 15490 synchronized (mPackages) { 15491 final int childCount = ps.childPackageNames.size(); 15492 outInfo.removedChildPackages = new ArrayMap<>(childCount); 15493 for (int i = 0; i < childCount; i++) { 15494 String childPackageName = ps.childPackageNames.get(i); 15495 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 15496 childInfo.removedPackage = childPackageName; 15497 outInfo.removedChildPackages.put(childPackageName, childInfo); 15498 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 15499 if (childPs != null) { 15500 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 15501 } 15502 } 15503 } 15504 } 15505 15506 boolean ret = false; 15507 if (isSystemApp(ps)) { 15508 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 15509 // When an updated system application is deleted we delete the existing resources 15510 // as well and fall back to existing code in system partition 15511 ret = deleteSystemPackageLI(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 15512 } else { 15513 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 15514 // Kill application pre-emptively especially for apps on sd. 15515 final boolean killApp = (flags & PackageManager.DELETE_DONT_KILL_APP) == 0; 15516 if (killApp) { 15517 killApplication(packageName, ps.appId, "uninstall pkg"); 15518 } 15519 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, allUserHandles, 15520 outInfo, writeSettings, replacingPackage); 15521 } 15522 15523 // Take a note whether we deleted the package for all users 15524 if (outInfo != null) { 15525 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 15526 if (outInfo.removedChildPackages != null) { 15527 synchronized (mPackages) { 15528 final int childCount = outInfo.removedChildPackages.size(); 15529 for (int i = 0; i < childCount; i++) { 15530 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 15531 if (childInfo != null) { 15532 childInfo.removedForAllUsers = mPackages.get( 15533 childInfo.removedPackage) == null; 15534 } 15535 } 15536 } 15537 } 15538 // If we uninstalled an update to a system app there may be some 15539 // child packages that appeared as they are declared in the system 15540 // app but were not declared in the update. 15541 if (isSystemApp(ps)) { 15542 synchronized (mPackages) { 15543 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 15544 final int childCount = (updatedPs.childPackageNames != null) 15545 ? updatedPs.childPackageNames.size() : 0; 15546 for (int i = 0; i < childCount; i++) { 15547 String childPackageName = updatedPs.childPackageNames.get(i); 15548 if (outInfo.removedChildPackages == null 15549 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 15550 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 15551 if (childPs == null) { 15552 continue; 15553 } 15554 PackageInstalledInfo installRes = new PackageInstalledInfo(); 15555 installRes.name = childPackageName; 15556 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 15557 installRes.pkg = mPackages.get(childPackageName); 15558 installRes.uid = childPs.pkg.applicationInfo.uid; 15559 if (outInfo.appearedChildPackages == null) { 15560 outInfo.appearedChildPackages = new ArrayMap<>(); 15561 } 15562 outInfo.appearedChildPackages.put(childPackageName, installRes); 15563 } 15564 } 15565 } 15566 } 15567 } 15568 15569 return ret; 15570 } 15571 15572 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 15573 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 15574 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 15575 for (int nextUserId : userIds) { 15576 if (DEBUG_REMOVE) { 15577 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 15578 } 15579 ps.setUserState(nextUserId, COMPONENT_ENABLED_STATE_DEFAULT, 15580 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 15581 false /*hidden*/, false /*suspended*/, null, null, null, 15582 false /*blockUninstall*/, 15583 ps.readUserState(nextUserId).domainVerificationStatus, 0); 15584 } 15585 } 15586 15587 private boolean clearPackageStateForUser(PackageSetting ps, int userId, 15588 PackageRemovedInfo outInfo) { 15589 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 15590 : new int[] {userId}; 15591 for (int nextUserId : userIds) { 15592 if (DEBUG_REMOVE) { 15593 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 15594 + nextUserId); 15595 } 15596 final int flags = StorageManager.FLAG_STORAGE_CE| StorageManager.FLAG_STORAGE_DE; 15597 try { 15598 mInstaller.destroyAppData(ps.volumeUuid, ps.name, nextUserId, flags); 15599 } catch (InstallerException e) { 15600 Slog.w(TAG, "Couldn't remove cache files for package " + ps.name, e); 15601 return false; 15602 } 15603 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 15604 schedulePackageCleaning(ps.name, nextUserId, false); 15605 synchronized (mPackages) { 15606 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 15607 scheduleWritePackageRestrictionsLocked(nextUserId); 15608 } 15609 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 15610 } 15611 } 15612 15613 if (outInfo != null) { 15614 outInfo.removedPackage = ps.name; 15615 outInfo.removedAppId = ps.appId; 15616 outInfo.removedUsers = userIds; 15617 } 15618 15619 return true; 15620 } 15621 15622 private final class ClearStorageConnection implements ServiceConnection { 15623 IMediaContainerService mContainerService; 15624 15625 @Override 15626 public void onServiceConnected(ComponentName name, IBinder service) { 15627 synchronized (this) { 15628 mContainerService = IMediaContainerService.Stub.asInterface(service); 15629 notifyAll(); 15630 } 15631 } 15632 15633 @Override 15634 public void onServiceDisconnected(ComponentName name) { 15635 } 15636 } 15637 15638 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 15639 final boolean mounted; 15640 if (Environment.isExternalStorageEmulated()) { 15641 mounted = true; 15642 } else { 15643 final String status = Environment.getExternalStorageState(); 15644 15645 mounted = status.equals(Environment.MEDIA_MOUNTED) 15646 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 15647 } 15648 15649 if (!mounted) { 15650 return; 15651 } 15652 15653 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 15654 int[] users; 15655 if (userId == UserHandle.USER_ALL) { 15656 users = sUserManager.getUserIds(); 15657 } else { 15658 users = new int[] { userId }; 15659 } 15660 final ClearStorageConnection conn = new ClearStorageConnection(); 15661 if (mContext.bindServiceAsUser( 15662 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 15663 try { 15664 for (int curUser : users) { 15665 long timeout = SystemClock.uptimeMillis() + 5000; 15666 synchronized (conn) { 15667 long now = SystemClock.uptimeMillis(); 15668 while (conn.mContainerService == null && now < timeout) { 15669 try { 15670 conn.wait(timeout - now); 15671 } catch (InterruptedException e) { 15672 } 15673 } 15674 } 15675 if (conn.mContainerService == null) { 15676 return; 15677 } 15678 15679 final UserEnvironment userEnv = new UserEnvironment(curUser); 15680 clearDirectory(conn.mContainerService, 15681 userEnv.buildExternalStorageAppCacheDirs(packageName)); 15682 if (allData) { 15683 clearDirectory(conn.mContainerService, 15684 userEnv.buildExternalStorageAppDataDirs(packageName)); 15685 clearDirectory(conn.mContainerService, 15686 userEnv.buildExternalStorageAppMediaDirs(packageName)); 15687 } 15688 } 15689 } finally { 15690 mContext.unbindService(conn); 15691 } 15692 } 15693 } 15694 15695 @Override 15696 public void clearApplicationProfileData(String packageName) { 15697 enforceSystemOrRoot("Only the system can clear all profile data"); 15698 try { 15699 mInstaller.clearAppProfiles(packageName); 15700 } catch (InstallerException ex) { 15701 Log.e(TAG, "Could not clear profile data of package " + packageName); 15702 } 15703 } 15704 15705 @Override 15706 public void clearApplicationUserData(final String packageName, 15707 final IPackageDataObserver observer, final int userId) { 15708 mContext.enforceCallingOrSelfPermission( 15709 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 15710 15711 enforceCrossUserPermission(Binder.getCallingUid(), userId, 15712 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 15713 15714 final DevicePolicyManagerInternal dpmi = LocalServices 15715 .getService(DevicePolicyManagerInternal.class); 15716 if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) { 15717 throw new SecurityException("Cannot clear data for a device owner or a profile owner"); 15718 } 15719 // Queue up an async operation since the package deletion may take a little while. 15720 mHandler.post(new Runnable() { 15721 public void run() { 15722 mHandler.removeCallbacks(this); 15723 final boolean succeeded; 15724 synchronized (mInstallLock) { 15725 succeeded = clearApplicationUserDataLI(packageName, userId); 15726 } 15727 clearExternalStorageDataSync(packageName, userId, true); 15728 if (succeeded) { 15729 // invoke DeviceStorageMonitor's update method to clear any notifications 15730 DeviceStorageMonitorInternal dsm = LocalServices 15731 .getService(DeviceStorageMonitorInternal.class); 15732 if (dsm != null) { 15733 dsm.checkMemory(); 15734 } 15735 } 15736 if(observer != null) { 15737 try { 15738 observer.onRemoveCompleted(packageName, succeeded); 15739 } catch (RemoteException e) { 15740 Log.i(TAG, "Observer no longer exists."); 15741 } 15742 } //end if observer 15743 } //end run 15744 }); 15745 } 15746 15747 private boolean clearApplicationUserDataLI(String packageName, int userId) { 15748 if (packageName == null) { 15749 Slog.w(TAG, "Attempt to delete null packageName."); 15750 return false; 15751 } 15752 15753 // Try finding details about the requested package 15754 PackageParser.Package pkg; 15755 synchronized (mPackages) { 15756 pkg = mPackages.get(packageName); 15757 if (pkg == null) { 15758 final PackageSetting ps = mSettings.mPackages.get(packageName); 15759 if (ps != null) { 15760 pkg = ps.pkg; 15761 } 15762 } 15763 15764 if (pkg == null) { 15765 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 15766 return false; 15767 } 15768 15769 PackageSetting ps = (PackageSetting) pkg.mExtras; 15770 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 15771 } 15772 15773 // Always delete data directories for package, even if we found no other 15774 // record of app. This helps users recover from UID mismatches without 15775 // resorting to a full data wipe. 15776 // TODO: triage flags as part of 26466827 15777 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 15778 try { 15779 mInstaller.clearAppData(pkg.volumeUuid, packageName, userId, flags); 15780 } catch (InstallerException e) { 15781 Slog.w(TAG, "Couldn't remove cache files for package " + packageName, e); 15782 return false; 15783 } 15784 15785 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 15786 removeKeystoreDataIfNeeded(userId, appId); 15787 15788 // Create a native library symlink only if we have native libraries 15789 // and if the native libraries are 32 bit libraries. We do not provide 15790 // this symlink for 64 bit libraries. 15791 if (pkg.applicationInfo.primaryCpuAbi != null && 15792 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 15793 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 15794 try { 15795 mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 15796 nativeLibPath, userId); 15797 } catch (InstallerException e) { 15798 Slog.w(TAG, "Failed linking native library dir", e); 15799 return false; 15800 } 15801 } 15802 15803 return true; 15804 } 15805 15806 /** 15807 * Reverts user permission state changes (permissions and flags) in 15808 * all packages for a given user. 15809 * 15810 * @param userId The device user for which to do a reset. 15811 */ 15812 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 15813 final int packageCount = mPackages.size(); 15814 for (int i = 0; i < packageCount; i++) { 15815 PackageParser.Package pkg = mPackages.valueAt(i); 15816 PackageSetting ps = (PackageSetting) pkg.mExtras; 15817 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 15818 } 15819 } 15820 15821 /** 15822 * Reverts user permission state changes (permissions and flags). 15823 * 15824 * @param ps The package for which to reset. 15825 * @param userId The device user for which to do a reset. 15826 */ 15827 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 15828 final PackageSetting ps, final int userId) { 15829 if (ps.pkg == null) { 15830 return; 15831 } 15832 15833 // These are flags that can change base on user actions. 15834 final int userSettableMask = FLAG_PERMISSION_USER_SET 15835 | FLAG_PERMISSION_USER_FIXED 15836 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 15837 | FLAG_PERMISSION_REVIEW_REQUIRED; 15838 15839 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 15840 | FLAG_PERMISSION_POLICY_FIXED; 15841 15842 boolean writeInstallPermissions = false; 15843 boolean writeRuntimePermissions = false; 15844 15845 final int permissionCount = ps.pkg.requestedPermissions.size(); 15846 for (int i = 0; i < permissionCount; i++) { 15847 String permission = ps.pkg.requestedPermissions.get(i); 15848 15849 BasePermission bp = mSettings.mPermissions.get(permission); 15850 if (bp == null) { 15851 continue; 15852 } 15853 15854 // If shared user we just reset the state to which only this app contributed. 15855 if (ps.sharedUser != null) { 15856 boolean used = false; 15857 final int packageCount = ps.sharedUser.packages.size(); 15858 for (int j = 0; j < packageCount; j++) { 15859 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 15860 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 15861 && pkg.pkg.requestedPermissions.contains(permission)) { 15862 used = true; 15863 break; 15864 } 15865 } 15866 if (used) { 15867 continue; 15868 } 15869 } 15870 15871 PermissionsState permissionsState = ps.getPermissionsState(); 15872 15873 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 15874 15875 // Always clear the user settable flags. 15876 final boolean hasInstallState = permissionsState.getInstallPermissionState( 15877 bp.name) != null; 15878 // If permission review is enabled and this is a legacy app, mark the 15879 // permission as requiring a review as this is the initial state. 15880 int flags = 0; 15881 if (Build.PERMISSIONS_REVIEW_REQUIRED 15882 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 15883 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 15884 } 15885 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 15886 if (hasInstallState) { 15887 writeInstallPermissions = true; 15888 } else { 15889 writeRuntimePermissions = true; 15890 } 15891 } 15892 15893 // Below is only runtime permission handling. 15894 if (!bp.isRuntime()) { 15895 continue; 15896 } 15897 15898 // Never clobber system or policy. 15899 if ((oldFlags & policyOrSystemFlags) != 0) { 15900 continue; 15901 } 15902 15903 // If this permission was granted by default, make sure it is. 15904 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 15905 if (permissionsState.grantRuntimePermission(bp, userId) 15906 != PERMISSION_OPERATION_FAILURE) { 15907 writeRuntimePermissions = true; 15908 } 15909 // If permission review is enabled the permissions for a legacy apps 15910 // are represented as constantly granted runtime ones, so don't revoke. 15911 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 15912 // Otherwise, reset the permission. 15913 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 15914 switch (revokeResult) { 15915 case PERMISSION_OPERATION_SUCCESS: 15916 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 15917 writeRuntimePermissions = true; 15918 final int appId = ps.appId; 15919 mHandler.post(new Runnable() { 15920 @Override 15921 public void run() { 15922 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 15923 } 15924 }); 15925 } break; 15926 } 15927 } 15928 } 15929 15930 // Synchronously write as we are taking permissions away. 15931 if (writeRuntimePermissions) { 15932 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 15933 } 15934 15935 // Synchronously write as we are taking permissions away. 15936 if (writeInstallPermissions) { 15937 mSettings.writeLPr(); 15938 } 15939 } 15940 15941 /** 15942 * Remove entries from the keystore daemon. Will only remove it if the 15943 * {@code appId} is valid. 15944 */ 15945 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 15946 if (appId < 0) { 15947 return; 15948 } 15949 15950 final KeyStore keyStore = KeyStore.getInstance(); 15951 if (keyStore != null) { 15952 if (userId == UserHandle.USER_ALL) { 15953 for (final int individual : sUserManager.getUserIds()) { 15954 keyStore.clearUid(UserHandle.getUid(individual, appId)); 15955 } 15956 } else { 15957 keyStore.clearUid(UserHandle.getUid(userId, appId)); 15958 } 15959 } else { 15960 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 15961 } 15962 } 15963 15964 @Override 15965 public void deleteApplicationCacheFiles(final String packageName, 15966 final IPackageDataObserver observer) { 15967 mContext.enforceCallingOrSelfPermission( 15968 android.Manifest.permission.DELETE_CACHE_FILES, null); 15969 // Queue up an async operation since the package deletion may take a little while. 15970 final int userId = UserHandle.getCallingUserId(); 15971 mHandler.post(new Runnable() { 15972 public void run() { 15973 mHandler.removeCallbacks(this); 15974 final boolean succeded; 15975 synchronized (mInstallLock) { 15976 succeded = deleteApplicationCacheFilesLI(packageName, userId); 15977 } 15978 clearExternalStorageDataSync(packageName, userId, false); 15979 if (observer != null) { 15980 try { 15981 observer.onRemoveCompleted(packageName, succeded); 15982 } catch (RemoteException e) { 15983 Log.i(TAG, "Observer no longer exists."); 15984 } 15985 } //end if observer 15986 } //end run 15987 }); 15988 } 15989 15990 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 15991 if (packageName == null) { 15992 Slog.w(TAG, "Attempt to delete null packageName."); 15993 return false; 15994 } 15995 PackageParser.Package p; 15996 synchronized (mPackages) { 15997 p = mPackages.get(packageName); 15998 } 15999 if (p == null) { 16000 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 16001 return false; 16002 } 16003 final ApplicationInfo applicationInfo = p.applicationInfo; 16004 if (applicationInfo == null) { 16005 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 16006 return false; 16007 } 16008 // TODO: triage flags as part of 26466827 16009 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 16010 try { 16011 mInstaller.clearAppData(p.volumeUuid, packageName, userId, 16012 flags | Installer.FLAG_CLEAR_CACHE_ONLY); 16013 } catch (InstallerException e) { 16014 Slog.w(TAG, "Couldn't remove cache files for package " 16015 + packageName + " u" + userId, e); 16016 return false; 16017 } 16018 return true; 16019 } 16020 16021 @Override 16022 public void getPackageSizeInfo(final String packageName, int userHandle, 16023 final IPackageStatsObserver observer) { 16024 mContext.enforceCallingOrSelfPermission( 16025 android.Manifest.permission.GET_PACKAGE_SIZE, null); 16026 if (packageName == null) { 16027 throw new IllegalArgumentException("Attempt to get size of null packageName"); 16028 } 16029 16030 PackageStats stats = new PackageStats(packageName, userHandle); 16031 16032 /* 16033 * Queue up an async operation since the package measurement may take a 16034 * little while. 16035 */ 16036 Message msg = mHandler.obtainMessage(INIT_COPY); 16037 msg.obj = new MeasureParams(stats, observer); 16038 mHandler.sendMessage(msg); 16039 } 16040 16041 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 16042 PackageStats pStats) { 16043 if (packageName == null) { 16044 Slog.w(TAG, "Attempt to get size of null packageName."); 16045 return false; 16046 } 16047 PackageParser.Package p; 16048 boolean dataOnly = false; 16049 String libDirRoot = null; 16050 String asecPath = null; 16051 PackageSetting ps = null; 16052 synchronized (mPackages) { 16053 p = mPackages.get(packageName); 16054 ps = mSettings.mPackages.get(packageName); 16055 if(p == null) { 16056 dataOnly = true; 16057 if((ps == null) || (ps.pkg == null)) { 16058 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 16059 return false; 16060 } 16061 p = ps.pkg; 16062 } 16063 if (ps != null) { 16064 libDirRoot = ps.legacyNativeLibraryPathString; 16065 } 16066 if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) { 16067 final long token = Binder.clearCallingIdentity(); 16068 try { 16069 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 16070 if (secureContainerId != null) { 16071 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 16072 } 16073 } finally { 16074 Binder.restoreCallingIdentity(token); 16075 } 16076 } 16077 } 16078 String publicSrcDir = null; 16079 if(!dataOnly) { 16080 final ApplicationInfo applicationInfo = p.applicationInfo; 16081 if (applicationInfo == null) { 16082 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 16083 return false; 16084 } 16085 if (p.isForwardLocked()) { 16086 publicSrcDir = applicationInfo.getBaseResourcePath(); 16087 } 16088 } 16089 // TODO: extend to measure size of split APKs 16090 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 16091 // not just the first level. 16092 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 16093 // just the primary. 16094 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 16095 16096 String apkPath; 16097 File packageDir = new File(p.codePath); 16098 16099 if (packageDir.isDirectory() && p.canHaveOatDir()) { 16100 apkPath = packageDir.getAbsolutePath(); 16101 // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice 16102 if (libDirRoot != null && libDirRoot.startsWith(apkPath)) { 16103 libDirRoot = null; 16104 } 16105 } else { 16106 apkPath = p.baseCodePath; 16107 } 16108 16109 // TODO: triage flags as part of 26466827 16110 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 16111 try { 16112 mInstaller.getAppSize(p.volumeUuid, packageName, userHandle, flags, apkPath, 16113 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 16114 } catch (InstallerException e) { 16115 return false; 16116 } 16117 16118 // Fix-up for forward-locked applications in ASEC containers. 16119 if (!isExternal(p)) { 16120 pStats.codeSize += pStats.externalCodeSize; 16121 pStats.externalCodeSize = 0L; 16122 } 16123 16124 return true; 16125 } 16126 16127 private int getUidTargetSdkVersionLockedLPr(int uid) { 16128 Object obj = mSettings.getUserIdLPr(uid); 16129 if (obj instanceof SharedUserSetting) { 16130 final SharedUserSetting sus = (SharedUserSetting) obj; 16131 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 16132 final Iterator<PackageSetting> it = sus.packages.iterator(); 16133 while (it.hasNext()) { 16134 final PackageSetting ps = it.next(); 16135 if (ps.pkg != null) { 16136 int v = ps.pkg.applicationInfo.targetSdkVersion; 16137 if (v < vers) vers = v; 16138 } 16139 } 16140 return vers; 16141 } else if (obj instanceof PackageSetting) { 16142 final PackageSetting ps = (PackageSetting) obj; 16143 if (ps.pkg != null) { 16144 return ps.pkg.applicationInfo.targetSdkVersion; 16145 } 16146 } 16147 return Build.VERSION_CODES.CUR_DEVELOPMENT; 16148 } 16149 16150 @Override 16151 public void addPreferredActivity(IntentFilter filter, int match, 16152 ComponentName[] set, ComponentName activity, int userId) { 16153 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16154 "Adding preferred"); 16155 } 16156 16157 private void addPreferredActivityInternal(IntentFilter filter, int match, 16158 ComponentName[] set, ComponentName activity, boolean always, int userId, 16159 String opname) { 16160 // writer 16161 int callingUid = Binder.getCallingUid(); 16162 enforceCrossUserPermission(callingUid, userId, 16163 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 16164 if (filter.countActions() == 0) { 16165 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16166 return; 16167 } 16168 synchronized (mPackages) { 16169 if (mContext.checkCallingOrSelfPermission( 16170 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16171 != PackageManager.PERMISSION_GRANTED) { 16172 if (getUidTargetSdkVersionLockedLPr(callingUid) 16173 < Build.VERSION_CODES.FROYO) { 16174 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 16175 + callingUid); 16176 return; 16177 } 16178 mContext.enforceCallingOrSelfPermission( 16179 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16180 } 16181 16182 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 16183 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 16184 + userId + ":"); 16185 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16186 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 16187 scheduleWritePackageRestrictionsLocked(userId); 16188 } 16189 } 16190 16191 @Override 16192 public void replacePreferredActivity(IntentFilter filter, int match, 16193 ComponentName[] set, ComponentName activity, int userId) { 16194 if (filter.countActions() != 1) { 16195 throw new IllegalArgumentException( 16196 "replacePreferredActivity expects filter to have only 1 action."); 16197 } 16198 if (filter.countDataAuthorities() != 0 16199 || filter.countDataPaths() != 0 16200 || filter.countDataSchemes() > 1 16201 || filter.countDataTypes() != 0) { 16202 throw new IllegalArgumentException( 16203 "replacePreferredActivity expects filter to have no data authorities, " + 16204 "paths, or types; and at most one scheme."); 16205 } 16206 16207 final int callingUid = Binder.getCallingUid(); 16208 enforceCrossUserPermission(callingUid, userId, 16209 true /* requireFullPermission */, false /* checkShell */, 16210 "replace preferred activity"); 16211 synchronized (mPackages) { 16212 if (mContext.checkCallingOrSelfPermission( 16213 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16214 != PackageManager.PERMISSION_GRANTED) { 16215 if (getUidTargetSdkVersionLockedLPr(callingUid) 16216 < Build.VERSION_CODES.FROYO) { 16217 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 16218 + Binder.getCallingUid()); 16219 return; 16220 } 16221 mContext.enforceCallingOrSelfPermission( 16222 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16223 } 16224 16225 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16226 if (pir != null) { 16227 // Get all of the existing entries that exactly match this filter. 16228 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 16229 if (existing != null && existing.size() == 1) { 16230 PreferredActivity cur = existing.get(0); 16231 if (DEBUG_PREFERRED) { 16232 Slog.i(TAG, "Checking replace of preferred:"); 16233 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16234 if (!cur.mPref.mAlways) { 16235 Slog.i(TAG, " -- CUR; not mAlways!"); 16236 } else { 16237 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 16238 Slog.i(TAG, " -- CUR: mSet=" 16239 + Arrays.toString(cur.mPref.mSetComponents)); 16240 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 16241 Slog.i(TAG, " -- NEW: mMatch=" 16242 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 16243 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 16244 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 16245 } 16246 } 16247 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 16248 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 16249 && cur.mPref.sameSet(set)) { 16250 // Setting the preferred activity to what it happens to be already 16251 if (DEBUG_PREFERRED) { 16252 Slog.i(TAG, "Replacing with same preferred activity " 16253 + cur.mPref.mShortComponent + " for user " 16254 + userId + ":"); 16255 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16256 } 16257 return; 16258 } 16259 } 16260 16261 if (existing != null) { 16262 if (DEBUG_PREFERRED) { 16263 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 16264 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16265 } 16266 for (int i = 0; i < existing.size(); i++) { 16267 PreferredActivity pa = existing.get(i); 16268 if (DEBUG_PREFERRED) { 16269 Slog.i(TAG, "Removing existing preferred activity " 16270 + pa.mPref.mComponent + ":"); 16271 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 16272 } 16273 pir.removeFilter(pa); 16274 } 16275 } 16276 } 16277 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16278 "Replacing preferred"); 16279 } 16280 } 16281 16282 @Override 16283 public void clearPackagePreferredActivities(String packageName) { 16284 final int uid = Binder.getCallingUid(); 16285 // writer 16286 synchronized (mPackages) { 16287 PackageParser.Package pkg = mPackages.get(packageName); 16288 if (pkg == null || pkg.applicationInfo.uid != uid) { 16289 if (mContext.checkCallingOrSelfPermission( 16290 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16291 != PackageManager.PERMISSION_GRANTED) { 16292 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 16293 < Build.VERSION_CODES.FROYO) { 16294 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 16295 + Binder.getCallingUid()); 16296 return; 16297 } 16298 mContext.enforceCallingOrSelfPermission( 16299 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16300 } 16301 } 16302 16303 int user = UserHandle.getCallingUserId(); 16304 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 16305 scheduleWritePackageRestrictionsLocked(user); 16306 } 16307 } 16308 } 16309 16310 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16311 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 16312 ArrayList<PreferredActivity> removed = null; 16313 boolean changed = false; 16314 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16315 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 16316 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16317 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 16318 continue; 16319 } 16320 Iterator<PreferredActivity> it = pir.filterIterator(); 16321 while (it.hasNext()) { 16322 PreferredActivity pa = it.next(); 16323 // Mark entry for removal only if it matches the package name 16324 // and the entry is of type "always". 16325 if (packageName == null || 16326 (pa.mPref.mComponent.getPackageName().equals(packageName) 16327 && pa.mPref.mAlways)) { 16328 if (removed == null) { 16329 removed = new ArrayList<PreferredActivity>(); 16330 } 16331 removed.add(pa); 16332 } 16333 } 16334 if (removed != null) { 16335 for (int j=0; j<removed.size(); j++) { 16336 PreferredActivity pa = removed.get(j); 16337 pir.removeFilter(pa); 16338 } 16339 changed = true; 16340 } 16341 } 16342 return changed; 16343 } 16344 16345 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16346 private void clearIntentFilterVerificationsLPw(int userId) { 16347 final int packageCount = mPackages.size(); 16348 for (int i = 0; i < packageCount; i++) { 16349 PackageParser.Package pkg = mPackages.valueAt(i); 16350 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 16351 } 16352 } 16353 16354 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16355 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 16356 if (userId == UserHandle.USER_ALL) { 16357 if (mSettings.removeIntentFilterVerificationLPw(packageName, 16358 sUserManager.getUserIds())) { 16359 for (int oneUserId : sUserManager.getUserIds()) { 16360 scheduleWritePackageRestrictionsLocked(oneUserId); 16361 } 16362 } 16363 } else { 16364 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 16365 scheduleWritePackageRestrictionsLocked(userId); 16366 } 16367 } 16368 } 16369 16370 void clearDefaultBrowserIfNeeded(String packageName) { 16371 for (int oneUserId : sUserManager.getUserIds()) { 16372 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 16373 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 16374 if (packageName.equals(defaultBrowserPackageName)) { 16375 setDefaultBrowserPackageName(null, oneUserId); 16376 } 16377 } 16378 } 16379 16380 @Override 16381 public void resetApplicationPreferences(int userId) { 16382 mContext.enforceCallingOrSelfPermission( 16383 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16384 // writer 16385 synchronized (mPackages) { 16386 final long identity = Binder.clearCallingIdentity(); 16387 try { 16388 clearPackagePreferredActivitiesLPw(null, userId); 16389 mSettings.applyDefaultPreferredAppsLPw(this, userId); 16390 // TODO: We have to reset the default SMS and Phone. This requires 16391 // significant refactoring to keep all default apps in the package 16392 // manager (cleaner but more work) or have the services provide 16393 // callbacks to the package manager to request a default app reset. 16394 applyFactoryDefaultBrowserLPw(userId); 16395 clearIntentFilterVerificationsLPw(userId); 16396 primeDomainVerificationsLPw(userId); 16397 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 16398 scheduleWritePackageRestrictionsLocked(userId); 16399 } finally { 16400 Binder.restoreCallingIdentity(identity); 16401 } 16402 } 16403 } 16404 16405 @Override 16406 public int getPreferredActivities(List<IntentFilter> outFilters, 16407 List<ComponentName> outActivities, String packageName) { 16408 16409 int num = 0; 16410 final int userId = UserHandle.getCallingUserId(); 16411 // reader 16412 synchronized (mPackages) { 16413 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16414 if (pir != null) { 16415 final Iterator<PreferredActivity> it = pir.filterIterator(); 16416 while (it.hasNext()) { 16417 final PreferredActivity pa = it.next(); 16418 if (packageName == null 16419 || (pa.mPref.mComponent.getPackageName().equals(packageName) 16420 && pa.mPref.mAlways)) { 16421 if (outFilters != null) { 16422 outFilters.add(new IntentFilter(pa)); 16423 } 16424 if (outActivities != null) { 16425 outActivities.add(pa.mPref.mComponent); 16426 } 16427 } 16428 } 16429 } 16430 } 16431 16432 return num; 16433 } 16434 16435 @Override 16436 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 16437 int userId) { 16438 int callingUid = Binder.getCallingUid(); 16439 if (callingUid != Process.SYSTEM_UID) { 16440 throw new SecurityException( 16441 "addPersistentPreferredActivity can only be run by the system"); 16442 } 16443 if (filter.countActions() == 0) { 16444 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16445 return; 16446 } 16447 synchronized (mPackages) { 16448 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 16449 ":"); 16450 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16451 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 16452 new PersistentPreferredActivity(filter, activity)); 16453 scheduleWritePackageRestrictionsLocked(userId); 16454 } 16455 } 16456 16457 @Override 16458 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 16459 int callingUid = Binder.getCallingUid(); 16460 if (callingUid != Process.SYSTEM_UID) { 16461 throw new SecurityException( 16462 "clearPackagePersistentPreferredActivities can only be run by the system"); 16463 } 16464 ArrayList<PersistentPreferredActivity> removed = null; 16465 boolean changed = false; 16466 synchronized (mPackages) { 16467 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 16468 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 16469 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 16470 .valueAt(i); 16471 if (userId != thisUserId) { 16472 continue; 16473 } 16474 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 16475 while (it.hasNext()) { 16476 PersistentPreferredActivity ppa = it.next(); 16477 // Mark entry for removal only if it matches the package name. 16478 if (ppa.mComponent.getPackageName().equals(packageName)) { 16479 if (removed == null) { 16480 removed = new ArrayList<PersistentPreferredActivity>(); 16481 } 16482 removed.add(ppa); 16483 } 16484 } 16485 if (removed != null) { 16486 for (int j=0; j<removed.size(); j++) { 16487 PersistentPreferredActivity ppa = removed.get(j); 16488 ppir.removeFilter(ppa); 16489 } 16490 changed = true; 16491 } 16492 } 16493 16494 if (changed) { 16495 scheduleWritePackageRestrictionsLocked(userId); 16496 } 16497 } 16498 } 16499 16500 /** 16501 * Common machinery for picking apart a restored XML blob and passing 16502 * it to a caller-supplied functor to be applied to the running system. 16503 */ 16504 private void restoreFromXml(XmlPullParser parser, int userId, 16505 String expectedStartTag, BlobXmlRestorer functor) 16506 throws IOException, XmlPullParserException { 16507 int type; 16508 while ((type = parser.next()) != XmlPullParser.START_TAG 16509 && type != XmlPullParser.END_DOCUMENT) { 16510 } 16511 if (type != XmlPullParser.START_TAG) { 16512 // oops didn't find a start tag?! 16513 if (DEBUG_BACKUP) { 16514 Slog.e(TAG, "Didn't find start tag during restore"); 16515 } 16516 return; 16517 } 16518Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 16519 // this is supposed to be TAG_PREFERRED_BACKUP 16520 if (!expectedStartTag.equals(parser.getName())) { 16521 if (DEBUG_BACKUP) { 16522 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 16523 } 16524 return; 16525 } 16526 16527 // skip interfering stuff, then we're aligned with the backing implementation 16528 while ((type = parser.next()) == XmlPullParser.TEXT) { } 16529Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 16530 functor.apply(parser, userId); 16531 } 16532 16533 private interface BlobXmlRestorer { 16534 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 16535 } 16536 16537 /** 16538 * Non-Binder method, support for the backup/restore mechanism: write the 16539 * full set of preferred activities in its canonical XML format. Returns the 16540 * XML output as a byte array, or null if there is none. 16541 */ 16542 @Override 16543 public byte[] getPreferredActivityBackup(int userId) { 16544 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16545 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 16546 } 16547 16548 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16549 try { 16550 final XmlSerializer serializer = new FastXmlSerializer(); 16551 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16552 serializer.startDocument(null, true); 16553 serializer.startTag(null, TAG_PREFERRED_BACKUP); 16554 16555 synchronized (mPackages) { 16556 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 16557 } 16558 16559 serializer.endTag(null, TAG_PREFERRED_BACKUP); 16560 serializer.endDocument(); 16561 serializer.flush(); 16562 } catch (Exception e) { 16563 if (DEBUG_BACKUP) { 16564 Slog.e(TAG, "Unable to write preferred activities for backup", e); 16565 } 16566 return null; 16567 } 16568 16569 return dataStream.toByteArray(); 16570 } 16571 16572 @Override 16573 public void restorePreferredActivities(byte[] backup, int userId) { 16574 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16575 throw new SecurityException("Only the system may call restorePreferredActivities()"); 16576 } 16577 16578 try { 16579 final XmlPullParser parser = Xml.newPullParser(); 16580 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16581 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 16582 new BlobXmlRestorer() { 16583 @Override 16584 public void apply(XmlPullParser parser, int userId) 16585 throws XmlPullParserException, IOException { 16586 synchronized (mPackages) { 16587 mSettings.readPreferredActivitiesLPw(parser, userId); 16588 } 16589 } 16590 } ); 16591 } catch (Exception e) { 16592 if (DEBUG_BACKUP) { 16593 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16594 } 16595 } 16596 } 16597 16598 /** 16599 * Non-Binder method, support for the backup/restore mechanism: write the 16600 * default browser (etc) settings in its canonical XML format. Returns the default 16601 * browser XML representation as a byte array, or null if there is none. 16602 */ 16603 @Override 16604 public byte[] getDefaultAppsBackup(int userId) { 16605 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16606 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 16607 } 16608 16609 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16610 try { 16611 final XmlSerializer serializer = new FastXmlSerializer(); 16612 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16613 serializer.startDocument(null, true); 16614 serializer.startTag(null, TAG_DEFAULT_APPS); 16615 16616 synchronized (mPackages) { 16617 mSettings.writeDefaultAppsLPr(serializer, userId); 16618 } 16619 16620 serializer.endTag(null, TAG_DEFAULT_APPS); 16621 serializer.endDocument(); 16622 serializer.flush(); 16623 } catch (Exception e) { 16624 if (DEBUG_BACKUP) { 16625 Slog.e(TAG, "Unable to write default apps for backup", e); 16626 } 16627 return null; 16628 } 16629 16630 return dataStream.toByteArray(); 16631 } 16632 16633 @Override 16634 public void restoreDefaultApps(byte[] backup, int userId) { 16635 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16636 throw new SecurityException("Only the system may call restoreDefaultApps()"); 16637 } 16638 16639 try { 16640 final XmlPullParser parser = Xml.newPullParser(); 16641 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16642 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 16643 new BlobXmlRestorer() { 16644 @Override 16645 public void apply(XmlPullParser parser, int userId) 16646 throws XmlPullParserException, IOException { 16647 synchronized (mPackages) { 16648 mSettings.readDefaultAppsLPw(parser, userId); 16649 } 16650 } 16651 } ); 16652 } catch (Exception e) { 16653 if (DEBUG_BACKUP) { 16654 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 16655 } 16656 } 16657 } 16658 16659 @Override 16660 public byte[] getIntentFilterVerificationBackup(int userId) { 16661 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16662 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 16663 } 16664 16665 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16666 try { 16667 final XmlSerializer serializer = new FastXmlSerializer(); 16668 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16669 serializer.startDocument(null, true); 16670 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 16671 16672 synchronized (mPackages) { 16673 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 16674 } 16675 16676 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 16677 serializer.endDocument(); 16678 serializer.flush(); 16679 } catch (Exception e) { 16680 if (DEBUG_BACKUP) { 16681 Slog.e(TAG, "Unable to write default apps for backup", e); 16682 } 16683 return null; 16684 } 16685 16686 return dataStream.toByteArray(); 16687 } 16688 16689 @Override 16690 public void restoreIntentFilterVerification(byte[] backup, int userId) { 16691 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16692 throw new SecurityException("Only the system may call restorePreferredActivities()"); 16693 } 16694 16695 try { 16696 final XmlPullParser parser = Xml.newPullParser(); 16697 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16698 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 16699 new BlobXmlRestorer() { 16700 @Override 16701 public void apply(XmlPullParser parser, int userId) 16702 throws XmlPullParserException, IOException { 16703 synchronized (mPackages) { 16704 mSettings.readAllDomainVerificationsLPr(parser, userId); 16705 mSettings.writeLPr(); 16706 } 16707 } 16708 } ); 16709 } catch (Exception e) { 16710 if (DEBUG_BACKUP) { 16711 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16712 } 16713 } 16714 } 16715 16716 @Override 16717 public byte[] getPermissionGrantBackup(int userId) { 16718 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16719 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 16720 } 16721 16722 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16723 try { 16724 final XmlSerializer serializer = new FastXmlSerializer(); 16725 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16726 serializer.startDocument(null, true); 16727 serializer.startTag(null, TAG_PERMISSION_BACKUP); 16728 16729 synchronized (mPackages) { 16730 serializeRuntimePermissionGrantsLPr(serializer, userId); 16731 } 16732 16733 serializer.endTag(null, TAG_PERMISSION_BACKUP); 16734 serializer.endDocument(); 16735 serializer.flush(); 16736 } catch (Exception e) { 16737 if (DEBUG_BACKUP) { 16738 Slog.e(TAG, "Unable to write default apps for backup", e); 16739 } 16740 return null; 16741 } 16742 16743 return dataStream.toByteArray(); 16744 } 16745 16746 @Override 16747 public void restorePermissionGrants(byte[] backup, int userId) { 16748 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16749 throw new SecurityException("Only the system may call restorePermissionGrants()"); 16750 } 16751 16752 try { 16753 final XmlPullParser parser = Xml.newPullParser(); 16754 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16755 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 16756 new BlobXmlRestorer() { 16757 @Override 16758 public void apply(XmlPullParser parser, int userId) 16759 throws XmlPullParserException, IOException { 16760 synchronized (mPackages) { 16761 processRestoredPermissionGrantsLPr(parser, userId); 16762 } 16763 } 16764 } ); 16765 } catch (Exception e) { 16766 if (DEBUG_BACKUP) { 16767 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16768 } 16769 } 16770 } 16771 16772 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 16773 throws IOException { 16774 serializer.startTag(null, TAG_ALL_GRANTS); 16775 16776 final int N = mSettings.mPackages.size(); 16777 for (int i = 0; i < N; i++) { 16778 final PackageSetting ps = mSettings.mPackages.valueAt(i); 16779 boolean pkgGrantsKnown = false; 16780 16781 PermissionsState packagePerms = ps.getPermissionsState(); 16782 16783 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 16784 final int grantFlags = state.getFlags(); 16785 // only look at grants that are not system/policy fixed 16786 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 16787 final boolean isGranted = state.isGranted(); 16788 // And only back up the user-twiddled state bits 16789 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 16790 final String packageName = mSettings.mPackages.keyAt(i); 16791 if (!pkgGrantsKnown) { 16792 serializer.startTag(null, TAG_GRANT); 16793 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 16794 pkgGrantsKnown = true; 16795 } 16796 16797 final boolean userSet = 16798 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 16799 final boolean userFixed = 16800 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 16801 final boolean revoke = 16802 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 16803 16804 serializer.startTag(null, TAG_PERMISSION); 16805 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 16806 if (isGranted) { 16807 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 16808 } 16809 if (userSet) { 16810 serializer.attribute(null, ATTR_USER_SET, "true"); 16811 } 16812 if (userFixed) { 16813 serializer.attribute(null, ATTR_USER_FIXED, "true"); 16814 } 16815 if (revoke) { 16816 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 16817 } 16818 serializer.endTag(null, TAG_PERMISSION); 16819 } 16820 } 16821 } 16822 16823 if (pkgGrantsKnown) { 16824 serializer.endTag(null, TAG_GRANT); 16825 } 16826 } 16827 16828 serializer.endTag(null, TAG_ALL_GRANTS); 16829 } 16830 16831 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 16832 throws XmlPullParserException, IOException { 16833 String pkgName = null; 16834 int outerDepth = parser.getDepth(); 16835 int type; 16836 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 16837 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 16838 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 16839 continue; 16840 } 16841 16842 final String tagName = parser.getName(); 16843 if (tagName.equals(TAG_GRANT)) { 16844 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 16845 if (DEBUG_BACKUP) { 16846 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 16847 } 16848 } else if (tagName.equals(TAG_PERMISSION)) { 16849 16850 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 16851 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 16852 16853 int newFlagSet = 0; 16854 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 16855 newFlagSet |= FLAG_PERMISSION_USER_SET; 16856 } 16857 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 16858 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 16859 } 16860 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 16861 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 16862 } 16863 if (DEBUG_BACKUP) { 16864 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 16865 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 16866 } 16867 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16868 if (ps != null) { 16869 // Already installed so we apply the grant immediately 16870 if (DEBUG_BACKUP) { 16871 Slog.v(TAG, " + already installed; applying"); 16872 } 16873 PermissionsState perms = ps.getPermissionsState(); 16874 BasePermission bp = mSettings.mPermissions.get(permName); 16875 if (bp != null) { 16876 if (isGranted) { 16877 perms.grantRuntimePermission(bp, userId); 16878 } 16879 if (newFlagSet != 0) { 16880 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 16881 } 16882 } 16883 } else { 16884 // Need to wait for post-restore install to apply the grant 16885 if (DEBUG_BACKUP) { 16886 Slog.v(TAG, " - not yet installed; saving for later"); 16887 } 16888 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 16889 isGranted, newFlagSet, userId); 16890 } 16891 } else { 16892 PackageManagerService.reportSettingsProblem(Log.WARN, 16893 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 16894 XmlUtils.skipCurrentTag(parser); 16895 } 16896 } 16897 16898 scheduleWriteSettingsLocked(); 16899 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 16900 } 16901 16902 @Override 16903 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 16904 int sourceUserId, int targetUserId, int flags) { 16905 mContext.enforceCallingOrSelfPermission( 16906 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 16907 int callingUid = Binder.getCallingUid(); 16908 enforceOwnerRights(ownerPackage, callingUid); 16909 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 16910 if (intentFilter.countActions() == 0) { 16911 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 16912 return; 16913 } 16914 synchronized (mPackages) { 16915 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 16916 ownerPackage, targetUserId, flags); 16917 CrossProfileIntentResolver resolver = 16918 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 16919 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 16920 // We have all those whose filter is equal. Now checking if the rest is equal as well. 16921 if (existing != null) { 16922 int size = existing.size(); 16923 for (int i = 0; i < size; i++) { 16924 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 16925 return; 16926 } 16927 } 16928 } 16929 resolver.addFilter(newFilter); 16930 scheduleWritePackageRestrictionsLocked(sourceUserId); 16931 } 16932 } 16933 16934 @Override 16935 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 16936 mContext.enforceCallingOrSelfPermission( 16937 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 16938 int callingUid = Binder.getCallingUid(); 16939 enforceOwnerRights(ownerPackage, callingUid); 16940 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 16941 synchronized (mPackages) { 16942 CrossProfileIntentResolver resolver = 16943 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 16944 ArraySet<CrossProfileIntentFilter> set = 16945 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 16946 for (CrossProfileIntentFilter filter : set) { 16947 if (filter.getOwnerPackage().equals(ownerPackage)) { 16948 resolver.removeFilter(filter); 16949 } 16950 } 16951 scheduleWritePackageRestrictionsLocked(sourceUserId); 16952 } 16953 } 16954 16955 // Enforcing that callingUid is owning pkg on userId 16956 private void enforceOwnerRights(String pkg, int callingUid) { 16957 // The system owns everything. 16958 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 16959 return; 16960 } 16961 int callingUserId = UserHandle.getUserId(callingUid); 16962 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 16963 if (pi == null) { 16964 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 16965 + callingUserId); 16966 } 16967 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 16968 throw new SecurityException("Calling uid " + callingUid 16969 + " does not own package " + pkg); 16970 } 16971 } 16972 16973 @Override 16974 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 16975 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 16976 } 16977 16978 private Intent getHomeIntent() { 16979 Intent intent = new Intent(Intent.ACTION_MAIN); 16980 intent.addCategory(Intent.CATEGORY_HOME); 16981 return intent; 16982 } 16983 16984 private IntentFilter getHomeFilter() { 16985 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 16986 filter.addCategory(Intent.CATEGORY_HOME); 16987 filter.addCategory(Intent.CATEGORY_DEFAULT); 16988 return filter; 16989 } 16990 16991 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 16992 int userId) { 16993 Intent intent = getHomeIntent(); 16994 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 16995 PackageManager.GET_META_DATA, userId); 16996 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 16997 true, false, false, userId); 16998 16999 allHomeCandidates.clear(); 17000 if (list != null) { 17001 for (ResolveInfo ri : list) { 17002 allHomeCandidates.add(ri); 17003 } 17004 } 17005 return (preferred == null || preferred.activityInfo == null) 17006 ? null 17007 : new ComponentName(preferred.activityInfo.packageName, 17008 preferred.activityInfo.name); 17009 } 17010 17011 @Override 17012 public void setHomeActivity(ComponentName comp, int userId) { 17013 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 17014 getHomeActivitiesAsUser(homeActivities, userId); 17015 17016 boolean found = false; 17017 17018 final int size = homeActivities.size(); 17019 final ComponentName[] set = new ComponentName[size]; 17020 for (int i = 0; i < size; i++) { 17021 final ResolveInfo candidate = homeActivities.get(i); 17022 final ActivityInfo info = candidate.activityInfo; 17023 final ComponentName activityName = new ComponentName(info.packageName, info.name); 17024 set[i] = activityName; 17025 if (!found && activityName.equals(comp)) { 17026 found = true; 17027 } 17028 } 17029 if (!found) { 17030 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 17031 + userId); 17032 } 17033 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 17034 set, comp, userId); 17035 } 17036 17037 private @Nullable String getSetupWizardPackageName() { 17038 final Intent intent = new Intent(Intent.ACTION_MAIN); 17039 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 17040 17041 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 17042 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 17043 | MATCH_DISABLED_COMPONENTS, 17044 UserHandle.myUserId()); 17045 if (matches.size() == 1) { 17046 return matches.get(0).getComponentInfo().packageName; 17047 } else { 17048 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 17049 + ": matches=" + matches); 17050 return null; 17051 } 17052 } 17053 17054 @Override 17055 public void setApplicationEnabledSetting(String appPackageName, 17056 int newState, int flags, int userId, String callingPackage) { 17057 if (!sUserManager.exists(userId)) return; 17058 if (callingPackage == null) { 17059 callingPackage = Integer.toString(Binder.getCallingUid()); 17060 } 17061 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 17062 } 17063 17064 @Override 17065 public void setComponentEnabledSetting(ComponentName componentName, 17066 int newState, int flags, int userId) { 17067 if (!sUserManager.exists(userId)) return; 17068 setEnabledSetting(componentName.getPackageName(), 17069 componentName.getClassName(), newState, flags, userId, null); 17070 } 17071 17072 private void setEnabledSetting(final String packageName, String className, int newState, 17073 final int flags, int userId, String callingPackage) { 17074 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 17075 || newState == COMPONENT_ENABLED_STATE_ENABLED 17076 || newState == COMPONENT_ENABLED_STATE_DISABLED 17077 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17078 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 17079 throw new IllegalArgumentException("Invalid new component state: " 17080 + newState); 17081 } 17082 PackageSetting pkgSetting; 17083 final int uid = Binder.getCallingUid(); 17084 final int permission; 17085 if (uid == Process.SYSTEM_UID) { 17086 permission = PackageManager.PERMISSION_GRANTED; 17087 } else { 17088 permission = mContext.checkCallingOrSelfPermission( 17089 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17090 } 17091 enforceCrossUserPermission(uid, userId, 17092 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 17093 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17094 boolean sendNow = false; 17095 boolean isApp = (className == null); 17096 String componentName = isApp ? packageName : className; 17097 int packageUid = -1; 17098 ArrayList<String> components; 17099 17100 // writer 17101 synchronized (mPackages) { 17102 pkgSetting = mSettings.mPackages.get(packageName); 17103 if (pkgSetting == null) { 17104 if (className == null) { 17105 throw new IllegalArgumentException("Unknown package: " + packageName); 17106 } 17107 throw new IllegalArgumentException( 17108 "Unknown component: " + packageName + "/" + className); 17109 } 17110 // Allow root and verify that userId is not being specified by a different user 17111 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 17112 throw new SecurityException( 17113 "Permission Denial: attempt to change component state from pid=" 17114 + Binder.getCallingPid() 17115 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 17116 } 17117 if (className == null) { 17118 // We're dealing with an application/package level state change 17119 if (pkgSetting.getEnabled(userId) == newState) { 17120 // Nothing to do 17121 return; 17122 } 17123 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 17124 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 17125 // Don't care about who enables an app. 17126 callingPackage = null; 17127 } 17128 pkgSetting.setEnabled(newState, userId, callingPackage); 17129 // pkgSetting.pkg.mSetEnabled = newState; 17130 } else { 17131 // We're dealing with a component level state change 17132 // First, verify that this is a valid class name. 17133 PackageParser.Package pkg = pkgSetting.pkg; 17134 if (pkg == null || !pkg.hasComponentClassName(className)) { 17135 if (pkg != null && 17136 pkg.applicationInfo.targetSdkVersion >= 17137 Build.VERSION_CODES.JELLY_BEAN) { 17138 throw new IllegalArgumentException("Component class " + className 17139 + " does not exist in " + packageName); 17140 } else { 17141 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 17142 + className + " does not exist in " + packageName); 17143 } 17144 } 17145 switch (newState) { 17146 case COMPONENT_ENABLED_STATE_ENABLED: 17147 if (!pkgSetting.enableComponentLPw(className, userId)) { 17148 return; 17149 } 17150 break; 17151 case COMPONENT_ENABLED_STATE_DISABLED: 17152 if (!pkgSetting.disableComponentLPw(className, userId)) { 17153 return; 17154 } 17155 break; 17156 case COMPONENT_ENABLED_STATE_DEFAULT: 17157 if (!pkgSetting.restoreComponentLPw(className, userId)) { 17158 return; 17159 } 17160 break; 17161 default: 17162 Slog.e(TAG, "Invalid new component state: " + newState); 17163 return; 17164 } 17165 } 17166 scheduleWritePackageRestrictionsLocked(userId); 17167 components = mPendingBroadcasts.get(userId, packageName); 17168 final boolean newPackage = components == null; 17169 if (newPackage) { 17170 components = new ArrayList<String>(); 17171 } 17172 if (!components.contains(componentName)) { 17173 components.add(componentName); 17174 } 17175 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 17176 sendNow = true; 17177 // Purge entry from pending broadcast list if another one exists already 17178 // since we are sending one right away. 17179 mPendingBroadcasts.remove(userId, packageName); 17180 } else { 17181 if (newPackage) { 17182 mPendingBroadcasts.put(userId, packageName, components); 17183 } 17184 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 17185 // Schedule a message 17186 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 17187 } 17188 } 17189 } 17190 17191 long callingId = Binder.clearCallingIdentity(); 17192 try { 17193 if (sendNow) { 17194 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 17195 sendPackageChangedBroadcast(packageName, 17196 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 17197 } 17198 } finally { 17199 Binder.restoreCallingIdentity(callingId); 17200 } 17201 } 17202 17203 @Override 17204 public void flushPackageRestrictionsAsUser(int userId) { 17205 if (!sUserManager.exists(userId)) { 17206 return; 17207 } 17208 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 17209 false /* checkShell */, "flushPackageRestrictions"); 17210 synchronized (mPackages) { 17211 mSettings.writePackageRestrictionsLPr(userId); 17212 mDirtyUsers.remove(userId); 17213 if (mDirtyUsers.isEmpty()) { 17214 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 17215 } 17216 } 17217 } 17218 17219 private void sendPackageChangedBroadcast(String packageName, 17220 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 17221 if (DEBUG_INSTALL) 17222 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 17223 + componentNames); 17224 Bundle extras = new Bundle(4); 17225 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 17226 String nameList[] = new String[componentNames.size()]; 17227 componentNames.toArray(nameList); 17228 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 17229 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 17230 extras.putInt(Intent.EXTRA_UID, packageUid); 17231 // If this is not reporting a change of the overall package, then only send it 17232 // to registered receivers. We don't want to launch a swath of apps for every 17233 // little component state change. 17234 final int flags = !componentNames.contains(packageName) 17235 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 17236 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 17237 new int[] {UserHandle.getUserId(packageUid)}); 17238 } 17239 17240 @Override 17241 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 17242 if (!sUserManager.exists(userId)) return; 17243 final int uid = Binder.getCallingUid(); 17244 final int permission = mContext.checkCallingOrSelfPermission( 17245 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17246 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17247 enforceCrossUserPermission(uid, userId, 17248 true /* requireFullPermission */, true /* checkShell */, "stop package"); 17249 // writer 17250 synchronized (mPackages) { 17251 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 17252 allowedByPermission, uid, userId)) { 17253 scheduleWritePackageRestrictionsLocked(userId); 17254 } 17255 } 17256 } 17257 17258 @Override 17259 public String getInstallerPackageName(String packageName) { 17260 // reader 17261 synchronized (mPackages) { 17262 return mSettings.getInstallerPackageNameLPr(packageName); 17263 } 17264 } 17265 17266 @Override 17267 public int getApplicationEnabledSetting(String packageName, int userId) { 17268 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17269 int uid = Binder.getCallingUid(); 17270 enforceCrossUserPermission(uid, userId, 17271 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 17272 // reader 17273 synchronized (mPackages) { 17274 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 17275 } 17276 } 17277 17278 @Override 17279 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 17280 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17281 int uid = Binder.getCallingUid(); 17282 enforceCrossUserPermission(uid, userId, 17283 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 17284 // reader 17285 synchronized (mPackages) { 17286 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 17287 } 17288 } 17289 17290 @Override 17291 public void enterSafeMode() { 17292 enforceSystemOrRoot("Only the system can request entering safe mode"); 17293 17294 if (!mSystemReady) { 17295 mSafeMode = true; 17296 } 17297 } 17298 17299 @Override 17300 public void systemReady() { 17301 mSystemReady = true; 17302 17303 // Read the compatibilty setting when the system is ready. 17304 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 17305 mContext.getContentResolver(), 17306 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 17307 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 17308 if (DEBUG_SETTINGS) { 17309 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 17310 } 17311 17312 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 17313 17314 synchronized (mPackages) { 17315 // Verify that all of the preferred activity components actually 17316 // exist. It is possible for applications to be updated and at 17317 // that point remove a previously declared activity component that 17318 // had been set as a preferred activity. We try to clean this up 17319 // the next time we encounter that preferred activity, but it is 17320 // possible for the user flow to never be able to return to that 17321 // situation so here we do a sanity check to make sure we haven't 17322 // left any junk around. 17323 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 17324 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17325 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17326 removed.clear(); 17327 for (PreferredActivity pa : pir.filterSet()) { 17328 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 17329 removed.add(pa); 17330 } 17331 } 17332 if (removed.size() > 0) { 17333 for (int r=0; r<removed.size(); r++) { 17334 PreferredActivity pa = removed.get(r); 17335 Slog.w(TAG, "Removing dangling preferred activity: " 17336 + pa.mPref.mComponent); 17337 pir.removeFilter(pa); 17338 } 17339 mSettings.writePackageRestrictionsLPr( 17340 mSettings.mPreferredActivities.keyAt(i)); 17341 } 17342 } 17343 17344 for (int userId : UserManagerService.getInstance().getUserIds()) { 17345 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 17346 grantPermissionsUserIds = ArrayUtils.appendInt( 17347 grantPermissionsUserIds, userId); 17348 } 17349 } 17350 } 17351 sUserManager.systemReady(); 17352 17353 // If we upgraded grant all default permissions before kicking off. 17354 for (int userId : grantPermissionsUserIds) { 17355 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 17356 } 17357 17358 // Kick off any messages waiting for system ready 17359 if (mPostSystemReadyMessages != null) { 17360 for (Message msg : mPostSystemReadyMessages) { 17361 msg.sendToTarget(); 17362 } 17363 mPostSystemReadyMessages = null; 17364 } 17365 17366 // Watch for external volumes that come and go over time 17367 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17368 storage.registerListener(mStorageListener); 17369 17370 mInstallerService.systemReady(); 17371 mPackageDexOptimizer.systemReady(); 17372 17373 MountServiceInternal mountServiceInternal = LocalServices.getService( 17374 MountServiceInternal.class); 17375 mountServiceInternal.addExternalStoragePolicy( 17376 new MountServiceInternal.ExternalStorageMountPolicy() { 17377 @Override 17378 public int getMountMode(int uid, String packageName) { 17379 if (Process.isIsolated(uid)) { 17380 return Zygote.MOUNT_EXTERNAL_NONE; 17381 } 17382 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 17383 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17384 } 17385 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17386 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17387 } 17388 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17389 return Zygote.MOUNT_EXTERNAL_READ; 17390 } 17391 return Zygote.MOUNT_EXTERNAL_WRITE; 17392 } 17393 17394 @Override 17395 public boolean hasExternalStorage(int uid, String packageName) { 17396 return true; 17397 } 17398 }); 17399 } 17400 17401 @Override 17402 public boolean isSafeMode() { 17403 return mSafeMode; 17404 } 17405 17406 @Override 17407 public boolean hasSystemUidErrors() { 17408 return mHasSystemUidErrors; 17409 } 17410 17411 static String arrayToString(int[] array) { 17412 StringBuffer buf = new StringBuffer(128); 17413 buf.append('['); 17414 if (array != null) { 17415 for (int i=0; i<array.length; i++) { 17416 if (i > 0) buf.append(", "); 17417 buf.append(array[i]); 17418 } 17419 } 17420 buf.append(']'); 17421 return buf.toString(); 17422 } 17423 17424 static class DumpState { 17425 public static final int DUMP_LIBS = 1 << 0; 17426 public static final int DUMP_FEATURES = 1 << 1; 17427 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 17428 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 17429 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 17430 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 17431 public static final int DUMP_PERMISSIONS = 1 << 6; 17432 public static final int DUMP_PACKAGES = 1 << 7; 17433 public static final int DUMP_SHARED_USERS = 1 << 8; 17434 public static final int DUMP_MESSAGES = 1 << 9; 17435 public static final int DUMP_PROVIDERS = 1 << 10; 17436 public static final int DUMP_VERIFIERS = 1 << 11; 17437 public static final int DUMP_PREFERRED = 1 << 12; 17438 public static final int DUMP_PREFERRED_XML = 1 << 13; 17439 public static final int DUMP_KEYSETS = 1 << 14; 17440 public static final int DUMP_VERSION = 1 << 15; 17441 public static final int DUMP_INSTALLS = 1 << 16; 17442 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 17443 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 17444 17445 public static final int OPTION_SHOW_FILTERS = 1 << 0; 17446 17447 private int mTypes; 17448 17449 private int mOptions; 17450 17451 private boolean mTitlePrinted; 17452 17453 private SharedUserSetting mSharedUser; 17454 17455 public boolean isDumping(int type) { 17456 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 17457 return true; 17458 } 17459 17460 return (mTypes & type) != 0; 17461 } 17462 17463 public void setDump(int type) { 17464 mTypes |= type; 17465 } 17466 17467 public boolean isOptionEnabled(int option) { 17468 return (mOptions & option) != 0; 17469 } 17470 17471 public void setOptionEnabled(int option) { 17472 mOptions |= option; 17473 } 17474 17475 public boolean onTitlePrinted() { 17476 final boolean printed = mTitlePrinted; 17477 mTitlePrinted = true; 17478 return printed; 17479 } 17480 17481 public boolean getTitlePrinted() { 17482 return mTitlePrinted; 17483 } 17484 17485 public void setTitlePrinted(boolean enabled) { 17486 mTitlePrinted = enabled; 17487 } 17488 17489 public SharedUserSetting getSharedUser() { 17490 return mSharedUser; 17491 } 17492 17493 public void setSharedUser(SharedUserSetting user) { 17494 mSharedUser = user; 17495 } 17496 } 17497 17498 @Override 17499 public void onShellCommand(FileDescriptor in, FileDescriptor out, 17500 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 17501 (new PackageManagerShellCommand(this)).exec( 17502 this, in, out, err, args, resultReceiver); 17503 } 17504 17505 @Override 17506 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 17507 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 17508 != PackageManager.PERMISSION_GRANTED) { 17509 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 17510 + Binder.getCallingPid() 17511 + ", uid=" + Binder.getCallingUid() 17512 + " without permission " 17513 + android.Manifest.permission.DUMP); 17514 return; 17515 } 17516 17517 DumpState dumpState = new DumpState(); 17518 boolean fullPreferred = false; 17519 boolean checkin = false; 17520 17521 String packageName = null; 17522 ArraySet<String> permissionNames = null; 17523 17524 int opti = 0; 17525 while (opti < args.length) { 17526 String opt = args[opti]; 17527 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 17528 break; 17529 } 17530 opti++; 17531 17532 if ("-a".equals(opt)) { 17533 // Right now we only know how to print all. 17534 } else if ("-h".equals(opt)) { 17535 pw.println("Package manager dump options:"); 17536 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 17537 pw.println(" --checkin: dump for a checkin"); 17538 pw.println(" -f: print details of intent filters"); 17539 pw.println(" -h: print this help"); 17540 pw.println(" cmd may be one of:"); 17541 pw.println(" l[ibraries]: list known shared libraries"); 17542 pw.println(" f[eatures]: list device features"); 17543 pw.println(" k[eysets]: print known keysets"); 17544 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 17545 pw.println(" perm[issions]: dump permissions"); 17546 pw.println(" permission [name ...]: dump declaration and use of given permission"); 17547 pw.println(" pref[erred]: print preferred package settings"); 17548 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 17549 pw.println(" prov[iders]: dump content providers"); 17550 pw.println(" p[ackages]: dump installed packages"); 17551 pw.println(" s[hared-users]: dump shared user IDs"); 17552 pw.println(" m[essages]: print collected runtime messages"); 17553 pw.println(" v[erifiers]: print package verifier info"); 17554 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 17555 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 17556 pw.println(" version: print database version info"); 17557 pw.println(" write: write current settings now"); 17558 pw.println(" installs: details about install sessions"); 17559 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 17560 pw.println(" <package.name>: info about given package"); 17561 return; 17562 } else if ("--checkin".equals(opt)) { 17563 checkin = true; 17564 } else if ("-f".equals(opt)) { 17565 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 17566 } else { 17567 pw.println("Unknown argument: " + opt + "; use -h for help"); 17568 } 17569 } 17570 17571 // Is the caller requesting to dump a particular piece of data? 17572 if (opti < args.length) { 17573 String cmd = args[opti]; 17574 opti++; 17575 // Is this a package name? 17576 if ("android".equals(cmd) || cmd.contains(".")) { 17577 packageName = cmd; 17578 // When dumping a single package, we always dump all of its 17579 // filter information since the amount of data will be reasonable. 17580 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 17581 } else if ("check-permission".equals(cmd)) { 17582 if (opti >= args.length) { 17583 pw.println("Error: check-permission missing permission argument"); 17584 return; 17585 } 17586 String perm = args[opti]; 17587 opti++; 17588 if (opti >= args.length) { 17589 pw.println("Error: check-permission missing package argument"); 17590 return; 17591 } 17592 String pkg = args[opti]; 17593 opti++; 17594 int user = UserHandle.getUserId(Binder.getCallingUid()); 17595 if (opti < args.length) { 17596 try { 17597 user = Integer.parseInt(args[opti]); 17598 } catch (NumberFormatException e) { 17599 pw.println("Error: check-permission user argument is not a number: " 17600 + args[opti]); 17601 return; 17602 } 17603 } 17604 pw.println(checkPermission(perm, pkg, user)); 17605 return; 17606 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 17607 dumpState.setDump(DumpState.DUMP_LIBS); 17608 } else if ("f".equals(cmd) || "features".equals(cmd)) { 17609 dumpState.setDump(DumpState.DUMP_FEATURES); 17610 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 17611 if (opti >= args.length) { 17612 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 17613 | DumpState.DUMP_SERVICE_RESOLVERS 17614 | DumpState.DUMP_RECEIVER_RESOLVERS 17615 | DumpState.DUMP_CONTENT_RESOLVERS); 17616 } else { 17617 while (opti < args.length) { 17618 String name = args[opti]; 17619 if ("a".equals(name) || "activity".equals(name)) { 17620 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 17621 } else if ("s".equals(name) || "service".equals(name)) { 17622 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 17623 } else if ("r".equals(name) || "receiver".equals(name)) { 17624 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 17625 } else if ("c".equals(name) || "content".equals(name)) { 17626 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 17627 } else { 17628 pw.println("Error: unknown resolver table type: " + name); 17629 return; 17630 } 17631 opti++; 17632 } 17633 } 17634 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 17635 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 17636 } else if ("permission".equals(cmd)) { 17637 if (opti >= args.length) { 17638 pw.println("Error: permission requires permission name"); 17639 return; 17640 } 17641 permissionNames = new ArraySet<>(); 17642 while (opti < args.length) { 17643 permissionNames.add(args[opti]); 17644 opti++; 17645 } 17646 dumpState.setDump(DumpState.DUMP_PERMISSIONS 17647 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 17648 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 17649 dumpState.setDump(DumpState.DUMP_PREFERRED); 17650 } else if ("preferred-xml".equals(cmd)) { 17651 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 17652 if (opti < args.length && "--full".equals(args[opti])) { 17653 fullPreferred = true; 17654 opti++; 17655 } 17656 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 17657 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 17658 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 17659 dumpState.setDump(DumpState.DUMP_PACKAGES); 17660 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 17661 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 17662 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 17663 dumpState.setDump(DumpState.DUMP_PROVIDERS); 17664 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 17665 dumpState.setDump(DumpState.DUMP_MESSAGES); 17666 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 17667 dumpState.setDump(DumpState.DUMP_VERIFIERS); 17668 } else if ("i".equals(cmd) || "ifv".equals(cmd) 17669 || "intent-filter-verifiers".equals(cmd)) { 17670 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 17671 } else if ("version".equals(cmd)) { 17672 dumpState.setDump(DumpState.DUMP_VERSION); 17673 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 17674 dumpState.setDump(DumpState.DUMP_KEYSETS); 17675 } else if ("installs".equals(cmd)) { 17676 dumpState.setDump(DumpState.DUMP_INSTALLS); 17677 } else if ("write".equals(cmd)) { 17678 synchronized (mPackages) { 17679 mSettings.writeLPr(); 17680 pw.println("Settings written."); 17681 return; 17682 } 17683 } 17684 } 17685 17686 if (checkin) { 17687 pw.println("vers,1"); 17688 } 17689 17690 // reader 17691 synchronized (mPackages) { 17692 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 17693 if (!checkin) { 17694 if (dumpState.onTitlePrinted()) 17695 pw.println(); 17696 pw.println("Database versions:"); 17697 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 17698 } 17699 } 17700 17701 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 17702 if (!checkin) { 17703 if (dumpState.onTitlePrinted()) 17704 pw.println(); 17705 pw.println("Verifiers:"); 17706 pw.print(" Required: "); 17707 pw.print(mRequiredVerifierPackage); 17708 pw.print(" (uid="); 17709 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 17710 UserHandle.USER_SYSTEM)); 17711 pw.println(")"); 17712 } else if (mRequiredVerifierPackage != null) { 17713 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 17714 pw.print(","); 17715 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 17716 UserHandle.USER_SYSTEM)); 17717 } 17718 } 17719 17720 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 17721 packageName == null) { 17722 if (mIntentFilterVerifierComponent != null) { 17723 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 17724 if (!checkin) { 17725 if (dumpState.onTitlePrinted()) 17726 pw.println(); 17727 pw.println("Intent Filter Verifier:"); 17728 pw.print(" Using: "); 17729 pw.print(verifierPackageName); 17730 pw.print(" (uid="); 17731 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 17732 UserHandle.USER_SYSTEM)); 17733 pw.println(")"); 17734 } else if (verifierPackageName != null) { 17735 pw.print("ifv,"); pw.print(verifierPackageName); 17736 pw.print(","); 17737 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 17738 UserHandle.USER_SYSTEM)); 17739 } 17740 } else { 17741 pw.println(); 17742 pw.println("No Intent Filter Verifier available!"); 17743 } 17744 } 17745 17746 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 17747 boolean printedHeader = false; 17748 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 17749 while (it.hasNext()) { 17750 String name = it.next(); 17751 SharedLibraryEntry ent = mSharedLibraries.get(name); 17752 if (!checkin) { 17753 if (!printedHeader) { 17754 if (dumpState.onTitlePrinted()) 17755 pw.println(); 17756 pw.println("Libraries:"); 17757 printedHeader = true; 17758 } 17759 pw.print(" "); 17760 } else { 17761 pw.print("lib,"); 17762 } 17763 pw.print(name); 17764 if (!checkin) { 17765 pw.print(" -> "); 17766 } 17767 if (ent.path != null) { 17768 if (!checkin) { 17769 pw.print("(jar) "); 17770 pw.print(ent.path); 17771 } else { 17772 pw.print(",jar,"); 17773 pw.print(ent.path); 17774 } 17775 } else { 17776 if (!checkin) { 17777 pw.print("(apk) "); 17778 pw.print(ent.apk); 17779 } else { 17780 pw.print(",apk,"); 17781 pw.print(ent.apk); 17782 } 17783 } 17784 pw.println(); 17785 } 17786 } 17787 17788 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 17789 if (dumpState.onTitlePrinted()) 17790 pw.println(); 17791 if (!checkin) { 17792 pw.println("Features:"); 17793 } 17794 17795 for (FeatureInfo feat : mAvailableFeatures.values()) { 17796 if (checkin) { 17797 pw.print("feat,"); 17798 pw.print(feat.name); 17799 pw.print(","); 17800 pw.println(feat.version); 17801 } else { 17802 pw.print(" "); 17803 pw.print(feat.name); 17804 if (feat.version > 0) { 17805 pw.print(" version="); 17806 pw.print(feat.version); 17807 } 17808 pw.println(); 17809 } 17810 } 17811 } 17812 17813 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 17814 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 17815 : "Activity Resolver Table:", " ", packageName, 17816 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17817 dumpState.setTitlePrinted(true); 17818 } 17819 } 17820 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 17821 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 17822 : "Receiver Resolver Table:", " ", packageName, 17823 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17824 dumpState.setTitlePrinted(true); 17825 } 17826 } 17827 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 17828 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 17829 : "Service Resolver Table:", " ", packageName, 17830 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17831 dumpState.setTitlePrinted(true); 17832 } 17833 } 17834 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 17835 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 17836 : "Provider Resolver Table:", " ", packageName, 17837 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17838 dumpState.setTitlePrinted(true); 17839 } 17840 } 17841 17842 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 17843 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17844 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17845 int user = mSettings.mPreferredActivities.keyAt(i); 17846 if (pir.dump(pw, 17847 dumpState.getTitlePrinted() 17848 ? "\nPreferred Activities User " + user + ":" 17849 : "Preferred Activities User " + user + ":", " ", 17850 packageName, true, false)) { 17851 dumpState.setTitlePrinted(true); 17852 } 17853 } 17854 } 17855 17856 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 17857 pw.flush(); 17858 FileOutputStream fout = new FileOutputStream(fd); 17859 BufferedOutputStream str = new BufferedOutputStream(fout); 17860 XmlSerializer serializer = new FastXmlSerializer(); 17861 try { 17862 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 17863 serializer.startDocument(null, true); 17864 serializer.setFeature( 17865 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 17866 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 17867 serializer.endDocument(); 17868 serializer.flush(); 17869 } catch (IllegalArgumentException e) { 17870 pw.println("Failed writing: " + e); 17871 } catch (IllegalStateException e) { 17872 pw.println("Failed writing: " + e); 17873 } catch (IOException e) { 17874 pw.println("Failed writing: " + e); 17875 } 17876 } 17877 17878 if (!checkin 17879 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 17880 && packageName == null) { 17881 pw.println(); 17882 int count = mSettings.mPackages.size(); 17883 if (count == 0) { 17884 pw.println("No applications!"); 17885 pw.println(); 17886 } else { 17887 final String prefix = " "; 17888 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 17889 if (allPackageSettings.size() == 0) { 17890 pw.println("No domain preferred apps!"); 17891 pw.println(); 17892 } else { 17893 pw.println("App verification status:"); 17894 pw.println(); 17895 count = 0; 17896 for (PackageSetting ps : allPackageSettings) { 17897 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 17898 if (ivi == null || ivi.getPackageName() == null) continue; 17899 pw.println(prefix + "Package: " + ivi.getPackageName()); 17900 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 17901 pw.println(prefix + "Status: " + ivi.getStatusString()); 17902 pw.println(); 17903 count++; 17904 } 17905 if (count == 0) { 17906 pw.println(prefix + "No app verification established."); 17907 pw.println(); 17908 } 17909 for (int userId : sUserManager.getUserIds()) { 17910 pw.println("App linkages for user " + userId + ":"); 17911 pw.println(); 17912 count = 0; 17913 for (PackageSetting ps : allPackageSettings) { 17914 final long status = ps.getDomainVerificationStatusForUser(userId); 17915 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 17916 continue; 17917 } 17918 pw.println(prefix + "Package: " + ps.name); 17919 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 17920 String statusStr = IntentFilterVerificationInfo. 17921 getStatusStringFromValue(status); 17922 pw.println(prefix + "Status: " + statusStr); 17923 pw.println(); 17924 count++; 17925 } 17926 if (count == 0) { 17927 pw.println(prefix + "No configured app linkages."); 17928 pw.println(); 17929 } 17930 } 17931 } 17932 } 17933 } 17934 17935 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 17936 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 17937 if (packageName == null && permissionNames == null) { 17938 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 17939 if (iperm == 0) { 17940 if (dumpState.onTitlePrinted()) 17941 pw.println(); 17942 pw.println("AppOp Permissions:"); 17943 } 17944 pw.print(" AppOp Permission "); 17945 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 17946 pw.println(":"); 17947 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 17948 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 17949 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 17950 } 17951 } 17952 } 17953 } 17954 17955 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 17956 boolean printedSomething = false; 17957 for (PackageParser.Provider p : mProviders.mProviders.values()) { 17958 if (packageName != null && !packageName.equals(p.info.packageName)) { 17959 continue; 17960 } 17961 if (!printedSomething) { 17962 if (dumpState.onTitlePrinted()) 17963 pw.println(); 17964 pw.println("Registered ContentProviders:"); 17965 printedSomething = true; 17966 } 17967 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 17968 pw.print(" "); pw.println(p.toString()); 17969 } 17970 printedSomething = false; 17971 for (Map.Entry<String, PackageParser.Provider> entry : 17972 mProvidersByAuthority.entrySet()) { 17973 PackageParser.Provider p = entry.getValue(); 17974 if (packageName != null && !packageName.equals(p.info.packageName)) { 17975 continue; 17976 } 17977 if (!printedSomething) { 17978 if (dumpState.onTitlePrinted()) 17979 pw.println(); 17980 pw.println("ContentProvider Authorities:"); 17981 printedSomething = true; 17982 } 17983 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 17984 pw.print(" "); pw.println(p.toString()); 17985 if (p.info != null && p.info.applicationInfo != null) { 17986 final String appInfo = p.info.applicationInfo.toString(); 17987 pw.print(" applicationInfo="); pw.println(appInfo); 17988 } 17989 } 17990 } 17991 17992 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 17993 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 17994 } 17995 17996 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 17997 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 17998 } 17999 18000 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 18001 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 18002 } 18003 18004 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 18005 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 18006 } 18007 18008 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 18009 // XXX should handle packageName != null by dumping only install data that 18010 // the given package is involved with. 18011 if (dumpState.onTitlePrinted()) pw.println(); 18012 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 18013 } 18014 18015 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 18016 if (dumpState.onTitlePrinted()) pw.println(); 18017 mSettings.dumpReadMessagesLPr(pw, dumpState); 18018 18019 pw.println(); 18020 pw.println("Package warning messages:"); 18021 BufferedReader in = null; 18022 String line = null; 18023 try { 18024 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18025 while ((line = in.readLine()) != null) { 18026 if (line.contains("ignored: updated version")) continue; 18027 pw.println(line); 18028 } 18029 } catch (IOException ignored) { 18030 } finally { 18031 IoUtils.closeQuietly(in); 18032 } 18033 } 18034 18035 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 18036 BufferedReader in = null; 18037 String line = null; 18038 try { 18039 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18040 while ((line = in.readLine()) != null) { 18041 if (line.contains("ignored: updated version")) continue; 18042 pw.print("msg,"); 18043 pw.println(line); 18044 } 18045 } catch (IOException ignored) { 18046 } finally { 18047 IoUtils.closeQuietly(in); 18048 } 18049 } 18050 } 18051 } 18052 18053 private String dumpDomainString(String packageName) { 18054 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 18055 .getList(); 18056 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 18057 18058 ArraySet<String> result = new ArraySet<>(); 18059 if (iviList.size() > 0) { 18060 for (IntentFilterVerificationInfo ivi : iviList) { 18061 for (String host : ivi.getDomains()) { 18062 result.add(host); 18063 } 18064 } 18065 } 18066 if (filters != null && filters.size() > 0) { 18067 for (IntentFilter filter : filters) { 18068 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 18069 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 18070 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 18071 result.addAll(filter.getHostsList()); 18072 } 18073 } 18074 } 18075 18076 StringBuilder sb = new StringBuilder(result.size() * 16); 18077 for (String domain : result) { 18078 if (sb.length() > 0) sb.append(" "); 18079 sb.append(domain); 18080 } 18081 return sb.toString(); 18082 } 18083 18084 // ------- apps on sdcard specific code ------- 18085 static final boolean DEBUG_SD_INSTALL = false; 18086 18087 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 18088 18089 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 18090 18091 private boolean mMediaMounted = false; 18092 18093 static String getEncryptKey() { 18094 try { 18095 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 18096 SD_ENCRYPTION_KEYSTORE_NAME); 18097 if (sdEncKey == null) { 18098 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 18099 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 18100 if (sdEncKey == null) { 18101 Slog.e(TAG, "Failed to create encryption keys"); 18102 return null; 18103 } 18104 } 18105 return sdEncKey; 18106 } catch (NoSuchAlgorithmException nsae) { 18107 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 18108 return null; 18109 } catch (IOException ioe) { 18110 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 18111 return null; 18112 } 18113 } 18114 18115 /* 18116 * Update media status on PackageManager. 18117 */ 18118 @Override 18119 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 18120 int callingUid = Binder.getCallingUid(); 18121 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 18122 throw new SecurityException("Media status can only be updated by the system"); 18123 } 18124 // reader; this apparently protects mMediaMounted, but should probably 18125 // be a different lock in that case. 18126 synchronized (mPackages) { 18127 Log.i(TAG, "Updating external media status from " 18128 + (mMediaMounted ? "mounted" : "unmounted") + " to " 18129 + (mediaStatus ? "mounted" : "unmounted")); 18130 if (DEBUG_SD_INSTALL) 18131 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 18132 + ", mMediaMounted=" + mMediaMounted); 18133 if (mediaStatus == mMediaMounted) { 18134 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 18135 : 0, -1); 18136 mHandler.sendMessage(msg); 18137 return; 18138 } 18139 mMediaMounted = mediaStatus; 18140 } 18141 // Queue up an async operation since the package installation may take a 18142 // little while. 18143 mHandler.post(new Runnable() { 18144 public void run() { 18145 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 18146 } 18147 }); 18148 } 18149 18150 /** 18151 * Called by MountService when the initial ASECs to scan are available. 18152 * Should block until all the ASEC containers are finished being scanned. 18153 */ 18154 public void scanAvailableAsecs() { 18155 updateExternalMediaStatusInner(true, false, false); 18156 } 18157 18158 /* 18159 * Collect information of applications on external media, map them against 18160 * existing containers and update information based on current mount status. 18161 * Please note that we always have to report status if reportStatus has been 18162 * set to true especially when unloading packages. 18163 */ 18164 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 18165 boolean externalStorage) { 18166 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 18167 int[] uidArr = EmptyArray.INT; 18168 18169 final String[] list = PackageHelper.getSecureContainerList(); 18170 if (ArrayUtils.isEmpty(list)) { 18171 Log.i(TAG, "No secure containers found"); 18172 } else { 18173 // Process list of secure containers and categorize them 18174 // as active or stale based on their package internal state. 18175 18176 // reader 18177 synchronized (mPackages) { 18178 for (String cid : list) { 18179 // Leave stages untouched for now; installer service owns them 18180 if (PackageInstallerService.isStageName(cid)) continue; 18181 18182 if (DEBUG_SD_INSTALL) 18183 Log.i(TAG, "Processing container " + cid); 18184 String pkgName = getAsecPackageName(cid); 18185 if (pkgName == null) { 18186 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 18187 continue; 18188 } 18189 if (DEBUG_SD_INSTALL) 18190 Log.i(TAG, "Looking for pkg : " + pkgName); 18191 18192 final PackageSetting ps = mSettings.mPackages.get(pkgName); 18193 if (ps == null) { 18194 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 18195 continue; 18196 } 18197 18198 /* 18199 * Skip packages that are not external if we're unmounting 18200 * external storage. 18201 */ 18202 if (externalStorage && !isMounted && !isExternal(ps)) { 18203 continue; 18204 } 18205 18206 final AsecInstallArgs args = new AsecInstallArgs(cid, 18207 getAppDexInstructionSets(ps), ps.isForwardLocked()); 18208 // The package status is changed only if the code path 18209 // matches between settings and the container id. 18210 if (ps.codePathString != null 18211 && ps.codePathString.startsWith(args.getCodePath())) { 18212 if (DEBUG_SD_INSTALL) { 18213 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 18214 + " at code path: " + ps.codePathString); 18215 } 18216 18217 // We do have a valid package installed on sdcard 18218 processCids.put(args, ps.codePathString); 18219 final int uid = ps.appId; 18220 if (uid != -1) { 18221 uidArr = ArrayUtils.appendInt(uidArr, uid); 18222 } 18223 } else { 18224 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 18225 + ps.codePathString); 18226 } 18227 } 18228 } 18229 18230 Arrays.sort(uidArr); 18231 } 18232 18233 // Process packages with valid entries. 18234 if (isMounted) { 18235 if (DEBUG_SD_INSTALL) 18236 Log.i(TAG, "Loading packages"); 18237 loadMediaPackages(processCids, uidArr, externalStorage); 18238 startCleaningPackages(); 18239 mInstallerService.onSecureContainersAvailable(); 18240 } else { 18241 if (DEBUG_SD_INSTALL) 18242 Log.i(TAG, "Unloading packages"); 18243 unloadMediaPackages(processCids, uidArr, reportStatus); 18244 } 18245 } 18246 18247 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18248 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 18249 final int size = infos.size(); 18250 final String[] packageNames = new String[size]; 18251 final int[] packageUids = new int[size]; 18252 for (int i = 0; i < size; i++) { 18253 final ApplicationInfo info = infos.get(i); 18254 packageNames[i] = info.packageName; 18255 packageUids[i] = info.uid; 18256 } 18257 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 18258 finishedReceiver); 18259 } 18260 18261 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18262 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18263 sendResourcesChangedBroadcast(mediaStatus, replacing, 18264 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 18265 } 18266 18267 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18268 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18269 int size = pkgList.length; 18270 if (size > 0) { 18271 // Send broadcasts here 18272 Bundle extras = new Bundle(); 18273 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 18274 if (uidArr != null) { 18275 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 18276 } 18277 if (replacing) { 18278 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 18279 } 18280 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 18281 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 18282 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 18283 } 18284 } 18285 18286 /* 18287 * Look at potentially valid container ids from processCids If package 18288 * information doesn't match the one on record or package scanning fails, 18289 * the cid is added to list of removeCids. We currently don't delete stale 18290 * containers. 18291 */ 18292 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 18293 boolean externalStorage) { 18294 ArrayList<String> pkgList = new ArrayList<String>(); 18295 Set<AsecInstallArgs> keys = processCids.keySet(); 18296 18297 for (AsecInstallArgs args : keys) { 18298 String codePath = processCids.get(args); 18299 if (DEBUG_SD_INSTALL) 18300 Log.i(TAG, "Loading container : " + args.cid); 18301 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 18302 try { 18303 // Make sure there are no container errors first. 18304 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 18305 Slog.e(TAG, "Failed to mount cid : " + args.cid 18306 + " when installing from sdcard"); 18307 continue; 18308 } 18309 // Check code path here. 18310 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 18311 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 18312 + " does not match one in settings " + codePath); 18313 continue; 18314 } 18315 // Parse package 18316 int parseFlags = mDefParseFlags; 18317 if (args.isExternalAsec()) { 18318 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 18319 } 18320 if (args.isFwdLocked()) { 18321 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 18322 } 18323 18324 synchronized (mInstallLock) { 18325 PackageParser.Package pkg = null; 18326 try { 18327 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null); 18328 } catch (PackageManagerException e) { 18329 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 18330 } 18331 // Scan the package 18332 if (pkg != null) { 18333 /* 18334 * TODO why is the lock being held? doPostInstall is 18335 * called in other places without the lock. This needs 18336 * to be straightened out. 18337 */ 18338 // writer 18339 synchronized (mPackages) { 18340 retCode = PackageManager.INSTALL_SUCCEEDED; 18341 pkgList.add(pkg.packageName); 18342 // Post process args 18343 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 18344 pkg.applicationInfo.uid); 18345 } 18346 } else { 18347 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 18348 } 18349 } 18350 18351 } finally { 18352 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 18353 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 18354 } 18355 } 18356 } 18357 // writer 18358 synchronized (mPackages) { 18359 // If the platform SDK has changed since the last time we booted, 18360 // we need to re-grant app permission to catch any new ones that 18361 // appear. This is really a hack, and means that apps can in some 18362 // cases get permissions that the user didn't initially explicitly 18363 // allow... it would be nice to have some better way to handle 18364 // this situation. 18365 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 18366 : mSettings.getInternalVersion(); 18367 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 18368 : StorageManager.UUID_PRIVATE_INTERNAL; 18369 18370 int updateFlags = UPDATE_PERMISSIONS_ALL; 18371 if (ver.sdkVersion != mSdkVersion) { 18372 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 18373 + mSdkVersion + "; regranting permissions for external"); 18374 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 18375 } 18376 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 18377 18378 // Yay, everything is now upgraded 18379 ver.forceCurrent(); 18380 18381 // can downgrade to reader 18382 // Persist settings 18383 mSettings.writeLPr(); 18384 } 18385 // Send a broadcast to let everyone know we are done processing 18386 if (pkgList.size() > 0) { 18387 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 18388 } 18389 } 18390 18391 /* 18392 * Utility method to unload a list of specified containers 18393 */ 18394 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 18395 // Just unmount all valid containers. 18396 for (AsecInstallArgs arg : cidArgs) { 18397 synchronized (mInstallLock) { 18398 arg.doPostDeleteLI(false); 18399 } 18400 } 18401 } 18402 18403 /* 18404 * Unload packages mounted on external media. This involves deleting package 18405 * data from internal structures, sending broadcasts about disabled packages, 18406 * gc'ing to free up references, unmounting all secure containers 18407 * corresponding to packages on external media, and posting a 18408 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 18409 * that we always have to post this message if status has been requested no 18410 * matter what. 18411 */ 18412 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 18413 final boolean reportStatus) { 18414 if (DEBUG_SD_INSTALL) 18415 Log.i(TAG, "unloading media packages"); 18416 ArrayList<String> pkgList = new ArrayList<String>(); 18417 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 18418 final Set<AsecInstallArgs> keys = processCids.keySet(); 18419 for (AsecInstallArgs args : keys) { 18420 String pkgName = args.getPackageName(); 18421 if (DEBUG_SD_INSTALL) 18422 Log.i(TAG, "Trying to unload pkg : " + pkgName); 18423 // Delete package internally 18424 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 18425 synchronized (mInstallLock) { 18426 boolean res = deletePackageLI(pkgName, null, false, null, 18427 PackageManager.DELETE_KEEP_DATA, outInfo, false, null); 18428 if (res) { 18429 pkgList.add(pkgName); 18430 } else { 18431 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 18432 failedList.add(args); 18433 } 18434 } 18435 } 18436 18437 // reader 18438 synchronized (mPackages) { 18439 // We didn't update the settings after removing each package; 18440 // write them now for all packages. 18441 mSettings.writeLPr(); 18442 } 18443 18444 // We have to absolutely send UPDATED_MEDIA_STATUS only 18445 // after confirming that all the receivers processed the ordered 18446 // broadcast when packages get disabled, force a gc to clean things up. 18447 // and unload all the containers. 18448 if (pkgList.size() > 0) { 18449 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 18450 new IIntentReceiver.Stub() { 18451 public void performReceive(Intent intent, int resultCode, String data, 18452 Bundle extras, boolean ordered, boolean sticky, 18453 int sendingUser) throws RemoteException { 18454 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 18455 reportStatus ? 1 : 0, 1, keys); 18456 mHandler.sendMessage(msg); 18457 } 18458 }); 18459 } else { 18460 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 18461 keys); 18462 mHandler.sendMessage(msg); 18463 } 18464 } 18465 18466 private void loadPrivatePackages(final VolumeInfo vol) { 18467 mHandler.post(new Runnable() { 18468 @Override 18469 public void run() { 18470 loadPrivatePackagesInner(vol); 18471 } 18472 }); 18473 } 18474 18475 private void loadPrivatePackagesInner(VolumeInfo vol) { 18476 final String volumeUuid = vol.fsUuid; 18477 if (TextUtils.isEmpty(volumeUuid)) { 18478 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 18479 return; 18480 } 18481 18482 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 18483 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 18484 18485 final VersionInfo ver; 18486 final List<PackageSetting> packages; 18487 synchronized (mPackages) { 18488 ver = mSettings.findOrCreateVersion(volumeUuid); 18489 packages = mSettings.getVolumePackagesLPr(volumeUuid); 18490 } 18491 18492 // TODO: introduce a new concept similar to "frozen" to prevent these 18493 // apps from being launched until after data has been fully reconciled 18494 for (PackageSetting ps : packages) { 18495 synchronized (mInstallLock) { 18496 final PackageParser.Package pkg; 18497 try { 18498 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 18499 loaded.add(pkg.applicationInfo); 18500 18501 } catch (PackageManagerException e) { 18502 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 18503 } 18504 18505 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 18506 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 18507 } 18508 } 18509 } 18510 18511 // Reconcile app data for all started/unlocked users 18512 final StorageManager sm = mContext.getSystemService(StorageManager.class); 18513 final UserManager um = mContext.getSystemService(UserManager.class); 18514 for (UserInfo user : um.getUsers()) { 18515 final int flags; 18516 if (um.isUserUnlocked(user.id)) { 18517 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18518 } else if (um.isUserRunning(user.id)) { 18519 flags = StorageManager.FLAG_STORAGE_DE; 18520 } else { 18521 continue; 18522 } 18523 18524 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 18525 reconcileAppsData(volumeUuid, user.id, flags); 18526 } 18527 18528 synchronized (mPackages) { 18529 int updateFlags = UPDATE_PERMISSIONS_ALL; 18530 if (ver.sdkVersion != mSdkVersion) { 18531 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 18532 + mSdkVersion + "; regranting permissions for " + volumeUuid); 18533 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 18534 } 18535 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 18536 18537 // Yay, everything is now upgraded 18538 ver.forceCurrent(); 18539 18540 mSettings.writeLPr(); 18541 } 18542 18543 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 18544 sendResourcesChangedBroadcast(true, false, loaded, null); 18545 } 18546 18547 private void unloadPrivatePackages(final VolumeInfo vol) { 18548 mHandler.post(new Runnable() { 18549 @Override 18550 public void run() { 18551 unloadPrivatePackagesInner(vol); 18552 } 18553 }); 18554 } 18555 18556 private void unloadPrivatePackagesInner(VolumeInfo vol) { 18557 final String volumeUuid = vol.fsUuid; 18558 if (TextUtils.isEmpty(volumeUuid)) { 18559 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 18560 return; 18561 } 18562 18563 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 18564 synchronized (mInstallLock) { 18565 synchronized (mPackages) { 18566 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 18567 for (PackageSetting ps : packages) { 18568 if (ps.pkg == null) continue; 18569 18570 final ApplicationInfo info = ps.pkg.applicationInfo; 18571 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 18572 if (deletePackageLI(ps.name, null, false, null, 18573 PackageManager.DELETE_KEEP_DATA, outInfo, false, null)) { 18574 unloaded.add(info); 18575 } else { 18576 Slog.w(TAG, "Failed to unload " + ps.codePath); 18577 } 18578 } 18579 18580 mSettings.writeLPr(); 18581 } 18582 } 18583 18584 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 18585 sendResourcesChangedBroadcast(false, false, unloaded, null); 18586 } 18587 18588 /** 18589 * Examine all users present on given mounted volume, and destroy data 18590 * belonging to users that are no longer valid, or whose user ID has been 18591 * recycled. 18592 */ 18593 private void reconcileUsers(String volumeUuid) { 18594 // TODO: also reconcile DE directories 18595 final File[] files = FileUtils 18596 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)); 18597 for (File file : files) { 18598 if (!file.isDirectory()) continue; 18599 18600 final int userId; 18601 final UserInfo info; 18602 try { 18603 userId = Integer.parseInt(file.getName()); 18604 info = sUserManager.getUserInfo(userId); 18605 } catch (NumberFormatException e) { 18606 Slog.w(TAG, "Invalid user directory " + file); 18607 continue; 18608 } 18609 18610 boolean destroyUser = false; 18611 if (info == null) { 18612 logCriticalInfo(Log.WARN, "Destroying user directory " + file 18613 + " because no matching user was found"); 18614 destroyUser = true; 18615 } else { 18616 try { 18617 UserManagerService.enforceSerialNumber(file, info.serialNumber); 18618 } catch (IOException e) { 18619 logCriticalInfo(Log.WARN, "Destroying user directory " + file 18620 + " because we failed to enforce serial number: " + e); 18621 destroyUser = true; 18622 } 18623 } 18624 18625 if (destroyUser) { 18626 synchronized (mInstallLock) { 18627 try { 18628 mInstaller.removeUserDataDirs(volumeUuid, userId); 18629 } catch (InstallerException e) { 18630 Slog.w(TAG, "Failed to clean up user dirs", e); 18631 } 18632 } 18633 } 18634 } 18635 } 18636 18637 private void assertPackageKnown(String volumeUuid, String packageName) 18638 throws PackageManagerException { 18639 synchronized (mPackages) { 18640 final PackageSetting ps = mSettings.mPackages.get(packageName); 18641 if (ps == null) { 18642 throw new PackageManagerException("Package " + packageName + " is unknown"); 18643 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 18644 throw new PackageManagerException( 18645 "Package " + packageName + " found on unknown volume " + volumeUuid 18646 + "; expected volume " + ps.volumeUuid); 18647 } 18648 } 18649 } 18650 18651 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 18652 throws PackageManagerException { 18653 synchronized (mPackages) { 18654 final PackageSetting ps = mSettings.mPackages.get(packageName); 18655 if (ps == null) { 18656 throw new PackageManagerException("Package " + packageName + " is unknown"); 18657 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 18658 throw new PackageManagerException( 18659 "Package " + packageName + " found on unknown volume " + volumeUuid 18660 + "; expected volume " + ps.volumeUuid); 18661 } else if (!ps.getInstalled(userId)) { 18662 throw new PackageManagerException( 18663 "Package " + packageName + " not installed for user " + userId); 18664 } 18665 } 18666 } 18667 18668 /** 18669 * Examine all apps present on given mounted volume, and destroy apps that 18670 * aren't expected, either due to uninstallation or reinstallation on 18671 * another volume. 18672 */ 18673 private void reconcileApps(String volumeUuid) { 18674 final File[] files = FileUtils 18675 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 18676 for (File file : files) { 18677 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 18678 && !PackageInstallerService.isStageName(file.getName()); 18679 if (!isPackage) { 18680 // Ignore entries which are not packages 18681 continue; 18682 } 18683 18684 try { 18685 final PackageLite pkg = PackageParser.parsePackageLite(file, 18686 PackageParser.PARSE_MUST_BE_APK); 18687 assertPackageKnown(volumeUuid, pkg.packageName); 18688 18689 } catch (PackageParserException | PackageManagerException e) { 18690 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 18691 synchronized (mInstallLock) { 18692 removeCodePathLI(file); 18693 } 18694 } 18695 } 18696 } 18697 18698 /** 18699 * Reconcile all app data for the given user. 18700 * <p> 18701 * Verifies that directories exist and that ownership and labeling is 18702 * correct for all installed apps on all mounted volumes. 18703 */ 18704 void reconcileAppsData(int userId, int flags) { 18705 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18706 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 18707 final String volumeUuid = vol.getFsUuid(); 18708 reconcileAppsData(volumeUuid, userId, flags); 18709 } 18710 } 18711 18712 /** 18713 * Reconcile all app data on given mounted volume. 18714 * <p> 18715 * Destroys app data that isn't expected, either due to uninstallation or 18716 * reinstallation on another volume. 18717 * <p> 18718 * Verifies that directories exist and that ownership and labeling is 18719 * correct for all installed apps. 18720 */ 18721 private void reconcileAppsData(String volumeUuid, int userId, int flags) { 18722 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 18723 + Integer.toHexString(flags)); 18724 18725 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 18726 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 18727 18728 boolean restoreconNeeded = false; 18729 18730 // First look for stale data that doesn't belong, and check if things 18731 // have changed since we did our last restorecon 18732 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18733 if (!isUserKeyUnlocked(userId)) { 18734 throw new RuntimeException( 18735 "Yikes, someone asked us to reconcile CE storage while " + userId 18736 + " was still locked; this would have caused massive data loss!"); 18737 } 18738 18739 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 18740 18741 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 18742 for (File file : files) { 18743 final String packageName = file.getName(); 18744 try { 18745 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 18746 } catch (PackageManagerException e) { 18747 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 18748 synchronized (mInstallLock) { 18749 destroyAppDataLI(volumeUuid, packageName, userId, 18750 StorageManager.FLAG_STORAGE_CE); 18751 } 18752 } 18753 } 18754 } 18755 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 18756 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 18757 18758 final File[] files = FileUtils.listFilesOrEmpty(deDir); 18759 for (File file : files) { 18760 final String packageName = file.getName(); 18761 try { 18762 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 18763 } catch (PackageManagerException e) { 18764 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 18765 synchronized (mInstallLock) { 18766 destroyAppDataLI(volumeUuid, packageName, userId, 18767 StorageManager.FLAG_STORAGE_DE); 18768 } 18769 } 18770 } 18771 } 18772 18773 // Ensure that data directories are ready to roll for all packages 18774 // installed for this volume and user 18775 final List<PackageSetting> packages; 18776 synchronized (mPackages) { 18777 packages = mSettings.getVolumePackagesLPr(volumeUuid); 18778 } 18779 int preparedCount = 0; 18780 for (PackageSetting ps : packages) { 18781 final String packageName = ps.name; 18782 if (ps.pkg == null) { 18783 Slog.w(TAG, "Odd, missing scanned package " + packageName); 18784 // TODO: might be due to legacy ASEC apps; we should circle back 18785 // and reconcile again once they're scanned 18786 continue; 18787 } 18788 18789 if (ps.getInstalled(userId)) { 18790 prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded); 18791 18792 if (maybeMigrateAppData(volumeUuid, userId, ps.pkg)) { 18793 // We may have just shuffled around app data directories, so 18794 // prepare them one more time 18795 prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded); 18796 } 18797 18798 preparedCount++; 18799 } 18800 } 18801 18802 if (restoreconNeeded) { 18803 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18804 SELinuxMMAC.setRestoreconDone(ceDir); 18805 } 18806 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 18807 SELinuxMMAC.setRestoreconDone(deDir); 18808 } 18809 } 18810 18811 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 18812 + " packages; restoreconNeeded was " + restoreconNeeded); 18813 } 18814 18815 /** 18816 * Prepare app data for the given app just after it was installed or 18817 * upgraded. This method carefully only touches users that it's installed 18818 * for, and it forces a restorecon to handle any seinfo changes. 18819 * <p> 18820 * Verifies that directories exist and that ownership and labeling is 18821 * correct for all installed apps. If there is an ownership mismatch, it 18822 * will try recovering system apps by wiping data; third-party app data is 18823 * left intact. 18824 * <p> 18825 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 18826 */ 18827 private void prepareAppDataAfterInstall(PackageParser.Package pkg) { 18828 prepareAppDataAfterInstallInternal(pkg); 18829 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 18830 for (int i = 0; i < childCount; i++) { 18831 PackageParser.Package childPackage = pkg.childPackages.get(i); 18832 prepareAppDataAfterInstallInternal(childPackage); 18833 } 18834 } 18835 18836 private void prepareAppDataAfterInstallInternal(PackageParser.Package pkg) { 18837 final PackageSetting ps; 18838 synchronized (mPackages) { 18839 ps = mSettings.mPackages.get(pkg.packageName); 18840 mSettings.writeKernelMappingLPr(ps); 18841 } 18842 18843 final UserManager um = mContext.getSystemService(UserManager.class); 18844 for (UserInfo user : um.getUsers()) { 18845 final int flags; 18846 if (um.isUserUnlocked(user.id)) { 18847 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18848 } else if (um.isUserRunning(user.id)) { 18849 flags = StorageManager.FLAG_STORAGE_DE; 18850 } else { 18851 continue; 18852 } 18853 18854 if (ps.getInstalled(user.id)) { 18855 // Whenever an app changes, force a restorecon of its data 18856 // TODO: when user data is locked, mark that we're still dirty 18857 prepareAppData(pkg.volumeUuid, user.id, flags, pkg, true); 18858 } 18859 } 18860 } 18861 18862 /** 18863 * Prepare app data for the given app. 18864 * <p> 18865 * Verifies that directories exist and that ownership and labeling is 18866 * correct for all installed apps. If there is an ownership mismatch, this 18867 * will try recovering system apps by wiping data; third-party app data is 18868 * left intact. 18869 */ 18870 private void prepareAppData(String volumeUuid, int userId, int flags, 18871 PackageParser.Package pkg, boolean restoreconNeeded) { 18872 if (DEBUG_APP_DATA) { 18873 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 18874 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 18875 } 18876 18877 final String packageName = pkg.packageName; 18878 final ApplicationInfo app = pkg.applicationInfo; 18879 final int appId = UserHandle.getAppId(app.uid); 18880 18881 Preconditions.checkNotNull(app.seinfo); 18882 18883 synchronized (mInstallLock) { 18884 try { 18885 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 18886 appId, app.seinfo, app.targetSdkVersion); 18887 } catch (InstallerException e) { 18888 if (app.isSystemApp()) { 18889 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 18890 + ", but trying to recover: " + e); 18891 destroyAppDataLI(volumeUuid, packageName, userId, flags); 18892 try { 18893 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 18894 appId, app.seinfo, app.targetSdkVersion); 18895 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 18896 } catch (InstallerException e2) { 18897 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 18898 } 18899 } else { 18900 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 18901 } 18902 } 18903 18904 if (restoreconNeeded) { 18905 restoreconAppDataLI(volumeUuid, packageName, userId, flags, appId, app.seinfo); 18906 } 18907 18908 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18909 // Create a native library symlink only if we have native libraries 18910 // and if the native libraries are 32 bit libraries. We do not provide 18911 // this symlink for 64 bit libraries. 18912 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 18913 final String nativeLibPath = app.nativeLibraryDir; 18914 try { 18915 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 18916 nativeLibPath, userId); 18917 } catch (InstallerException e) { 18918 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 18919 } 18920 } 18921 } 18922 } 18923 } 18924 18925 /** 18926 * For system apps on non-FBE devices, this method migrates any existing 18927 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 18928 * requested by the app. 18929 */ 18930 private boolean maybeMigrateAppData(String volumeUuid, int userId, PackageParser.Package pkg) { 18931 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 18932 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 18933 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 18934 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 18935 synchronized (mInstallLock) { 18936 try { 18937 mInstaller.migrateAppData(volumeUuid, pkg.packageName, userId, storageTarget); 18938 } catch (InstallerException e) { 18939 logCriticalInfo(Log.WARN, 18940 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 18941 } 18942 } 18943 return true; 18944 } else { 18945 return false; 18946 } 18947 } 18948 18949 private void unfreezePackage(String packageName) { 18950 synchronized (mPackages) { 18951 final PackageSetting ps = mSettings.mPackages.get(packageName); 18952 if (ps != null) { 18953 ps.frozen = false; 18954 } 18955 } 18956 } 18957 18958 @Override 18959 public int movePackage(final String packageName, final String volumeUuid) { 18960 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 18961 18962 final int moveId = mNextMoveId.getAndIncrement(); 18963 mHandler.post(new Runnable() { 18964 @Override 18965 public void run() { 18966 try { 18967 movePackageInternal(packageName, volumeUuid, moveId); 18968 } catch (PackageManagerException e) { 18969 Slog.w(TAG, "Failed to move " + packageName, e); 18970 mMoveCallbacks.notifyStatusChanged(moveId, 18971 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 18972 } 18973 } 18974 }); 18975 return moveId; 18976 } 18977 18978 private void movePackageInternal(final String packageName, final String volumeUuid, 18979 final int moveId) throws PackageManagerException { 18980 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 18981 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18982 final PackageManager pm = mContext.getPackageManager(); 18983 18984 final boolean currentAsec; 18985 final String currentVolumeUuid; 18986 final File codeFile; 18987 final String installerPackageName; 18988 final String packageAbiOverride; 18989 final int appId; 18990 final String seinfo; 18991 final String label; 18992 final int targetSdkVersion; 18993 18994 // reader 18995 synchronized (mPackages) { 18996 final PackageParser.Package pkg = mPackages.get(packageName); 18997 final PackageSetting ps = mSettings.mPackages.get(packageName); 18998 if (pkg == null || ps == null) { 18999 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 19000 } 19001 19002 if (pkg.applicationInfo.isSystemApp()) { 19003 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 19004 "Cannot move system application"); 19005 } 19006 19007 if (pkg.applicationInfo.isExternalAsec()) { 19008 currentAsec = true; 19009 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 19010 } else if (pkg.applicationInfo.isForwardLocked()) { 19011 currentAsec = true; 19012 currentVolumeUuid = "forward_locked"; 19013 } else { 19014 currentAsec = false; 19015 currentVolumeUuid = ps.volumeUuid; 19016 19017 final File probe = new File(pkg.codePath); 19018 final File probeOat = new File(probe, "oat"); 19019 if (!probe.isDirectory() || !probeOat.isDirectory()) { 19020 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19021 "Move only supported for modern cluster style installs"); 19022 } 19023 } 19024 19025 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 19026 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19027 "Package already moved to " + volumeUuid); 19028 } 19029 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 19030 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 19031 "Device admin cannot be moved"); 19032 } 19033 19034 if (ps.frozen) { 19035 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 19036 "Failed to move already frozen package"); 19037 } 19038 ps.frozen = true; 19039 19040 codeFile = new File(pkg.codePath); 19041 installerPackageName = ps.installerPackageName; 19042 packageAbiOverride = ps.cpuAbiOverrideString; 19043 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 19044 seinfo = pkg.applicationInfo.seinfo; 19045 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 19046 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 19047 } 19048 19049 // Now that we're guarded by frozen state, kill app during move 19050 final long token = Binder.clearCallingIdentity(); 19051 try { 19052 killApplication(packageName, appId, "move pkg"); 19053 } finally { 19054 Binder.restoreCallingIdentity(token); 19055 } 19056 19057 final Bundle extras = new Bundle(); 19058 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 19059 extras.putString(Intent.EXTRA_TITLE, label); 19060 mMoveCallbacks.notifyCreated(moveId, extras); 19061 19062 int installFlags; 19063 final boolean moveCompleteApp; 19064 final File measurePath; 19065 19066 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 19067 installFlags = INSTALL_INTERNAL; 19068 moveCompleteApp = !currentAsec; 19069 measurePath = Environment.getDataAppDirectory(volumeUuid); 19070 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 19071 installFlags = INSTALL_EXTERNAL; 19072 moveCompleteApp = false; 19073 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 19074 } else { 19075 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 19076 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 19077 || !volume.isMountedWritable()) { 19078 unfreezePackage(packageName); 19079 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19080 "Move location not mounted private volume"); 19081 } 19082 19083 Preconditions.checkState(!currentAsec); 19084 19085 installFlags = INSTALL_INTERNAL; 19086 moveCompleteApp = true; 19087 measurePath = Environment.getDataAppDirectory(volumeUuid); 19088 } 19089 19090 final PackageStats stats = new PackageStats(null, -1); 19091 synchronized (mInstaller) { 19092 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 19093 unfreezePackage(packageName); 19094 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19095 "Failed to measure package size"); 19096 } 19097 } 19098 19099 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 19100 + stats.dataSize); 19101 19102 final long startFreeBytes = measurePath.getFreeSpace(); 19103 final long sizeBytes; 19104 if (moveCompleteApp) { 19105 sizeBytes = stats.codeSize + stats.dataSize; 19106 } else { 19107 sizeBytes = stats.codeSize; 19108 } 19109 19110 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 19111 unfreezePackage(packageName); 19112 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19113 "Not enough free space to move"); 19114 } 19115 19116 mMoveCallbacks.notifyStatusChanged(moveId, 10); 19117 19118 final CountDownLatch installedLatch = new CountDownLatch(1); 19119 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 19120 @Override 19121 public void onUserActionRequired(Intent intent) throws RemoteException { 19122 throw new IllegalStateException(); 19123 } 19124 19125 @Override 19126 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 19127 Bundle extras) throws RemoteException { 19128 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 19129 + PackageManager.installStatusToString(returnCode, msg)); 19130 19131 installedLatch.countDown(); 19132 19133 // Regardless of success or failure of the move operation, 19134 // always unfreeze the package 19135 unfreezePackage(packageName); 19136 19137 final int status = PackageManager.installStatusToPublicStatus(returnCode); 19138 switch (status) { 19139 case PackageInstaller.STATUS_SUCCESS: 19140 mMoveCallbacks.notifyStatusChanged(moveId, 19141 PackageManager.MOVE_SUCCEEDED); 19142 break; 19143 case PackageInstaller.STATUS_FAILURE_STORAGE: 19144 mMoveCallbacks.notifyStatusChanged(moveId, 19145 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 19146 break; 19147 default: 19148 mMoveCallbacks.notifyStatusChanged(moveId, 19149 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19150 break; 19151 } 19152 } 19153 }; 19154 19155 final MoveInfo move; 19156 if (moveCompleteApp) { 19157 // Kick off a thread to report progress estimates 19158 new Thread() { 19159 @Override 19160 public void run() { 19161 while (true) { 19162 try { 19163 if (installedLatch.await(1, TimeUnit.SECONDS)) { 19164 break; 19165 } 19166 } catch (InterruptedException ignored) { 19167 } 19168 19169 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 19170 final int progress = 10 + (int) MathUtils.constrain( 19171 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 19172 mMoveCallbacks.notifyStatusChanged(moveId, progress); 19173 } 19174 } 19175 }.start(); 19176 19177 final String dataAppName = codeFile.getName(); 19178 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 19179 dataAppName, appId, seinfo, targetSdkVersion); 19180 } else { 19181 move = null; 19182 } 19183 19184 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 19185 19186 final Message msg = mHandler.obtainMessage(INIT_COPY); 19187 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 19188 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 19189 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 19190 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/); 19191 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 19192 msg.obj = params; 19193 19194 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 19195 System.identityHashCode(msg.obj)); 19196 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 19197 System.identityHashCode(msg.obj)); 19198 19199 mHandler.sendMessage(msg); 19200 } 19201 19202 @Override 19203 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 19204 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19205 19206 final int realMoveId = mNextMoveId.getAndIncrement(); 19207 final Bundle extras = new Bundle(); 19208 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 19209 mMoveCallbacks.notifyCreated(realMoveId, extras); 19210 19211 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 19212 @Override 19213 public void onCreated(int moveId, Bundle extras) { 19214 // Ignored 19215 } 19216 19217 @Override 19218 public void onStatusChanged(int moveId, int status, long estMillis) { 19219 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 19220 } 19221 }; 19222 19223 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19224 storage.setPrimaryStorageUuid(volumeUuid, callback); 19225 return realMoveId; 19226 } 19227 19228 @Override 19229 public int getMoveStatus(int moveId) { 19230 mContext.enforceCallingOrSelfPermission( 19231 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19232 return mMoveCallbacks.mLastStatus.get(moveId); 19233 } 19234 19235 @Override 19236 public void registerMoveCallback(IPackageMoveObserver callback) { 19237 mContext.enforceCallingOrSelfPermission( 19238 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19239 mMoveCallbacks.register(callback); 19240 } 19241 19242 @Override 19243 public void unregisterMoveCallback(IPackageMoveObserver callback) { 19244 mContext.enforceCallingOrSelfPermission( 19245 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19246 mMoveCallbacks.unregister(callback); 19247 } 19248 19249 @Override 19250 public boolean setInstallLocation(int loc) { 19251 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 19252 null); 19253 if (getInstallLocation() == loc) { 19254 return true; 19255 } 19256 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 19257 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 19258 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 19259 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 19260 return true; 19261 } 19262 return false; 19263 } 19264 19265 @Override 19266 public int getInstallLocation() { 19267 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 19268 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 19269 PackageHelper.APP_INSTALL_AUTO); 19270 } 19271 19272 /** Called by UserManagerService */ 19273 void cleanUpUser(UserManagerService userManager, int userHandle) { 19274 synchronized (mPackages) { 19275 mDirtyUsers.remove(userHandle); 19276 mUserNeedsBadging.delete(userHandle); 19277 mSettings.removeUserLPw(userHandle); 19278 mPendingBroadcasts.remove(userHandle); 19279 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 19280 } 19281 synchronized (mInstallLock) { 19282 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19283 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19284 final String volumeUuid = vol.getFsUuid(); 19285 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 19286 try { 19287 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 19288 } catch (InstallerException e) { 19289 Slog.w(TAG, "Failed to remove user data", e); 19290 } 19291 } 19292 synchronized (mPackages) { 19293 removeUnusedPackagesLILPw(userManager, userHandle); 19294 } 19295 } 19296 } 19297 19298 /** 19299 * We're removing userHandle and would like to remove any downloaded packages 19300 * that are no longer in use by any other user. 19301 * @param userHandle the user being removed 19302 */ 19303 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 19304 final boolean DEBUG_CLEAN_APKS = false; 19305 int [] users = userManager.getUserIds(); 19306 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 19307 while (psit.hasNext()) { 19308 PackageSetting ps = psit.next(); 19309 if (ps.pkg == null) { 19310 continue; 19311 } 19312 final String packageName = ps.pkg.packageName; 19313 // Skip over if system app 19314 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 19315 continue; 19316 } 19317 if (DEBUG_CLEAN_APKS) { 19318 Slog.i(TAG, "Checking package " + packageName); 19319 } 19320 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 19321 if (keep) { 19322 if (DEBUG_CLEAN_APKS) { 19323 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 19324 } 19325 } else { 19326 for (int i = 0; i < users.length; i++) { 19327 if (users[i] != userHandle && ps.getInstalled(users[i])) { 19328 keep = true; 19329 if (DEBUG_CLEAN_APKS) { 19330 Slog.i(TAG, " Keeping package " + packageName + " for user " 19331 + users[i]); 19332 } 19333 break; 19334 } 19335 } 19336 } 19337 if (!keep) { 19338 if (DEBUG_CLEAN_APKS) { 19339 Slog.i(TAG, " Removing package " + packageName); 19340 } 19341 mHandler.post(new Runnable() { 19342 public void run() { 19343 deletePackageX(packageName, userHandle, 0); 19344 } //end run 19345 }); 19346 } 19347 } 19348 } 19349 19350 /** Called by UserManagerService */ 19351 void createNewUser(int userHandle) { 19352 synchronized (mInstallLock) { 19353 try { 19354 mInstaller.createUserConfig(userHandle); 19355 } catch (InstallerException e) { 19356 Slog.w(TAG, "Failed to create user config", e); 19357 } 19358 mSettings.createNewUserLI(this, mInstaller, userHandle); 19359 } 19360 synchronized (mPackages) { 19361 applyFactoryDefaultBrowserLPw(userHandle); 19362 primeDomainVerificationsLPw(userHandle); 19363 } 19364 } 19365 19366 void newUserCreated(final int userHandle) { 19367 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 19368 // If permission review for legacy apps is required, we represent 19369 // dagerous permissions for such apps as always granted runtime 19370 // permissions to keep per user flag state whether review is needed. 19371 // Hence, if a new user is added we have to propagate dangerous 19372 // permission grants for these legacy apps. 19373 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 19374 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 19375 | UPDATE_PERMISSIONS_REPLACE_ALL); 19376 } 19377 } 19378 19379 @Override 19380 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 19381 mContext.enforceCallingOrSelfPermission( 19382 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 19383 "Only package verification agents can read the verifier device identity"); 19384 19385 synchronized (mPackages) { 19386 return mSettings.getVerifierDeviceIdentityLPw(); 19387 } 19388 } 19389 19390 @Override 19391 public void setPermissionEnforced(String permission, boolean enforced) { 19392 // TODO: Now that we no longer change GID for storage, this should to away. 19393 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 19394 "setPermissionEnforced"); 19395 if (READ_EXTERNAL_STORAGE.equals(permission)) { 19396 synchronized (mPackages) { 19397 if (mSettings.mReadExternalStorageEnforced == null 19398 || mSettings.mReadExternalStorageEnforced != enforced) { 19399 mSettings.mReadExternalStorageEnforced = enforced; 19400 mSettings.writeLPr(); 19401 } 19402 } 19403 // kill any non-foreground processes so we restart them and 19404 // grant/revoke the GID. 19405 final IActivityManager am = ActivityManagerNative.getDefault(); 19406 if (am != null) { 19407 final long token = Binder.clearCallingIdentity(); 19408 try { 19409 am.killProcessesBelowForeground("setPermissionEnforcement"); 19410 } catch (RemoteException e) { 19411 } finally { 19412 Binder.restoreCallingIdentity(token); 19413 } 19414 } 19415 } else { 19416 throw new IllegalArgumentException("No selective enforcement for " + permission); 19417 } 19418 } 19419 19420 @Override 19421 @Deprecated 19422 public boolean isPermissionEnforced(String permission) { 19423 return true; 19424 } 19425 19426 @Override 19427 public boolean isStorageLow() { 19428 final long token = Binder.clearCallingIdentity(); 19429 try { 19430 final DeviceStorageMonitorInternal 19431 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 19432 if (dsm != null) { 19433 return dsm.isMemoryLow(); 19434 } else { 19435 return false; 19436 } 19437 } finally { 19438 Binder.restoreCallingIdentity(token); 19439 } 19440 } 19441 19442 @Override 19443 public IPackageInstaller getPackageInstaller() { 19444 return mInstallerService; 19445 } 19446 19447 private boolean userNeedsBadging(int userId) { 19448 int index = mUserNeedsBadging.indexOfKey(userId); 19449 if (index < 0) { 19450 final UserInfo userInfo; 19451 final long token = Binder.clearCallingIdentity(); 19452 try { 19453 userInfo = sUserManager.getUserInfo(userId); 19454 } finally { 19455 Binder.restoreCallingIdentity(token); 19456 } 19457 final boolean b; 19458 if (userInfo != null && userInfo.isManagedProfile()) { 19459 b = true; 19460 } else { 19461 b = false; 19462 } 19463 mUserNeedsBadging.put(userId, b); 19464 return b; 19465 } 19466 return mUserNeedsBadging.valueAt(index); 19467 } 19468 19469 @Override 19470 public KeySet getKeySetByAlias(String packageName, String alias) { 19471 if (packageName == null || alias == null) { 19472 return null; 19473 } 19474 synchronized(mPackages) { 19475 final PackageParser.Package pkg = mPackages.get(packageName); 19476 if (pkg == null) { 19477 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19478 throw new IllegalArgumentException("Unknown package: " + packageName); 19479 } 19480 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19481 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 19482 } 19483 } 19484 19485 @Override 19486 public KeySet getSigningKeySet(String packageName) { 19487 if (packageName == null) { 19488 return null; 19489 } 19490 synchronized(mPackages) { 19491 final PackageParser.Package pkg = mPackages.get(packageName); 19492 if (pkg == null) { 19493 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19494 throw new IllegalArgumentException("Unknown package: " + packageName); 19495 } 19496 if (pkg.applicationInfo.uid != Binder.getCallingUid() 19497 && Process.SYSTEM_UID != Binder.getCallingUid()) { 19498 throw new SecurityException("May not access signing KeySet of other apps."); 19499 } 19500 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19501 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 19502 } 19503 } 19504 19505 @Override 19506 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 19507 if (packageName == null || ks == null) { 19508 return false; 19509 } 19510 synchronized(mPackages) { 19511 final PackageParser.Package pkg = mPackages.get(packageName); 19512 if (pkg == null) { 19513 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19514 throw new IllegalArgumentException("Unknown package: " + packageName); 19515 } 19516 IBinder ksh = ks.getToken(); 19517 if (ksh instanceof KeySetHandle) { 19518 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19519 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 19520 } 19521 return false; 19522 } 19523 } 19524 19525 @Override 19526 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 19527 if (packageName == null || ks == null) { 19528 return false; 19529 } 19530 synchronized(mPackages) { 19531 final PackageParser.Package pkg = mPackages.get(packageName); 19532 if (pkg == null) { 19533 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19534 throw new IllegalArgumentException("Unknown package: " + packageName); 19535 } 19536 IBinder ksh = ks.getToken(); 19537 if (ksh instanceof KeySetHandle) { 19538 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19539 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 19540 } 19541 return false; 19542 } 19543 } 19544 19545 private void deletePackageIfUnusedLPr(final String packageName) { 19546 PackageSetting ps = mSettings.mPackages.get(packageName); 19547 if (ps == null) { 19548 return; 19549 } 19550 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 19551 // TODO Implement atomic delete if package is unused 19552 // It is currently possible that the package will be deleted even if it is installed 19553 // after this method returns. 19554 mHandler.post(new Runnable() { 19555 public void run() { 19556 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 19557 } 19558 }); 19559 } 19560 } 19561 19562 /** 19563 * Check and throw if the given before/after packages would be considered a 19564 * downgrade. 19565 */ 19566 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 19567 throws PackageManagerException { 19568 if (after.versionCode < before.mVersionCode) { 19569 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 19570 "Update version code " + after.versionCode + " is older than current " 19571 + before.mVersionCode); 19572 } else if (after.versionCode == before.mVersionCode) { 19573 if (after.baseRevisionCode < before.baseRevisionCode) { 19574 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 19575 "Update base revision code " + after.baseRevisionCode 19576 + " is older than current " + before.baseRevisionCode); 19577 } 19578 19579 if (!ArrayUtils.isEmpty(after.splitNames)) { 19580 for (int i = 0; i < after.splitNames.length; i++) { 19581 final String splitName = after.splitNames[i]; 19582 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 19583 if (j != -1) { 19584 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 19585 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 19586 "Update split " + splitName + " revision code " 19587 + after.splitRevisionCodes[i] + " is older than current " 19588 + before.splitRevisionCodes[j]); 19589 } 19590 } 19591 } 19592 } 19593 } 19594 } 19595 19596 private static class MoveCallbacks extends Handler { 19597 private static final int MSG_CREATED = 1; 19598 private static final int MSG_STATUS_CHANGED = 2; 19599 19600 private final RemoteCallbackList<IPackageMoveObserver> 19601 mCallbacks = new RemoteCallbackList<>(); 19602 19603 private final SparseIntArray mLastStatus = new SparseIntArray(); 19604 19605 public MoveCallbacks(Looper looper) { 19606 super(looper); 19607 } 19608 19609 public void register(IPackageMoveObserver callback) { 19610 mCallbacks.register(callback); 19611 } 19612 19613 public void unregister(IPackageMoveObserver callback) { 19614 mCallbacks.unregister(callback); 19615 } 19616 19617 @Override 19618 public void handleMessage(Message msg) { 19619 final SomeArgs args = (SomeArgs) msg.obj; 19620 final int n = mCallbacks.beginBroadcast(); 19621 for (int i = 0; i < n; i++) { 19622 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 19623 try { 19624 invokeCallback(callback, msg.what, args); 19625 } catch (RemoteException ignored) { 19626 } 19627 } 19628 mCallbacks.finishBroadcast(); 19629 args.recycle(); 19630 } 19631 19632 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 19633 throws RemoteException { 19634 switch (what) { 19635 case MSG_CREATED: { 19636 callback.onCreated(args.argi1, (Bundle) args.arg2); 19637 break; 19638 } 19639 case MSG_STATUS_CHANGED: { 19640 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 19641 break; 19642 } 19643 } 19644 } 19645 19646 private void notifyCreated(int moveId, Bundle extras) { 19647 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 19648 19649 final SomeArgs args = SomeArgs.obtain(); 19650 args.argi1 = moveId; 19651 args.arg2 = extras; 19652 obtainMessage(MSG_CREATED, args).sendToTarget(); 19653 } 19654 19655 private void notifyStatusChanged(int moveId, int status) { 19656 notifyStatusChanged(moveId, status, -1); 19657 } 19658 19659 private void notifyStatusChanged(int moveId, int status, long estMillis) { 19660 Slog.v(TAG, "Move " + moveId + " status " + status); 19661 19662 final SomeArgs args = SomeArgs.obtain(); 19663 args.argi1 = moveId; 19664 args.argi2 = status; 19665 args.arg3 = estMillis; 19666 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 19667 19668 synchronized (mLastStatus) { 19669 mLastStatus.put(moveId, status); 19670 } 19671 } 19672 } 19673 19674 private final static class OnPermissionChangeListeners extends Handler { 19675 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 19676 19677 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 19678 new RemoteCallbackList<>(); 19679 19680 public OnPermissionChangeListeners(Looper looper) { 19681 super(looper); 19682 } 19683 19684 @Override 19685 public void handleMessage(Message msg) { 19686 switch (msg.what) { 19687 case MSG_ON_PERMISSIONS_CHANGED: { 19688 final int uid = msg.arg1; 19689 handleOnPermissionsChanged(uid); 19690 } break; 19691 } 19692 } 19693 19694 public void addListenerLocked(IOnPermissionsChangeListener listener) { 19695 mPermissionListeners.register(listener); 19696 19697 } 19698 19699 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 19700 mPermissionListeners.unregister(listener); 19701 } 19702 19703 public void onPermissionsChanged(int uid) { 19704 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 19705 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 19706 } 19707 } 19708 19709 private void handleOnPermissionsChanged(int uid) { 19710 final int count = mPermissionListeners.beginBroadcast(); 19711 try { 19712 for (int i = 0; i < count; i++) { 19713 IOnPermissionsChangeListener callback = mPermissionListeners 19714 .getBroadcastItem(i); 19715 try { 19716 callback.onPermissionsChanged(uid); 19717 } catch (RemoteException e) { 19718 Log.e(TAG, "Permission listener is dead", e); 19719 } 19720 } 19721 } finally { 19722 mPermissionListeners.finishBroadcast(); 19723 } 19724 } 19725 } 19726 19727 private class PackageManagerInternalImpl extends PackageManagerInternal { 19728 @Override 19729 public void setLocationPackagesProvider(PackagesProvider provider) { 19730 synchronized (mPackages) { 19731 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 19732 } 19733 } 19734 19735 @Override 19736 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 19737 synchronized (mPackages) { 19738 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 19739 } 19740 } 19741 19742 @Override 19743 public void setSmsAppPackagesProvider(PackagesProvider provider) { 19744 synchronized (mPackages) { 19745 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 19746 } 19747 } 19748 19749 @Override 19750 public void setDialerAppPackagesProvider(PackagesProvider provider) { 19751 synchronized (mPackages) { 19752 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 19753 } 19754 } 19755 19756 @Override 19757 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 19758 synchronized (mPackages) { 19759 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 19760 } 19761 } 19762 19763 @Override 19764 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 19765 synchronized (mPackages) { 19766 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 19767 } 19768 } 19769 19770 @Override 19771 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 19772 synchronized (mPackages) { 19773 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 19774 packageName, userId); 19775 } 19776 } 19777 19778 @Override 19779 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 19780 synchronized (mPackages) { 19781 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 19782 packageName, userId); 19783 } 19784 } 19785 19786 @Override 19787 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 19788 synchronized (mPackages) { 19789 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 19790 packageName, userId); 19791 } 19792 } 19793 19794 @Override 19795 public void setKeepUninstalledPackages(final List<String> packageList) { 19796 Preconditions.checkNotNull(packageList); 19797 List<String> removedFromList = null; 19798 synchronized (mPackages) { 19799 if (mKeepUninstalledPackages != null) { 19800 final int packagesCount = mKeepUninstalledPackages.size(); 19801 for (int i = 0; i < packagesCount; i++) { 19802 String oldPackage = mKeepUninstalledPackages.get(i); 19803 if (packageList != null && packageList.contains(oldPackage)) { 19804 continue; 19805 } 19806 if (removedFromList == null) { 19807 removedFromList = new ArrayList<>(); 19808 } 19809 removedFromList.add(oldPackage); 19810 } 19811 } 19812 mKeepUninstalledPackages = new ArrayList<>(packageList); 19813 if (removedFromList != null) { 19814 final int removedCount = removedFromList.size(); 19815 for (int i = 0; i < removedCount; i++) { 19816 deletePackageIfUnusedLPr(removedFromList.get(i)); 19817 } 19818 } 19819 } 19820 } 19821 19822 @Override 19823 public boolean isPermissionsReviewRequired(String packageName, int userId) { 19824 synchronized (mPackages) { 19825 // If we do not support permission review, done. 19826 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 19827 return false; 19828 } 19829 19830 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 19831 if (packageSetting == null) { 19832 return false; 19833 } 19834 19835 // Permission review applies only to apps not supporting the new permission model. 19836 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 19837 return false; 19838 } 19839 19840 // Legacy apps have the permission and get user consent on launch. 19841 PermissionsState permissionsState = packageSetting.getPermissionsState(); 19842 return permissionsState.isPermissionReviewRequired(userId); 19843 } 19844 } 19845 19846 @Override 19847 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 19848 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 19849 } 19850 19851 @Override 19852 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 19853 int userId) { 19854 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 19855 } 19856 } 19857 19858 @Override 19859 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 19860 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 19861 synchronized (mPackages) { 19862 final long identity = Binder.clearCallingIdentity(); 19863 try { 19864 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 19865 packageNames, userId); 19866 } finally { 19867 Binder.restoreCallingIdentity(identity); 19868 } 19869 } 19870 } 19871 19872 private static void enforceSystemOrPhoneCaller(String tag) { 19873 int callingUid = Binder.getCallingUid(); 19874 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 19875 throw new SecurityException( 19876 "Cannot call " + tag + " from UID " + callingUid); 19877 } 19878 } 19879 19880 boolean isHistoricalPackageUsageAvailable() { 19881 return mPackageUsage.isHistoricalPackageUsageAvailable(); 19882 } 19883 19884 /** 19885 * Return a <b>copy</b> of the collection of packages known to the package manager. 19886 * @return A copy of the values of mPackages. 19887 */ 19888 Collection<PackageParser.Package> getPackages() { 19889 synchronized (mPackages) { 19890 return new ArrayList<>(mPackages.values()); 19891 } 19892 } 19893 19894 /** 19895 * Logs process start information (including base APK hash) to the security log. 19896 * @hide 19897 */ 19898 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 19899 String apkFile, int pid) { 19900 if (!SecurityLog.isLoggingEnabled()) { 19901 return; 19902 } 19903 Bundle data = new Bundle(); 19904 data.putLong("startTimestamp", System.currentTimeMillis()); 19905 data.putString("processName", processName); 19906 data.putInt("uid", uid); 19907 data.putString("seinfo", seinfo); 19908 data.putString("apkFile", apkFile); 19909 data.putInt("pid", pid); 19910 Message msg = mProcessLoggingHandler.obtainMessage( 19911 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 19912 msg.setData(data); 19913 mProcessLoggingHandler.sendMessage(msg); 19914 } 19915} 19916