PackageManagerService.java revision ad14b884f4110e03ec7b5ba7b913be25d19aa95c
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; 21import static android.Manifest.permission.WRITE_MEDIA_STORAGE; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 27import static android.content.pm.PackageManager.DELETE_KEEP_DATA; 28import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 29import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED; 30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 31import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 32import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 34import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET; 35import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 36import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 37import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 38import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 40import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 41import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 42import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 43import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 44import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 45import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 46import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 47import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 48import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 49import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 50import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 51import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 52import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 53import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 54import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 55import static android.content.pm.PackageManager.INSTALL_INTERNAL; 56import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK; 59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 62import static android.content.pm.PackageManager.MATCH_ALL; 63import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 64import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE; 65import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE; 66import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS; 67import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY; 68import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY; 69import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 70import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN; 71import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 72import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 73import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 74import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 75import static android.content.pm.PackageManager.PERMISSION_DENIED; 76import static android.content.pm.PackageManager.PERMISSION_GRANTED; 77import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED; 78import static android.content.pm.PackageParser.isApkFile; 79import static android.os.Process.PACKAGE_INFO_GID; 80import static android.os.Process.SYSTEM_UID; 81import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 82import static android.system.OsConstants.O_CREAT; 83import static android.system.OsConstants.O_RDWR; 84 85import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 86import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 87import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 88import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 89import static com.android.internal.util.ArrayUtils.appendInt; 90import static com.android.server.pm.Installer.DEXOPT_PUBLIC; 91import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 92import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 93import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 94import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 95import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 96import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason; 97import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter; 98import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 99import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 100import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 101 102import android.Manifest; 103import android.annotation.NonNull; 104import android.annotation.Nullable; 105import android.app.ActivityManager; 106import android.app.ActivityManagerNative; 107import android.app.IActivityManager; 108import android.app.admin.DevicePolicyManagerInternal; 109import android.app.admin.IDevicePolicyManager; 110import android.app.admin.SecurityLog; 111import android.app.backup.IBackupManager; 112import android.content.BroadcastReceiver; 113import android.content.ComponentName; 114import android.content.Context; 115import android.content.IIntentReceiver; 116import android.content.Intent; 117import android.content.IntentFilter; 118import android.content.IntentSender; 119import android.content.IntentSender.SendIntentException; 120import android.content.ServiceConnection; 121import android.content.pm.ActivityInfo; 122import android.content.pm.ApplicationInfo; 123import android.content.pm.AppsQueryHelper; 124import android.content.pm.ComponentInfo; 125import android.content.pm.EphemeralApplicationInfo; 126import android.content.pm.EphemeralResolveInfo; 127import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo; 128import android.content.pm.FeatureInfo; 129import android.content.pm.IOnPermissionsChangeListener; 130import android.content.pm.IPackageDataObserver; 131import android.content.pm.IPackageDeleteObserver; 132import android.content.pm.IPackageDeleteObserver2; 133import android.content.pm.IPackageInstallObserver2; 134import android.content.pm.IPackageInstaller; 135import android.content.pm.IPackageManager; 136import android.content.pm.IPackageMoveObserver; 137import android.content.pm.IPackageStatsObserver; 138import android.content.pm.InstrumentationInfo; 139import android.content.pm.IntentFilterVerificationInfo; 140import android.content.pm.KeySet; 141import android.content.pm.PackageCleanItem; 142import android.content.pm.PackageInfo; 143import android.content.pm.PackageInfoLite; 144import android.content.pm.PackageInstaller; 145import android.content.pm.PackageManager; 146import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 147import android.content.pm.PackageManagerInternal; 148import android.content.pm.PackageParser; 149import android.content.pm.PackageParser.ActivityIntentInfo; 150import android.content.pm.PackageParser.PackageLite; 151import android.content.pm.PackageParser.PackageParserException; 152import android.content.pm.PackageStats; 153import android.content.pm.PackageUserState; 154import android.content.pm.ParceledListSlice; 155import android.content.pm.PermissionGroupInfo; 156import android.content.pm.PermissionInfo; 157import android.content.pm.ProviderInfo; 158import android.content.pm.ResolveInfo; 159import android.content.pm.ServiceInfo; 160import android.content.pm.Signature; 161import android.content.pm.UserInfo; 162import android.content.pm.VerifierDeviceIdentity; 163import android.content.pm.VerifierInfo; 164import android.content.res.Resources; 165import android.graphics.Bitmap; 166import android.hardware.display.DisplayManager; 167import android.net.Uri; 168import android.os.Binder; 169import android.os.Build; 170import android.os.Bundle; 171import android.os.Debug; 172import android.os.Environment; 173import android.os.Environment.UserEnvironment; 174import android.os.FileUtils; 175import android.os.Handler; 176import android.os.IBinder; 177import android.os.Looper; 178import android.os.Message; 179import android.os.Parcel; 180import android.os.ParcelFileDescriptor; 181import android.os.Process; 182import android.os.RemoteCallbackList; 183import android.os.RemoteException; 184import android.os.ResultReceiver; 185import android.os.SELinux; 186import android.os.ServiceManager; 187import android.os.SystemClock; 188import android.os.SystemProperties; 189import android.os.Trace; 190import android.os.UserHandle; 191import android.os.UserManager; 192import android.os.storage.IMountService; 193import android.os.storage.MountServiceInternal; 194import android.os.storage.StorageEventListener; 195import android.os.storage.StorageManager; 196import android.os.storage.VolumeInfo; 197import android.os.storage.VolumeRecord; 198import android.security.KeyStore; 199import android.security.SystemKeyStore; 200import android.system.ErrnoException; 201import android.system.Os; 202import android.text.TextUtils; 203import android.text.format.DateUtils; 204import android.util.ArrayMap; 205import android.util.ArraySet; 206import android.util.AtomicFile; 207import android.util.DisplayMetrics; 208import android.util.EventLog; 209import android.util.ExceptionUtils; 210import android.util.Log; 211import android.util.LogPrinter; 212import android.util.MathUtils; 213import android.util.PrintStreamPrinter; 214import android.util.Slog; 215import android.util.SparseArray; 216import android.util.SparseBooleanArray; 217import android.util.SparseIntArray; 218import android.util.Xml; 219import android.view.Display; 220 221import com.android.internal.R; 222import com.android.internal.annotations.GuardedBy; 223import com.android.internal.app.IMediaContainerService; 224import com.android.internal.app.ResolverActivity; 225import com.android.internal.content.NativeLibraryHelper; 226import com.android.internal.content.PackageHelper; 227import com.android.internal.os.IParcelFileDescriptorFactory; 228import com.android.internal.os.InstallerConnection.InstallerException; 229import com.android.internal.os.SomeArgs; 230import com.android.internal.os.Zygote; 231import com.android.internal.telephony.CarrierAppUtils; 232import com.android.internal.util.ArrayUtils; 233import com.android.internal.util.FastPrintWriter; 234import com.android.internal.util.FastXmlSerializer; 235import com.android.internal.util.IndentingPrintWriter; 236import com.android.internal.util.Preconditions; 237import com.android.internal.util.XmlUtils; 238import com.android.server.EventLogTags; 239import com.android.server.FgThread; 240import com.android.server.IntentResolver; 241import com.android.server.LocalServices; 242import com.android.server.ServiceThread; 243import com.android.server.SystemConfig; 244import com.android.server.Watchdog; 245import com.android.server.pm.PermissionsState.PermissionState; 246import com.android.server.pm.Settings.DatabaseVersion; 247import com.android.server.pm.Settings.VersionInfo; 248import com.android.server.storage.DeviceStorageMonitorInternal; 249 250import dalvik.system.CloseGuard; 251import dalvik.system.DexFile; 252import dalvik.system.VMRuntime; 253 254import libcore.io.IoUtils; 255import libcore.util.EmptyArray; 256 257import org.xmlpull.v1.XmlPullParser; 258import org.xmlpull.v1.XmlPullParserException; 259import org.xmlpull.v1.XmlSerializer; 260 261import java.io.BufferedInputStream; 262import java.io.BufferedOutputStream; 263import java.io.BufferedReader; 264import java.io.ByteArrayInputStream; 265import java.io.ByteArrayOutputStream; 266import java.io.File; 267import java.io.FileDescriptor; 268import java.io.FileNotFoundException; 269import java.io.FileOutputStream; 270import java.io.FileReader; 271import java.io.FilenameFilter; 272import java.io.IOException; 273import java.io.InputStream; 274import java.io.PrintWriter; 275import java.nio.charset.StandardCharsets; 276import java.security.MessageDigest; 277import java.security.NoSuchAlgorithmException; 278import java.security.PublicKey; 279import java.security.cert.Certificate; 280import java.security.cert.CertificateEncodingException; 281import java.security.cert.CertificateException; 282import java.text.SimpleDateFormat; 283import java.util.ArrayList; 284import java.util.Arrays; 285import java.util.Collection; 286import java.util.Collections; 287import java.util.Comparator; 288import java.util.Date; 289import java.util.HashSet; 290import java.util.Iterator; 291import java.util.List; 292import java.util.Map; 293import java.util.Objects; 294import java.util.Set; 295import java.util.concurrent.CountDownLatch; 296import java.util.concurrent.TimeUnit; 297import java.util.concurrent.atomic.AtomicBoolean; 298import java.util.concurrent.atomic.AtomicInteger; 299import java.util.concurrent.atomic.AtomicLong; 300 301/** 302 * Keep track of all those APKs everywhere. 303 * <p> 304 * Internally there are two important locks: 305 * <ul> 306 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 307 * and other related state. It is a fine-grained lock that should only be held 308 * momentarily, as it's one of the most contended locks in the system. 309 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 310 * operations typically involve heavy lifting of application data on disk. Since 311 * {@code installd} is single-threaded, and it's operations can often be slow, 312 * this lock should never be acquired while already holding {@link #mPackages}. 313 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 314 * holding {@link #mInstallLock}. 315 * </ul> 316 * Many internal methods rely on the caller to hold the appropriate locks, and 317 * this contract is expressed through method name suffixes: 318 * <ul> 319 * <li>fooLI(): the caller must hold {@link #mInstallLock} 320 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 321 * being modified must be frozen 322 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 323 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 324 * </ul> 325 * <p> 326 * Because this class is very central to the platform's security; please run all 327 * CTS and unit tests whenever making modifications: 328 * 329 * <pre> 330 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 331 * $ cts-tradefed run commandAndExit cts -m AppSecurityTests 332 * </pre> 333 */ 334public class PackageManagerService extends IPackageManager.Stub { 335 static final String TAG = "PackageManager"; 336 static final boolean DEBUG_SETTINGS = false; 337 static final boolean DEBUG_PREFERRED = false; 338 static final boolean DEBUG_UPGRADE = false; 339 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 340 private static final boolean DEBUG_BACKUP = false; 341 private static final boolean DEBUG_INSTALL = false; 342 private static final boolean DEBUG_REMOVE = false; 343 private static final boolean DEBUG_BROADCASTS = false; 344 private static final boolean DEBUG_SHOW_INFO = false; 345 private static final boolean DEBUG_PACKAGE_INFO = false; 346 private static final boolean DEBUG_INTENT_MATCHING = false; 347 private static final boolean DEBUG_PACKAGE_SCANNING = false; 348 private static final boolean DEBUG_VERIFY = false; 349 private static final boolean DEBUG_FILTERS = false; 350 351 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 352 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 353 // user, but by default initialize to this. 354 static final boolean DEBUG_DEXOPT = false; 355 356 private static final boolean DEBUG_ABI_SELECTION = false; 357 private static final boolean DEBUG_EPHEMERAL = false; 358 private static final boolean DEBUG_TRIAGED_MISSING = false; 359 private static final boolean DEBUG_APP_DATA = false; 360 361 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 362 363 private static final boolean DISABLE_EPHEMERAL_APPS = true; 364 365 private static final int RADIO_UID = Process.PHONE_UID; 366 private static final int LOG_UID = Process.LOG_UID; 367 private static final int NFC_UID = Process.NFC_UID; 368 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 369 private static final int SHELL_UID = Process.SHELL_UID; 370 371 // Cap the size of permission trees that 3rd party apps can define 372 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 373 374 // Suffix used during package installation when copying/moving 375 // package apks to install directory. 376 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 377 378 static final int SCAN_NO_DEX = 1<<1; 379 static final int SCAN_FORCE_DEX = 1<<2; 380 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 381 static final int SCAN_NEW_INSTALL = 1<<4; 382 static final int SCAN_NO_PATHS = 1<<5; 383 static final int SCAN_UPDATE_TIME = 1<<6; 384 static final int SCAN_DEFER_DEX = 1<<7; 385 static final int SCAN_BOOTING = 1<<8; 386 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 387 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 388 static final int SCAN_REPLACING = 1<<11; 389 static final int SCAN_REQUIRE_KNOWN = 1<<12; 390 static final int SCAN_MOVE = 1<<13; 391 static final int SCAN_INITIAL = 1<<14; 392 static final int SCAN_CHECK_ONLY = 1<<15; 393 static final int SCAN_DONT_KILL_APP = 1<<17; 394 static final int SCAN_IGNORE_FROZEN = 1<<18; 395 396 static final int REMOVE_CHATTY = 1<<16; 397 398 private static final int[] EMPTY_INT_ARRAY = new int[0]; 399 400 /** 401 * Timeout (in milliseconds) after which the watchdog should declare that 402 * our handler thread is wedged. The usual default for such things is one 403 * minute but we sometimes do very lengthy I/O operations on this thread, 404 * such as installing multi-gigabyte applications, so ours needs to be longer. 405 */ 406 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 407 408 /** 409 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 410 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 411 * settings entry if available, otherwise we use the hardcoded default. If it's been 412 * more than this long since the last fstrim, we force one during the boot sequence. 413 * 414 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 415 * one gets run at the next available charging+idle time. This final mandatory 416 * no-fstrim check kicks in only of the other scheduling criteria is never met. 417 */ 418 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 419 420 /** 421 * Whether verification is enabled by default. 422 */ 423 private static final boolean DEFAULT_VERIFY_ENABLE = true; 424 425 /** 426 * The default maximum time to wait for the verification agent to return in 427 * milliseconds. 428 */ 429 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 430 431 /** 432 * The default response for package verification timeout. 433 * 434 * This can be either PackageManager.VERIFICATION_ALLOW or 435 * PackageManager.VERIFICATION_REJECT. 436 */ 437 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 438 439 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 440 441 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 442 DEFAULT_CONTAINER_PACKAGE, 443 "com.android.defcontainer.DefaultContainerService"); 444 445 private static final String KILL_APP_REASON_GIDS_CHANGED = 446 "permission grant or revoke changed gids"; 447 448 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 449 "permissions revoked"; 450 451 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 452 453 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 454 455 /** Permission grant: not grant the permission. */ 456 private static final int GRANT_DENIED = 1; 457 458 /** Permission grant: grant the permission as an install permission. */ 459 private static final int GRANT_INSTALL = 2; 460 461 /** Permission grant: grant the permission as a runtime one. */ 462 private static final int GRANT_RUNTIME = 3; 463 464 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 465 private static final int GRANT_UPGRADE = 4; 466 467 /** Canonical intent used to identify what counts as a "web browser" app */ 468 private static final Intent sBrowserIntent; 469 static { 470 sBrowserIntent = new Intent(); 471 sBrowserIntent.setAction(Intent.ACTION_VIEW); 472 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 473 sBrowserIntent.setData(Uri.parse("http:")); 474 } 475 476 /** 477 * The set of all protected actions [i.e. those actions for which a high priority 478 * intent filter is disallowed]. 479 */ 480 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 481 static { 482 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 483 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 484 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 485 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 486 } 487 488 // Compilation reasons. 489 public static final int REASON_FIRST_BOOT = 0; 490 public static final int REASON_BOOT = 1; 491 public static final int REASON_INSTALL = 2; 492 public static final int REASON_BACKGROUND_DEXOPT = 3; 493 public static final int REASON_AB_OTA = 4; 494 public static final int REASON_NON_SYSTEM_LIBRARY = 5; 495 public static final int REASON_SHARED_APK = 6; 496 public static final int REASON_FORCED_DEXOPT = 7; 497 498 public static final int REASON_LAST = REASON_FORCED_DEXOPT; 499 500 final ServiceThread mHandlerThread; 501 502 final PackageHandler mHandler; 503 504 private final ProcessLoggingHandler mProcessLoggingHandler; 505 506 /** 507 * Messages for {@link #mHandler} that need to wait for system ready before 508 * being dispatched. 509 */ 510 private ArrayList<Message> mPostSystemReadyMessages; 511 512 final int mSdkVersion = Build.VERSION.SDK_INT; 513 514 final Context mContext; 515 final boolean mFactoryTest; 516 final boolean mOnlyCore; 517 final DisplayMetrics mMetrics; 518 final int mDefParseFlags; 519 final String[] mSeparateProcesses; 520 final boolean mIsUpgrade; 521 final boolean mIsPreNUpgrade; 522 523 /** The location for ASEC container files on internal storage. */ 524 final String mAsecInternalPath; 525 526 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 527 // LOCK HELD. Can be called with mInstallLock held. 528 @GuardedBy("mInstallLock") 529 final Installer mInstaller; 530 531 /** Directory where installed third-party apps stored */ 532 final File mAppInstallDir; 533 final File mEphemeralInstallDir; 534 535 /** 536 * Directory to which applications installed internally have their 537 * 32 bit native libraries copied. 538 */ 539 private File mAppLib32InstallDir; 540 541 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 542 // apps. 543 final File mDrmAppPrivateInstallDir; 544 545 // ---------------------------------------------------------------- 546 547 // Lock for state used when installing and doing other long running 548 // operations. Methods that must be called with this lock held have 549 // the suffix "LI". 550 final Object mInstallLock = new Object(); 551 552 // ---------------------------------------------------------------- 553 554 // Keys are String (package name), values are Package. This also serves 555 // as the lock for the global state. Methods that must be called with 556 // this lock held have the prefix "LP". 557 @GuardedBy("mPackages") 558 final ArrayMap<String, PackageParser.Package> mPackages = 559 new ArrayMap<String, PackageParser.Package>(); 560 561 final ArrayMap<String, Set<String>> mKnownCodebase = 562 new ArrayMap<String, Set<String>>(); 563 564 // Tracks available target package names -> overlay package paths. 565 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 566 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 567 568 /** 569 * Tracks new system packages [received in an OTA] that we expect to 570 * find updated user-installed versions. Keys are package name, values 571 * are package location. 572 */ 573 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 574 /** 575 * Tracks high priority intent filters for protected actions. During boot, certain 576 * filter actions are protected and should never be allowed to have a high priority 577 * intent filter for them. However, there is one, and only one exception -- the 578 * setup wizard. It must be able to define a high priority intent filter for these 579 * actions to ensure there are no escapes from the wizard. We need to delay processing 580 * of these during boot as we need to look at all of the system packages in order 581 * to know which component is the setup wizard. 582 */ 583 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 584 /** 585 * Whether or not processing protected filters should be deferred. 586 */ 587 private boolean mDeferProtectedFilters = true; 588 589 /** 590 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 591 */ 592 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 593 /** 594 * Whether or not system app permissions should be promoted from install to runtime. 595 */ 596 boolean mPromoteSystemApps; 597 598 @GuardedBy("mPackages") 599 final Settings mSettings; 600 601 /** 602 * Set of package names that are currently "frozen", which means active 603 * surgery is being done on the code/data for that package. The platform 604 * will refuse to launch frozen packages to avoid race conditions. 605 * 606 * @see PackageFreezer 607 */ 608 @GuardedBy("mPackages") 609 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 610 611 boolean mRestoredSettings; 612 613 // System configuration read by SystemConfig. 614 final int[] mGlobalGids; 615 final SparseArray<ArraySet<String>> mSystemPermissions; 616 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 617 618 // If mac_permissions.xml was found for seinfo labeling. 619 boolean mFoundPolicyFile; 620 621 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 622 623 public static final class SharedLibraryEntry { 624 public final String path; 625 public final String apk; 626 627 SharedLibraryEntry(String _path, String _apk) { 628 path = _path; 629 apk = _apk; 630 } 631 } 632 633 // Currently known shared libraries. 634 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 635 new ArrayMap<String, SharedLibraryEntry>(); 636 637 // All available activities, for your resolving pleasure. 638 final ActivityIntentResolver mActivities = 639 new ActivityIntentResolver(); 640 641 // All available receivers, for your resolving pleasure. 642 final ActivityIntentResolver mReceivers = 643 new ActivityIntentResolver(); 644 645 // All available services, for your resolving pleasure. 646 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 647 648 // All available providers, for your resolving pleasure. 649 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 650 651 // Mapping from provider base names (first directory in content URI codePath) 652 // to the provider information. 653 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 654 new ArrayMap<String, PackageParser.Provider>(); 655 656 // Mapping from instrumentation class names to info about them. 657 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 658 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 659 660 // Mapping from permission names to info about them. 661 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 662 new ArrayMap<String, PackageParser.PermissionGroup>(); 663 664 // Packages whose data we have transfered into another package, thus 665 // should no longer exist. 666 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 667 668 // Broadcast actions that are only available to the system. 669 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 670 671 /** List of packages waiting for verification. */ 672 final SparseArray<PackageVerificationState> mPendingVerification 673 = new SparseArray<PackageVerificationState>(); 674 675 /** Set of packages associated with each app op permission. */ 676 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 677 678 final PackageInstallerService mInstallerService; 679 680 private final PackageDexOptimizer mPackageDexOptimizer; 681 682 private AtomicInteger mNextMoveId = new AtomicInteger(); 683 private final MoveCallbacks mMoveCallbacks; 684 685 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 686 687 // Cache of users who need badging. 688 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 689 690 /** Token for keys in mPendingVerification. */ 691 private int mPendingVerificationToken = 0; 692 693 volatile boolean mSystemReady; 694 volatile boolean mSafeMode; 695 volatile boolean mHasSystemUidErrors; 696 697 ApplicationInfo mAndroidApplication; 698 final ActivityInfo mResolveActivity = new ActivityInfo(); 699 final ResolveInfo mResolveInfo = new ResolveInfo(); 700 ComponentName mResolveComponentName; 701 PackageParser.Package mPlatformPackage; 702 ComponentName mCustomResolverComponentName; 703 704 boolean mResolverReplaced = false; 705 706 private final @Nullable ComponentName mIntentFilterVerifierComponent; 707 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 708 709 private int mIntentFilterVerificationToken = 0; 710 711 /** Component that knows whether or not an ephemeral application exists */ 712 final ComponentName mEphemeralResolverComponent; 713 /** The service connection to the ephemeral resolver */ 714 final EphemeralResolverConnection mEphemeralResolverConnection; 715 716 /** Component used to install ephemeral applications */ 717 final ComponentName mEphemeralInstallerComponent; 718 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 719 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 720 721 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 722 = new SparseArray<IntentFilterVerificationState>(); 723 724 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 725 new DefaultPermissionGrantPolicy(this); 726 727 // List of packages names to keep cached, even if they are uninstalled for all users 728 private List<String> mKeepUninstalledPackages; 729 730 private static class IFVerificationParams { 731 PackageParser.Package pkg; 732 boolean replacing; 733 int userId; 734 int verifierUid; 735 736 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 737 int _userId, int _verifierUid) { 738 pkg = _pkg; 739 replacing = _replacing; 740 userId = _userId; 741 replacing = _replacing; 742 verifierUid = _verifierUid; 743 } 744 } 745 746 private interface IntentFilterVerifier<T extends IntentFilter> { 747 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 748 T filter, String packageName); 749 void startVerifications(int userId); 750 void receiveVerificationResponse(int verificationId); 751 } 752 753 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 754 private Context mContext; 755 private ComponentName mIntentFilterVerifierComponent; 756 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 757 758 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 759 mContext = context; 760 mIntentFilterVerifierComponent = verifierComponent; 761 } 762 763 private String getDefaultScheme() { 764 return IntentFilter.SCHEME_HTTPS; 765 } 766 767 @Override 768 public void startVerifications(int userId) { 769 // Launch verifications requests 770 int count = mCurrentIntentFilterVerifications.size(); 771 for (int n=0; n<count; n++) { 772 int verificationId = mCurrentIntentFilterVerifications.get(n); 773 final IntentFilterVerificationState ivs = 774 mIntentFilterVerificationStates.get(verificationId); 775 776 String packageName = ivs.getPackageName(); 777 778 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 779 final int filterCount = filters.size(); 780 ArraySet<String> domainsSet = new ArraySet<>(); 781 for (int m=0; m<filterCount; m++) { 782 PackageParser.ActivityIntentInfo filter = filters.get(m); 783 domainsSet.addAll(filter.getHostsList()); 784 } 785 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 786 synchronized (mPackages) { 787 if (mSettings.createIntentFilterVerificationIfNeededLPw( 788 packageName, domainsList) != null) { 789 scheduleWriteSettingsLocked(); 790 } 791 } 792 sendVerificationRequest(userId, verificationId, ivs); 793 } 794 mCurrentIntentFilterVerifications.clear(); 795 } 796 797 private void sendVerificationRequest(int userId, int verificationId, 798 IntentFilterVerificationState ivs) { 799 800 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 801 verificationIntent.putExtra( 802 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 803 verificationId); 804 verificationIntent.putExtra( 805 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 806 getDefaultScheme()); 807 verificationIntent.putExtra( 808 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 809 ivs.getHostsString()); 810 verificationIntent.putExtra( 811 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 812 ivs.getPackageName()); 813 verificationIntent.setComponent(mIntentFilterVerifierComponent); 814 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 815 816 UserHandle user = new UserHandle(userId); 817 mContext.sendBroadcastAsUser(verificationIntent, user); 818 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 819 "Sending IntentFilter verification broadcast"); 820 } 821 822 public void receiveVerificationResponse(int verificationId) { 823 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 824 825 final boolean verified = ivs.isVerified(); 826 827 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 828 final int count = filters.size(); 829 if (DEBUG_DOMAIN_VERIFICATION) { 830 Slog.i(TAG, "Received verification response " + verificationId 831 + " for " + count + " filters, verified=" + verified); 832 } 833 for (int n=0; n<count; n++) { 834 PackageParser.ActivityIntentInfo filter = filters.get(n); 835 filter.setVerified(verified); 836 837 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 838 + " verified with result:" + verified + " and hosts:" 839 + ivs.getHostsString()); 840 } 841 842 mIntentFilterVerificationStates.remove(verificationId); 843 844 final String packageName = ivs.getPackageName(); 845 IntentFilterVerificationInfo ivi = null; 846 847 synchronized (mPackages) { 848 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 849 } 850 if (ivi == null) { 851 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 852 + verificationId + " packageName:" + packageName); 853 return; 854 } 855 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 856 "Updating IntentFilterVerificationInfo for package " + packageName 857 +" verificationId:" + verificationId); 858 859 synchronized (mPackages) { 860 if (verified) { 861 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 862 } else { 863 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 864 } 865 scheduleWriteSettingsLocked(); 866 867 final int userId = ivs.getUserId(); 868 if (userId != UserHandle.USER_ALL) { 869 final int userStatus = 870 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 871 872 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 873 boolean needUpdate = false; 874 875 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 876 // already been set by the User thru the Disambiguation dialog 877 switch (userStatus) { 878 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 879 if (verified) { 880 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 881 } else { 882 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 883 } 884 needUpdate = true; 885 break; 886 887 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 888 if (verified) { 889 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 890 needUpdate = true; 891 } 892 break; 893 894 default: 895 // Nothing to do 896 } 897 898 if (needUpdate) { 899 mSettings.updateIntentFilterVerificationStatusLPw( 900 packageName, updatedStatus, userId); 901 scheduleWritePackageRestrictionsLocked(userId); 902 } 903 } 904 } 905 } 906 907 @Override 908 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 909 ActivityIntentInfo filter, String packageName) { 910 if (!hasValidDomains(filter)) { 911 return false; 912 } 913 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 914 if (ivs == null) { 915 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 916 packageName); 917 } 918 if (DEBUG_DOMAIN_VERIFICATION) { 919 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 920 } 921 ivs.addFilter(filter); 922 return true; 923 } 924 925 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 926 int userId, int verificationId, String packageName) { 927 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 928 verifierUid, userId, packageName); 929 ivs.setPendingState(); 930 synchronized (mPackages) { 931 mIntentFilterVerificationStates.append(verificationId, ivs); 932 mCurrentIntentFilterVerifications.add(verificationId); 933 } 934 return ivs; 935 } 936 } 937 938 private static boolean hasValidDomains(ActivityIntentInfo filter) { 939 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 940 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 941 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 942 } 943 944 // Set of pending broadcasts for aggregating enable/disable of components. 945 static class PendingPackageBroadcasts { 946 // for each user id, a map of <package name -> components within that package> 947 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 948 949 public PendingPackageBroadcasts() { 950 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 951 } 952 953 public ArrayList<String> get(int userId, String packageName) { 954 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 955 return packages.get(packageName); 956 } 957 958 public void put(int userId, String packageName, ArrayList<String> components) { 959 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 960 packages.put(packageName, components); 961 } 962 963 public void remove(int userId, String packageName) { 964 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 965 if (packages != null) { 966 packages.remove(packageName); 967 } 968 } 969 970 public void remove(int userId) { 971 mUidMap.remove(userId); 972 } 973 974 public int userIdCount() { 975 return mUidMap.size(); 976 } 977 978 public int userIdAt(int n) { 979 return mUidMap.keyAt(n); 980 } 981 982 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 983 return mUidMap.get(userId); 984 } 985 986 public int size() { 987 // total number of pending broadcast entries across all userIds 988 int num = 0; 989 for (int i = 0; i< mUidMap.size(); i++) { 990 num += mUidMap.valueAt(i).size(); 991 } 992 return num; 993 } 994 995 public void clear() { 996 mUidMap.clear(); 997 } 998 999 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1000 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1001 if (map == null) { 1002 map = new ArrayMap<String, ArrayList<String>>(); 1003 mUidMap.put(userId, map); 1004 } 1005 return map; 1006 } 1007 } 1008 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1009 1010 // Service Connection to remote media container service to copy 1011 // package uri's from external media onto secure containers 1012 // or internal storage. 1013 private IMediaContainerService mContainerService = null; 1014 1015 static final int SEND_PENDING_BROADCAST = 1; 1016 static final int MCS_BOUND = 3; 1017 static final int END_COPY = 4; 1018 static final int INIT_COPY = 5; 1019 static final int MCS_UNBIND = 6; 1020 static final int START_CLEANING_PACKAGE = 7; 1021 static final int FIND_INSTALL_LOC = 8; 1022 static final int POST_INSTALL = 9; 1023 static final int MCS_RECONNECT = 10; 1024 static final int MCS_GIVE_UP = 11; 1025 static final int UPDATED_MEDIA_STATUS = 12; 1026 static final int WRITE_SETTINGS = 13; 1027 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1028 static final int PACKAGE_VERIFIED = 15; 1029 static final int CHECK_PENDING_VERIFICATION = 16; 1030 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1031 static final int INTENT_FILTER_VERIFIED = 18; 1032 1033 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1034 1035 // Delay time in millisecs 1036 static final int BROADCAST_DELAY = 10 * 1000; 1037 1038 static UserManagerService sUserManager; 1039 1040 // Stores a list of users whose package restrictions file needs to be updated 1041 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1042 1043 final private DefaultContainerConnection mDefContainerConn = 1044 new DefaultContainerConnection(); 1045 class DefaultContainerConnection implements ServiceConnection { 1046 public void onServiceConnected(ComponentName name, IBinder service) { 1047 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1048 IMediaContainerService imcs = 1049 IMediaContainerService.Stub.asInterface(service); 1050 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1051 } 1052 1053 public void onServiceDisconnected(ComponentName name) { 1054 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1055 } 1056 } 1057 1058 // Recordkeeping of restore-after-install operations that are currently in flight 1059 // between the Package Manager and the Backup Manager 1060 static class PostInstallData { 1061 public InstallArgs args; 1062 public PackageInstalledInfo res; 1063 1064 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1065 args = _a; 1066 res = _r; 1067 } 1068 } 1069 1070 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1071 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1072 1073 // XML tags for backup/restore of various bits of state 1074 private static final String TAG_PREFERRED_BACKUP = "pa"; 1075 private static final String TAG_DEFAULT_APPS = "da"; 1076 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1077 1078 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1079 private static final String TAG_ALL_GRANTS = "rt-grants"; 1080 private static final String TAG_GRANT = "grant"; 1081 private static final String ATTR_PACKAGE_NAME = "pkg"; 1082 1083 private static final String TAG_PERMISSION = "perm"; 1084 private static final String ATTR_PERMISSION_NAME = "name"; 1085 private static final String ATTR_IS_GRANTED = "g"; 1086 private static final String ATTR_USER_SET = "set"; 1087 private static final String ATTR_USER_FIXED = "fixed"; 1088 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1089 1090 // System/policy permission grants are not backed up 1091 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1092 FLAG_PERMISSION_POLICY_FIXED 1093 | FLAG_PERMISSION_SYSTEM_FIXED 1094 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1095 1096 // And we back up these user-adjusted states 1097 private static final int USER_RUNTIME_GRANT_MASK = 1098 FLAG_PERMISSION_USER_SET 1099 | FLAG_PERMISSION_USER_FIXED 1100 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1101 1102 final @Nullable String mRequiredVerifierPackage; 1103 final @NonNull String mRequiredInstallerPackage; 1104 final @Nullable String mSetupWizardPackage; 1105 final @NonNull String mServicesSystemSharedLibraryPackageName; 1106 1107 private final PackageUsage mPackageUsage = new PackageUsage(); 1108 1109 private class PackageUsage { 1110 private static final int WRITE_INTERVAL 1111 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 1112 1113 private final Object mFileLock = new Object(); 1114 private final AtomicLong mLastWritten = new AtomicLong(0); 1115 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 1116 1117 private boolean mIsHistoricalPackageUsageAvailable = true; 1118 1119 boolean isHistoricalPackageUsageAvailable() { 1120 return mIsHistoricalPackageUsageAvailable; 1121 } 1122 1123 void write(boolean force) { 1124 if (force) { 1125 writeInternal(); 1126 return; 1127 } 1128 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 1129 && !DEBUG_DEXOPT) { 1130 return; 1131 } 1132 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 1133 new Thread("PackageUsage_DiskWriter") { 1134 @Override 1135 public void run() { 1136 try { 1137 writeInternal(); 1138 } finally { 1139 mBackgroundWriteRunning.set(false); 1140 } 1141 } 1142 }.start(); 1143 } 1144 } 1145 1146 private void writeInternal() { 1147 synchronized (mPackages) { 1148 synchronized (mFileLock) { 1149 AtomicFile file = getFile(); 1150 FileOutputStream f = null; 1151 try { 1152 f = file.startWrite(); 1153 BufferedOutputStream out = new BufferedOutputStream(f); 1154 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1155 StringBuilder sb = new StringBuilder(); 1156 for (PackageParser.Package pkg : mPackages.values()) { 1157 if (pkg.mLastPackageUsageTimeInMills == 0) { 1158 continue; 1159 } 1160 sb.setLength(0); 1161 sb.append(pkg.packageName); 1162 sb.append(' '); 1163 sb.append((long)pkg.mLastPackageUsageTimeInMills); 1164 sb.append('\n'); 1165 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1166 } 1167 out.flush(); 1168 file.finishWrite(f); 1169 } catch (IOException e) { 1170 if (f != null) { 1171 file.failWrite(f); 1172 } 1173 Log.e(TAG, "Failed to write package usage times", e); 1174 } 1175 } 1176 } 1177 mLastWritten.set(SystemClock.elapsedRealtime()); 1178 } 1179 1180 void readLP() { 1181 synchronized (mFileLock) { 1182 AtomicFile file = getFile(); 1183 BufferedInputStream in = null; 1184 try { 1185 in = new BufferedInputStream(file.openRead()); 1186 StringBuffer sb = new StringBuffer(); 1187 while (true) { 1188 String packageName = readToken(in, sb, ' '); 1189 if (packageName == null) { 1190 break; 1191 } 1192 String timeInMillisString = readToken(in, sb, '\n'); 1193 if (timeInMillisString == null) { 1194 throw new IOException("Failed to find last usage time for package " 1195 + packageName); 1196 } 1197 PackageParser.Package pkg = mPackages.get(packageName); 1198 if (pkg == null) { 1199 continue; 1200 } 1201 long timeInMillis; 1202 try { 1203 timeInMillis = Long.parseLong(timeInMillisString); 1204 } catch (NumberFormatException e) { 1205 throw new IOException("Failed to parse " + timeInMillisString 1206 + " as a long.", e); 1207 } 1208 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1209 } 1210 } catch (FileNotFoundException expected) { 1211 mIsHistoricalPackageUsageAvailable = false; 1212 } catch (IOException e) { 1213 Log.w(TAG, "Failed to read package usage times", e); 1214 } finally { 1215 IoUtils.closeQuietly(in); 1216 } 1217 } 1218 mLastWritten.set(SystemClock.elapsedRealtime()); 1219 } 1220 1221 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1222 throws IOException { 1223 sb.setLength(0); 1224 while (true) { 1225 int ch = in.read(); 1226 if (ch == -1) { 1227 if (sb.length() == 0) { 1228 return null; 1229 } 1230 throw new IOException("Unexpected EOF"); 1231 } 1232 if (ch == endOfToken) { 1233 return sb.toString(); 1234 } 1235 sb.append((char)ch); 1236 } 1237 } 1238 1239 private AtomicFile getFile() { 1240 File dataDir = Environment.getDataDirectory(); 1241 File systemDir = new File(dataDir, "system"); 1242 File fname = new File(systemDir, "package-usage.list"); 1243 return new AtomicFile(fname); 1244 } 1245 } 1246 1247 class PackageHandler extends Handler { 1248 private boolean mBound = false; 1249 final ArrayList<HandlerParams> mPendingInstalls = 1250 new ArrayList<HandlerParams>(); 1251 1252 private boolean connectToService() { 1253 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1254 " DefaultContainerService"); 1255 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1256 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1257 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1258 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1259 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1260 mBound = true; 1261 return true; 1262 } 1263 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1264 return false; 1265 } 1266 1267 private void disconnectService() { 1268 mContainerService = null; 1269 mBound = false; 1270 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1271 mContext.unbindService(mDefContainerConn); 1272 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1273 } 1274 1275 PackageHandler(Looper looper) { 1276 super(looper); 1277 } 1278 1279 public void handleMessage(Message msg) { 1280 try { 1281 doHandleMessage(msg); 1282 } finally { 1283 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1284 } 1285 } 1286 1287 void doHandleMessage(Message msg) { 1288 switch (msg.what) { 1289 case INIT_COPY: { 1290 HandlerParams params = (HandlerParams) msg.obj; 1291 int idx = mPendingInstalls.size(); 1292 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1293 // If a bind was already initiated we dont really 1294 // need to do anything. The pending install 1295 // will be processed later on. 1296 if (!mBound) { 1297 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1298 System.identityHashCode(mHandler)); 1299 // If this is the only one pending we might 1300 // have to bind to the service again. 1301 if (!connectToService()) { 1302 Slog.e(TAG, "Failed to bind to media container service"); 1303 params.serviceError(); 1304 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1305 System.identityHashCode(mHandler)); 1306 if (params.traceMethod != null) { 1307 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1308 params.traceCookie); 1309 } 1310 return; 1311 } else { 1312 // Once we bind to the service, the first 1313 // pending request will be processed. 1314 mPendingInstalls.add(idx, params); 1315 } 1316 } else { 1317 mPendingInstalls.add(idx, params); 1318 // Already bound to the service. Just make 1319 // sure we trigger off processing the first request. 1320 if (idx == 0) { 1321 mHandler.sendEmptyMessage(MCS_BOUND); 1322 } 1323 } 1324 break; 1325 } 1326 case MCS_BOUND: { 1327 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1328 if (msg.obj != null) { 1329 mContainerService = (IMediaContainerService) msg.obj; 1330 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1331 System.identityHashCode(mHandler)); 1332 } 1333 if (mContainerService == null) { 1334 if (!mBound) { 1335 // Something seriously wrong since we are not bound and we are not 1336 // waiting for connection. Bail out. 1337 Slog.e(TAG, "Cannot bind to media container service"); 1338 for (HandlerParams params : mPendingInstalls) { 1339 // Indicate service bind error 1340 params.serviceError(); 1341 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1342 System.identityHashCode(params)); 1343 if (params.traceMethod != null) { 1344 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1345 params.traceMethod, params.traceCookie); 1346 } 1347 return; 1348 } 1349 mPendingInstalls.clear(); 1350 } else { 1351 Slog.w(TAG, "Waiting to connect to media container service"); 1352 } 1353 } else if (mPendingInstalls.size() > 0) { 1354 HandlerParams params = mPendingInstalls.get(0); 1355 if (params != null) { 1356 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1357 System.identityHashCode(params)); 1358 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1359 if (params.startCopy()) { 1360 // We are done... look for more work or to 1361 // go idle. 1362 if (DEBUG_SD_INSTALL) Log.i(TAG, 1363 "Checking for more work or unbind..."); 1364 // Delete pending install 1365 if (mPendingInstalls.size() > 0) { 1366 mPendingInstalls.remove(0); 1367 } 1368 if (mPendingInstalls.size() == 0) { 1369 if (mBound) { 1370 if (DEBUG_SD_INSTALL) Log.i(TAG, 1371 "Posting delayed MCS_UNBIND"); 1372 removeMessages(MCS_UNBIND); 1373 Message ubmsg = obtainMessage(MCS_UNBIND); 1374 // Unbind after a little delay, to avoid 1375 // continual thrashing. 1376 sendMessageDelayed(ubmsg, 10000); 1377 } 1378 } else { 1379 // There are more pending requests in queue. 1380 // Just post MCS_BOUND message to trigger processing 1381 // of next pending install. 1382 if (DEBUG_SD_INSTALL) Log.i(TAG, 1383 "Posting MCS_BOUND for next work"); 1384 mHandler.sendEmptyMessage(MCS_BOUND); 1385 } 1386 } 1387 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1388 } 1389 } else { 1390 // Should never happen ideally. 1391 Slog.w(TAG, "Empty queue"); 1392 } 1393 break; 1394 } 1395 case MCS_RECONNECT: { 1396 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1397 if (mPendingInstalls.size() > 0) { 1398 if (mBound) { 1399 disconnectService(); 1400 } 1401 if (!connectToService()) { 1402 Slog.e(TAG, "Failed to bind to media container service"); 1403 for (HandlerParams params : mPendingInstalls) { 1404 // Indicate service bind error 1405 params.serviceError(); 1406 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1407 System.identityHashCode(params)); 1408 } 1409 mPendingInstalls.clear(); 1410 } 1411 } 1412 break; 1413 } 1414 case MCS_UNBIND: { 1415 // If there is no actual work left, then time to unbind. 1416 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1417 1418 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1419 if (mBound) { 1420 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1421 1422 disconnectService(); 1423 } 1424 } else if (mPendingInstalls.size() > 0) { 1425 // There are more pending requests in queue. 1426 // Just post MCS_BOUND message to trigger processing 1427 // of next pending install. 1428 mHandler.sendEmptyMessage(MCS_BOUND); 1429 } 1430 1431 break; 1432 } 1433 case MCS_GIVE_UP: { 1434 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1435 HandlerParams params = mPendingInstalls.remove(0); 1436 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1437 System.identityHashCode(params)); 1438 break; 1439 } 1440 case SEND_PENDING_BROADCAST: { 1441 String packages[]; 1442 ArrayList<String> components[]; 1443 int size = 0; 1444 int uids[]; 1445 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1446 synchronized (mPackages) { 1447 if (mPendingBroadcasts == null) { 1448 return; 1449 } 1450 size = mPendingBroadcasts.size(); 1451 if (size <= 0) { 1452 // Nothing to be done. Just return 1453 return; 1454 } 1455 packages = new String[size]; 1456 components = new ArrayList[size]; 1457 uids = new int[size]; 1458 int i = 0; // filling out the above arrays 1459 1460 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1461 int packageUserId = mPendingBroadcasts.userIdAt(n); 1462 Iterator<Map.Entry<String, ArrayList<String>>> it 1463 = mPendingBroadcasts.packagesForUserId(packageUserId) 1464 .entrySet().iterator(); 1465 while (it.hasNext() && i < size) { 1466 Map.Entry<String, ArrayList<String>> ent = it.next(); 1467 packages[i] = ent.getKey(); 1468 components[i] = ent.getValue(); 1469 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1470 uids[i] = (ps != null) 1471 ? UserHandle.getUid(packageUserId, ps.appId) 1472 : -1; 1473 i++; 1474 } 1475 } 1476 size = i; 1477 mPendingBroadcasts.clear(); 1478 } 1479 // Send broadcasts 1480 for (int i = 0; i < size; i++) { 1481 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1482 } 1483 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1484 break; 1485 } 1486 case START_CLEANING_PACKAGE: { 1487 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1488 final String packageName = (String)msg.obj; 1489 final int userId = msg.arg1; 1490 final boolean andCode = msg.arg2 != 0; 1491 synchronized (mPackages) { 1492 if (userId == UserHandle.USER_ALL) { 1493 int[] users = sUserManager.getUserIds(); 1494 for (int user : users) { 1495 mSettings.addPackageToCleanLPw( 1496 new PackageCleanItem(user, packageName, andCode)); 1497 } 1498 } else { 1499 mSettings.addPackageToCleanLPw( 1500 new PackageCleanItem(userId, packageName, andCode)); 1501 } 1502 } 1503 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1504 startCleaningPackages(); 1505 } break; 1506 case POST_INSTALL: { 1507 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1508 1509 PostInstallData data = mRunningInstalls.get(msg.arg1); 1510 mRunningInstalls.delete(msg.arg1); 1511 1512 if (data != null) { 1513 InstallArgs args = data.args; 1514 PackageInstalledInfo parentRes = data.res; 1515 1516 final boolean grantPermissions = (args.installFlags 1517 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1518 final boolean killApp = (args.installFlags 1519 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1520 final String[] grantedPermissions = args.installGrantPermissions; 1521 1522 // Handle the parent package 1523 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1524 grantedPermissions, args.observer); 1525 1526 // Handle the child packages 1527 final int childCount = (parentRes.addedChildPackages != null) 1528 ? parentRes.addedChildPackages.size() : 0; 1529 for (int i = 0; i < childCount; i++) { 1530 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1531 handlePackagePostInstall(childRes, grantPermissions, killApp, 1532 grantedPermissions, args.observer); 1533 } 1534 1535 // Log tracing if needed 1536 if (args.traceMethod != null) { 1537 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1538 args.traceCookie); 1539 } 1540 } else { 1541 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1542 } 1543 1544 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1545 } break; 1546 case UPDATED_MEDIA_STATUS: { 1547 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1548 boolean reportStatus = msg.arg1 == 1; 1549 boolean doGc = msg.arg2 == 1; 1550 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1551 if (doGc) { 1552 // Force a gc to clear up stale containers. 1553 Runtime.getRuntime().gc(); 1554 } 1555 if (msg.obj != null) { 1556 @SuppressWarnings("unchecked") 1557 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1558 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1559 // Unload containers 1560 unloadAllContainers(args); 1561 } 1562 if (reportStatus) { 1563 try { 1564 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1565 PackageHelper.getMountService().finishMediaUpdate(); 1566 } catch (RemoteException e) { 1567 Log.e(TAG, "MountService not running?"); 1568 } 1569 } 1570 } break; 1571 case WRITE_SETTINGS: { 1572 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1573 synchronized (mPackages) { 1574 removeMessages(WRITE_SETTINGS); 1575 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1576 mSettings.writeLPr(); 1577 mDirtyUsers.clear(); 1578 } 1579 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1580 } break; 1581 case WRITE_PACKAGE_RESTRICTIONS: { 1582 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1583 synchronized (mPackages) { 1584 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1585 for (int userId : mDirtyUsers) { 1586 mSettings.writePackageRestrictionsLPr(userId); 1587 } 1588 mDirtyUsers.clear(); 1589 } 1590 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1591 } break; 1592 case CHECK_PENDING_VERIFICATION: { 1593 final int verificationId = msg.arg1; 1594 final PackageVerificationState state = mPendingVerification.get(verificationId); 1595 1596 if ((state != null) && !state.timeoutExtended()) { 1597 final InstallArgs args = state.getInstallArgs(); 1598 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1599 1600 Slog.i(TAG, "Verification timed out for " + originUri); 1601 mPendingVerification.remove(verificationId); 1602 1603 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1604 1605 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1606 Slog.i(TAG, "Continuing with installation of " + originUri); 1607 state.setVerifierResponse(Binder.getCallingUid(), 1608 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1609 broadcastPackageVerified(verificationId, originUri, 1610 PackageManager.VERIFICATION_ALLOW, 1611 state.getInstallArgs().getUser()); 1612 try { 1613 ret = args.copyApk(mContainerService, true); 1614 } catch (RemoteException e) { 1615 Slog.e(TAG, "Could not contact the ContainerService"); 1616 } 1617 } else { 1618 broadcastPackageVerified(verificationId, originUri, 1619 PackageManager.VERIFICATION_REJECT, 1620 state.getInstallArgs().getUser()); 1621 } 1622 1623 Trace.asyncTraceEnd( 1624 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1625 1626 processPendingInstall(args, ret); 1627 mHandler.sendEmptyMessage(MCS_UNBIND); 1628 } 1629 break; 1630 } 1631 case PACKAGE_VERIFIED: { 1632 final int verificationId = msg.arg1; 1633 1634 final PackageVerificationState state = mPendingVerification.get(verificationId); 1635 if (state == null) { 1636 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1637 break; 1638 } 1639 1640 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1641 1642 state.setVerifierResponse(response.callerUid, response.code); 1643 1644 if (state.isVerificationComplete()) { 1645 mPendingVerification.remove(verificationId); 1646 1647 final InstallArgs args = state.getInstallArgs(); 1648 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1649 1650 int ret; 1651 if (state.isInstallAllowed()) { 1652 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1653 broadcastPackageVerified(verificationId, originUri, 1654 response.code, state.getInstallArgs().getUser()); 1655 try { 1656 ret = args.copyApk(mContainerService, true); 1657 } catch (RemoteException e) { 1658 Slog.e(TAG, "Could not contact the ContainerService"); 1659 } 1660 } else { 1661 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1662 } 1663 1664 Trace.asyncTraceEnd( 1665 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1666 1667 processPendingInstall(args, ret); 1668 mHandler.sendEmptyMessage(MCS_UNBIND); 1669 } 1670 1671 break; 1672 } 1673 case START_INTENT_FILTER_VERIFICATIONS: { 1674 IFVerificationParams params = (IFVerificationParams) msg.obj; 1675 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1676 params.replacing, params.pkg); 1677 break; 1678 } 1679 case INTENT_FILTER_VERIFIED: { 1680 final int verificationId = msg.arg1; 1681 1682 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1683 verificationId); 1684 if (state == null) { 1685 Slog.w(TAG, "Invalid IntentFilter verification token " 1686 + verificationId + " received"); 1687 break; 1688 } 1689 1690 final int userId = state.getUserId(); 1691 1692 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1693 "Processing IntentFilter verification with token:" 1694 + verificationId + " and userId:" + userId); 1695 1696 final IntentFilterVerificationResponse response = 1697 (IntentFilterVerificationResponse) msg.obj; 1698 1699 state.setVerifierResponse(response.callerUid, response.code); 1700 1701 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1702 "IntentFilter verification with token:" + verificationId 1703 + " and userId:" + userId 1704 + " is settings verifier response with response code:" 1705 + response.code); 1706 1707 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1708 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1709 + response.getFailedDomainsString()); 1710 } 1711 1712 if (state.isVerificationComplete()) { 1713 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1714 } else { 1715 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1716 "IntentFilter verification with token:" + verificationId 1717 + " was not said to be complete"); 1718 } 1719 1720 break; 1721 } 1722 } 1723 } 1724 } 1725 1726 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1727 boolean killApp, String[] grantedPermissions, 1728 IPackageInstallObserver2 installObserver) { 1729 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1730 // Send the removed broadcasts 1731 if (res.removedInfo != null) { 1732 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1733 } 1734 1735 // Now that we successfully installed the package, grant runtime 1736 // permissions if requested before broadcasting the install. 1737 if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion 1738 >= Build.VERSION_CODES.M) { 1739 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1740 } 1741 1742 final boolean update = res.removedInfo != null 1743 && res.removedInfo.removedPackage != null; 1744 1745 // If this is the first time we have child packages for a disabled privileged 1746 // app that had no children, we grant requested runtime permissions to the new 1747 // children if the parent on the system image had them already granted. 1748 if (res.pkg.parentPackage != null) { 1749 synchronized (mPackages) { 1750 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1751 } 1752 } 1753 1754 synchronized (mPackages) { 1755 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1756 } 1757 1758 final String packageName = res.pkg.applicationInfo.packageName; 1759 Bundle extras = new Bundle(1); 1760 extras.putInt(Intent.EXTRA_UID, res.uid); 1761 1762 // Determine the set of users who are adding this package for 1763 // the first time vs. those who are seeing an update. 1764 int[] firstUsers = EMPTY_INT_ARRAY; 1765 int[] updateUsers = EMPTY_INT_ARRAY; 1766 if (res.origUsers == null || res.origUsers.length == 0) { 1767 firstUsers = res.newUsers; 1768 } else { 1769 for (int newUser : res.newUsers) { 1770 boolean isNew = true; 1771 for (int origUser : res.origUsers) { 1772 if (origUser == newUser) { 1773 isNew = false; 1774 break; 1775 } 1776 } 1777 if (isNew) { 1778 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1779 } else { 1780 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1781 } 1782 } 1783 } 1784 1785 // Send installed broadcasts if the install/update is not ephemeral 1786 if (!isEphemeral(res.pkg)) { 1787 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1788 1789 // Send added for users that see the package for the first time 1790 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1791 extras, 0 /*flags*/, null /*targetPackage*/, 1792 null /*finishedReceiver*/, firstUsers); 1793 1794 // Send added for users that don't see the package for the first time 1795 if (update) { 1796 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1797 } 1798 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1799 extras, 0 /*flags*/, null /*targetPackage*/, 1800 null /*finishedReceiver*/, updateUsers); 1801 1802 // Send replaced for users that don't see the package for the first time 1803 if (update) { 1804 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1805 packageName, extras, 0 /*flags*/, 1806 null /*targetPackage*/, null /*finishedReceiver*/, 1807 updateUsers); 1808 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1809 null /*package*/, null /*extras*/, 0 /*flags*/, 1810 packageName /*targetPackage*/, 1811 null /*finishedReceiver*/, updateUsers); 1812 } 1813 1814 // Send broadcast package appeared if forward locked/external for all users 1815 // treat asec-hosted packages like removable media on upgrade 1816 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1817 if (DEBUG_INSTALL) { 1818 Slog.i(TAG, "upgrading pkg " + res.pkg 1819 + " is ASEC-hosted -> AVAILABLE"); 1820 } 1821 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1822 ArrayList<String> pkgList = new ArrayList<>(1); 1823 pkgList.add(packageName); 1824 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1825 } 1826 } 1827 1828 // Work that needs to happen on first install within each user 1829 if (firstUsers != null && firstUsers.length > 0) { 1830 synchronized (mPackages) { 1831 for (int userId : firstUsers) { 1832 // If this app is a browser and it's newly-installed for some 1833 // users, clear any default-browser state in those users. The 1834 // app's nature doesn't depend on the user, so we can just check 1835 // its browser nature in any user and generalize. 1836 if (packageIsBrowser(packageName, userId)) { 1837 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1838 } 1839 1840 // We may also need to apply pending (restored) runtime 1841 // permission grants within these users. 1842 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1843 } 1844 } 1845 } 1846 1847 // Log current value of "unknown sources" setting 1848 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1849 getUnknownSourcesSettings()); 1850 1851 // Force a gc to clear up things 1852 Runtime.getRuntime().gc(); 1853 1854 // Remove the replaced package's older resources safely now 1855 // We delete after a gc for applications on sdcard. 1856 if (res.removedInfo != null && res.removedInfo.args != null) { 1857 synchronized (mInstallLock) { 1858 res.removedInfo.args.doPostDeleteLI(true); 1859 } 1860 } 1861 } 1862 1863 // If someone is watching installs - notify them 1864 if (installObserver != null) { 1865 try { 1866 Bundle extras = extrasForInstallResult(res); 1867 installObserver.onPackageInstalled(res.name, res.returnCode, 1868 res.returnMsg, extras); 1869 } catch (RemoteException e) { 1870 Slog.i(TAG, "Observer no longer exists."); 1871 } 1872 } 1873 } 1874 1875 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1876 PackageParser.Package pkg) { 1877 if (pkg.parentPackage == null) { 1878 return; 1879 } 1880 if (pkg.requestedPermissions == null) { 1881 return; 1882 } 1883 final PackageSetting disabledSysParentPs = mSettings 1884 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1885 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1886 || !disabledSysParentPs.isPrivileged() 1887 || (disabledSysParentPs.childPackageNames != null 1888 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1889 return; 1890 } 1891 final int[] allUserIds = sUserManager.getUserIds(); 1892 final int permCount = pkg.requestedPermissions.size(); 1893 for (int i = 0; i < permCount; i++) { 1894 String permission = pkg.requestedPermissions.get(i); 1895 BasePermission bp = mSettings.mPermissions.get(permission); 1896 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1897 continue; 1898 } 1899 for (int userId : allUserIds) { 1900 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1901 permission, userId)) { 1902 grantRuntimePermission(pkg.packageName, permission, userId); 1903 } 1904 } 1905 } 1906 } 1907 1908 private StorageEventListener mStorageListener = new StorageEventListener() { 1909 @Override 1910 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1911 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1912 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1913 final String volumeUuid = vol.getFsUuid(); 1914 1915 // Clean up any users or apps that were removed or recreated 1916 // while this volume was missing 1917 reconcileUsers(volumeUuid); 1918 reconcileApps(volumeUuid); 1919 1920 // Clean up any install sessions that expired or were 1921 // cancelled while this volume was missing 1922 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1923 1924 loadPrivatePackages(vol); 1925 1926 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1927 unloadPrivatePackages(vol); 1928 } 1929 } 1930 1931 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1932 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1933 updateExternalMediaStatus(true, false); 1934 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1935 updateExternalMediaStatus(false, false); 1936 } 1937 } 1938 } 1939 1940 @Override 1941 public void onVolumeForgotten(String fsUuid) { 1942 if (TextUtils.isEmpty(fsUuid)) { 1943 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1944 return; 1945 } 1946 1947 // Remove any apps installed on the forgotten volume 1948 synchronized (mPackages) { 1949 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1950 for (PackageSetting ps : packages) { 1951 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1952 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1953 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 1954 } 1955 1956 mSettings.onVolumeForgotten(fsUuid); 1957 mSettings.writeLPr(); 1958 } 1959 } 1960 }; 1961 1962 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 1963 String[] grantedPermissions) { 1964 for (int userId : userIds) { 1965 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1966 } 1967 1968 // We could have touched GID membership, so flush out packages.list 1969 synchronized (mPackages) { 1970 mSettings.writePackageListLPr(); 1971 } 1972 } 1973 1974 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1975 String[] grantedPermissions) { 1976 SettingBase sb = (SettingBase) pkg.mExtras; 1977 if (sb == null) { 1978 return; 1979 } 1980 1981 PermissionsState permissionsState = sb.getPermissionsState(); 1982 1983 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 1984 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 1985 1986 synchronized (mPackages) { 1987 for (String permission : pkg.requestedPermissions) { 1988 BasePermission bp = mSettings.mPermissions.get(permission); 1989 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 1990 && (grantedPermissions == null 1991 || ArrayUtils.contains(grantedPermissions, permission))) { 1992 final int flags = permissionsState.getPermissionFlags(permission, userId); 1993 // Installer cannot change immutable permissions. 1994 if ((flags & immutableFlags) == 0) { 1995 grantRuntimePermission(pkg.packageName, permission, userId); 1996 } 1997 } 1998 } 1999 } 2000 } 2001 2002 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2003 Bundle extras = null; 2004 switch (res.returnCode) { 2005 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2006 extras = new Bundle(); 2007 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2008 res.origPermission); 2009 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2010 res.origPackage); 2011 break; 2012 } 2013 case PackageManager.INSTALL_SUCCEEDED: { 2014 extras = new Bundle(); 2015 extras.putBoolean(Intent.EXTRA_REPLACING, 2016 res.removedInfo != null && res.removedInfo.removedPackage != null); 2017 break; 2018 } 2019 } 2020 return extras; 2021 } 2022 2023 void scheduleWriteSettingsLocked() { 2024 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2025 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2026 } 2027 } 2028 2029 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2030 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2031 scheduleWritePackageRestrictionsLocked(userId); 2032 } 2033 2034 void scheduleWritePackageRestrictionsLocked(int userId) { 2035 final int[] userIds = (userId == UserHandle.USER_ALL) 2036 ? sUserManager.getUserIds() : new int[]{userId}; 2037 for (int nextUserId : userIds) { 2038 if (!sUserManager.exists(nextUserId)) return; 2039 mDirtyUsers.add(nextUserId); 2040 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2041 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2042 } 2043 } 2044 } 2045 2046 public static PackageManagerService main(Context context, Installer installer, 2047 boolean factoryTest, boolean onlyCore) { 2048 // Self-check for initial settings. 2049 PackageManagerServiceCompilerMapping.checkProperties(); 2050 2051 PackageManagerService m = new PackageManagerService(context, installer, 2052 factoryTest, onlyCore); 2053 m.enableSystemUserPackages(); 2054 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 2055 // disabled after already being started. 2056 CarrierAppUtils.disableCarrierAppsUntilPrivileged(context.getOpPackageName(), m, 2057 UserHandle.USER_SYSTEM); 2058 ServiceManager.addService("package", m); 2059 return m; 2060 } 2061 2062 private void enableSystemUserPackages() { 2063 if (!UserManager.isSplitSystemUser()) { 2064 return; 2065 } 2066 // For system user, enable apps based on the following conditions: 2067 // - app is whitelisted or belong to one of these groups: 2068 // -- system app which has no launcher icons 2069 // -- system app which has INTERACT_ACROSS_USERS permission 2070 // -- system IME app 2071 // - app is not in the blacklist 2072 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2073 Set<String> enableApps = new ArraySet<>(); 2074 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2075 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2076 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2077 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2078 enableApps.addAll(wlApps); 2079 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2080 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2081 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2082 enableApps.removeAll(blApps); 2083 Log.i(TAG, "Applications installed for system user: " + enableApps); 2084 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2085 UserHandle.SYSTEM); 2086 final int allAppsSize = allAps.size(); 2087 synchronized (mPackages) { 2088 for (int i = 0; i < allAppsSize; i++) { 2089 String pName = allAps.get(i); 2090 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2091 // Should not happen, but we shouldn't be failing if it does 2092 if (pkgSetting == null) { 2093 continue; 2094 } 2095 boolean install = enableApps.contains(pName); 2096 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2097 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2098 + " for system user"); 2099 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2100 } 2101 } 2102 } 2103 } 2104 2105 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2106 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2107 Context.DISPLAY_SERVICE); 2108 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2109 } 2110 2111 public PackageManagerService(Context context, Installer installer, 2112 boolean factoryTest, boolean onlyCore) { 2113 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2114 SystemClock.uptimeMillis()); 2115 2116 if (mSdkVersion <= 0) { 2117 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2118 } 2119 2120 mContext = context; 2121 mFactoryTest = factoryTest; 2122 mOnlyCore = onlyCore; 2123 mMetrics = new DisplayMetrics(); 2124 mSettings = new Settings(mPackages); 2125 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2126 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2127 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2128 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2129 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2130 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2131 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2132 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2133 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2134 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2135 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2136 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2137 2138 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2139 if (separateProcesses != null && separateProcesses.length() > 0) { 2140 if ("*".equals(separateProcesses)) { 2141 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2142 mSeparateProcesses = null; 2143 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2144 } else { 2145 mDefParseFlags = 0; 2146 mSeparateProcesses = separateProcesses.split(","); 2147 Slog.w(TAG, "Running with debug.separate_processes: " 2148 + separateProcesses); 2149 } 2150 } else { 2151 mDefParseFlags = 0; 2152 mSeparateProcesses = null; 2153 } 2154 2155 mInstaller = installer; 2156 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2157 "*dexopt*"); 2158 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2159 2160 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2161 FgThread.get().getLooper()); 2162 2163 getDefaultDisplayMetrics(context, mMetrics); 2164 2165 SystemConfig systemConfig = SystemConfig.getInstance(); 2166 mGlobalGids = systemConfig.getGlobalGids(); 2167 mSystemPermissions = systemConfig.getSystemPermissions(); 2168 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2169 2170 synchronized (mInstallLock) { 2171 // writer 2172 synchronized (mPackages) { 2173 mHandlerThread = new ServiceThread(TAG, 2174 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2175 mHandlerThread.start(); 2176 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2177 mProcessLoggingHandler = new ProcessLoggingHandler(); 2178 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2179 2180 File dataDir = Environment.getDataDirectory(); 2181 mAppInstallDir = new File(dataDir, "app"); 2182 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2183 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2184 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2185 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2186 2187 sUserManager = new UserManagerService(context, this, mPackages); 2188 2189 // Propagate permission configuration in to package manager. 2190 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2191 = systemConfig.getPermissions(); 2192 for (int i=0; i<permConfig.size(); i++) { 2193 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2194 BasePermission bp = mSettings.mPermissions.get(perm.name); 2195 if (bp == null) { 2196 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2197 mSettings.mPermissions.put(perm.name, bp); 2198 } 2199 if (perm.gids != null) { 2200 bp.setGids(perm.gids, perm.perUser); 2201 } 2202 } 2203 2204 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2205 for (int i=0; i<libConfig.size(); i++) { 2206 mSharedLibraries.put(libConfig.keyAt(i), 2207 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2208 } 2209 2210 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2211 2212 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 2213 2214 String customResolverActivity = Resources.getSystem().getString( 2215 R.string.config_customResolverActivity); 2216 if (TextUtils.isEmpty(customResolverActivity)) { 2217 customResolverActivity = null; 2218 } else { 2219 mCustomResolverComponentName = ComponentName.unflattenFromString( 2220 customResolverActivity); 2221 } 2222 2223 long startTime = SystemClock.uptimeMillis(); 2224 2225 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2226 startTime); 2227 2228 // Set flag to monitor and not change apk file paths when 2229 // scanning install directories. 2230 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2231 2232 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2233 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2234 2235 if (bootClassPath == null) { 2236 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2237 } 2238 2239 if (systemServerClassPath == null) { 2240 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2241 } 2242 2243 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2244 final String[] dexCodeInstructionSets = 2245 getDexCodeInstructionSets( 2246 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2247 2248 /** 2249 * Ensure all external libraries have had dexopt run on them. 2250 */ 2251 if (mSharedLibraries.size() > 0) { 2252 // NOTE: For now, we're compiling these system "shared libraries" 2253 // (and framework jars) into all available architectures. It's possible 2254 // to compile them only when we come across an app that uses them (there's 2255 // already logic for that in scanPackageLI) but that adds some complexity. 2256 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2257 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2258 final String lib = libEntry.path; 2259 if (lib == null) { 2260 continue; 2261 } 2262 2263 try { 2264 // Shared libraries do not have profiles so we perform a full 2265 // AOT compilation (if needed). 2266 int dexoptNeeded = DexFile.getDexOptNeeded( 2267 lib, dexCodeInstructionSet, 2268 getCompilerFilterForReason(REASON_SHARED_APK), 2269 false /* newProfile */); 2270 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2271 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2272 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/, 2273 getCompilerFilterForReason(REASON_SHARED_APK), 2274 StorageManager.UUID_PRIVATE_INTERNAL); 2275 } 2276 } catch (FileNotFoundException e) { 2277 Slog.w(TAG, "Library not found: " + lib); 2278 } catch (IOException | InstallerException e) { 2279 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2280 + e.getMessage()); 2281 } 2282 } 2283 } 2284 } 2285 2286 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2287 2288 final VersionInfo ver = mSettings.getInternalVersion(); 2289 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2290 2291 // when upgrading from pre-M, promote system app permissions from install to runtime 2292 mPromoteSystemApps = 2293 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2294 2295 // save off the names of pre-existing system packages prior to scanning; we don't 2296 // want to automatically grant runtime permissions for new system apps 2297 if (mPromoteSystemApps) { 2298 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2299 while (pkgSettingIter.hasNext()) { 2300 PackageSetting ps = pkgSettingIter.next(); 2301 if (isSystemApp(ps)) { 2302 mExistingSystemPackages.add(ps.name); 2303 } 2304 } 2305 } 2306 2307 // When upgrading from pre-N, we need to handle package extraction like first boot, 2308 // as there is no profiling data available. 2309 mIsPreNUpgrade = !mSettings.isNWorkDone(); 2310 mSettings.setNWorkDone(); 2311 2312 // Collect vendor overlay packages. 2313 // (Do this before scanning any apps.) 2314 // For security and version matching reason, only consider 2315 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2316 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2317 scanDirTracedLI(vendorOverlayDir, mDefParseFlags 2318 | PackageParser.PARSE_IS_SYSTEM 2319 | PackageParser.PARSE_IS_SYSTEM_DIR 2320 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2321 2322 // Find base frameworks (resource packages without code). 2323 scanDirTracedLI(frameworkDir, mDefParseFlags 2324 | PackageParser.PARSE_IS_SYSTEM 2325 | PackageParser.PARSE_IS_SYSTEM_DIR 2326 | PackageParser.PARSE_IS_PRIVILEGED, 2327 scanFlags | SCAN_NO_DEX, 0); 2328 2329 // Collected privileged system packages. 2330 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2331 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2332 | PackageParser.PARSE_IS_SYSTEM 2333 | PackageParser.PARSE_IS_SYSTEM_DIR 2334 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2335 2336 // Collect ordinary system packages. 2337 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2338 scanDirTracedLI(systemAppDir, mDefParseFlags 2339 | PackageParser.PARSE_IS_SYSTEM 2340 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2341 2342 // Collect all vendor packages. 2343 File vendorAppDir = new File("/vendor/app"); 2344 try { 2345 vendorAppDir = vendorAppDir.getCanonicalFile(); 2346 } catch (IOException e) { 2347 // failed to look up canonical path, continue with original one 2348 } 2349 scanDirTracedLI(vendorAppDir, mDefParseFlags 2350 | PackageParser.PARSE_IS_SYSTEM 2351 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2352 2353 // Collect all OEM packages. 2354 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2355 scanDirTracedLI(oemAppDir, mDefParseFlags 2356 | PackageParser.PARSE_IS_SYSTEM 2357 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2358 2359 // Prune any system packages that no longer exist. 2360 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2361 if (!mOnlyCore) { 2362 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2363 while (psit.hasNext()) { 2364 PackageSetting ps = psit.next(); 2365 2366 /* 2367 * If this is not a system app, it can't be a 2368 * disable system app. 2369 */ 2370 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2371 continue; 2372 } 2373 2374 /* 2375 * If the package is scanned, it's not erased. 2376 */ 2377 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2378 if (scannedPkg != null) { 2379 /* 2380 * If the system app is both scanned and in the 2381 * disabled packages list, then it must have been 2382 * added via OTA. Remove it from the currently 2383 * scanned package so the previously user-installed 2384 * application can be scanned. 2385 */ 2386 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2387 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2388 + ps.name + "; removing system app. Last known codePath=" 2389 + ps.codePathString + ", installStatus=" + ps.installStatus 2390 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2391 + scannedPkg.mVersionCode); 2392 removePackageLI(scannedPkg, true); 2393 mExpectingBetter.put(ps.name, ps.codePath); 2394 } 2395 2396 continue; 2397 } 2398 2399 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2400 psit.remove(); 2401 logCriticalInfo(Log.WARN, "System package " + ps.name 2402 + " no longer exists; it's data will be wiped"); 2403 // Actual deletion of code and data will be handled by later 2404 // reconciliation step 2405 } else { 2406 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2407 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2408 possiblyDeletedUpdatedSystemApps.add(ps.name); 2409 } 2410 } 2411 } 2412 } 2413 2414 //look for any incomplete package installations 2415 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2416 for (int i = 0; i < deletePkgsList.size(); i++) { 2417 // Actual deletion of code and data will be handled by later 2418 // reconciliation step 2419 final String packageName = deletePkgsList.get(i).name; 2420 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2421 synchronized (mPackages) { 2422 mSettings.removePackageLPw(packageName); 2423 } 2424 } 2425 2426 //delete tmp files 2427 deleteTempPackageFiles(); 2428 2429 // Remove any shared userIDs that have no associated packages 2430 mSettings.pruneSharedUsersLPw(); 2431 2432 if (!mOnlyCore) { 2433 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2434 SystemClock.uptimeMillis()); 2435 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2436 2437 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2438 | PackageParser.PARSE_FORWARD_LOCK, 2439 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2440 2441 scanDirLI(mEphemeralInstallDir, mDefParseFlags 2442 | PackageParser.PARSE_IS_EPHEMERAL, 2443 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2444 2445 /** 2446 * Remove disable package settings for any updated system 2447 * apps that were removed via an OTA. If they're not a 2448 * previously-updated app, remove them completely. 2449 * Otherwise, just revoke their system-level permissions. 2450 */ 2451 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2452 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2453 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2454 2455 String msg; 2456 if (deletedPkg == null) { 2457 msg = "Updated system package " + deletedAppName 2458 + " no longer exists; it's data will be wiped"; 2459 // Actual deletion of code and data will be handled by later 2460 // reconciliation step 2461 } else { 2462 msg = "Updated system app + " + deletedAppName 2463 + " no longer present; removing system privileges for " 2464 + deletedAppName; 2465 2466 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2467 2468 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2469 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2470 } 2471 logCriticalInfo(Log.WARN, msg); 2472 } 2473 2474 /** 2475 * Make sure all system apps that we expected to appear on 2476 * the userdata partition actually showed up. If they never 2477 * appeared, crawl back and revive the system version. 2478 */ 2479 for (int i = 0; i < mExpectingBetter.size(); i++) { 2480 final String packageName = mExpectingBetter.keyAt(i); 2481 if (!mPackages.containsKey(packageName)) { 2482 final File scanFile = mExpectingBetter.valueAt(i); 2483 2484 logCriticalInfo(Log.WARN, "Expected better " + packageName 2485 + " but never showed up; reverting to system"); 2486 2487 int reparseFlags = mDefParseFlags; 2488 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2489 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2490 | PackageParser.PARSE_IS_SYSTEM_DIR 2491 | PackageParser.PARSE_IS_PRIVILEGED; 2492 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2493 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2494 | PackageParser.PARSE_IS_SYSTEM_DIR; 2495 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2496 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2497 | PackageParser.PARSE_IS_SYSTEM_DIR; 2498 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2499 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2500 | PackageParser.PARSE_IS_SYSTEM_DIR; 2501 } else { 2502 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2503 continue; 2504 } 2505 2506 mSettings.enableSystemPackageLPw(packageName); 2507 2508 try { 2509 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2510 } catch (PackageManagerException e) { 2511 Slog.e(TAG, "Failed to parse original system package: " 2512 + e.getMessage()); 2513 } 2514 } 2515 } 2516 } 2517 mExpectingBetter.clear(); 2518 2519 // Resolve protected action filters. Only the setup wizard is allowed to 2520 // have a high priority filter for these actions. 2521 mSetupWizardPackage = getSetupWizardPackageName(); 2522 if (mProtectedFilters.size() > 0) { 2523 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2524 Slog.i(TAG, "No setup wizard;" 2525 + " All protected intents capped to priority 0"); 2526 } 2527 for (ActivityIntentInfo filter : mProtectedFilters) { 2528 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2529 if (DEBUG_FILTERS) { 2530 Slog.i(TAG, "Found setup wizard;" 2531 + " allow priority " + filter.getPriority() + ";" 2532 + " package: " + filter.activity.info.packageName 2533 + " activity: " + filter.activity.className 2534 + " priority: " + filter.getPriority()); 2535 } 2536 // skip setup wizard; allow it to keep the high priority filter 2537 continue; 2538 } 2539 Slog.w(TAG, "Protected action; cap priority to 0;" 2540 + " package: " + filter.activity.info.packageName 2541 + " activity: " + filter.activity.className 2542 + " origPrio: " + filter.getPriority()); 2543 filter.setPriority(0); 2544 } 2545 } 2546 mDeferProtectedFilters = false; 2547 mProtectedFilters.clear(); 2548 2549 // Now that we know all of the shared libraries, update all clients to have 2550 // the correct library paths. 2551 updateAllSharedLibrariesLPw(); 2552 2553 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2554 // NOTE: We ignore potential failures here during a system scan (like 2555 // the rest of the commands above) because there's precious little we 2556 // can do about it. A settings error is reported, though. 2557 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2558 false /* boot complete */); 2559 } 2560 2561 // Now that we know all the packages we are keeping, 2562 // read and update their last usage times. 2563 mPackageUsage.readLP(); 2564 2565 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2566 SystemClock.uptimeMillis()); 2567 Slog.i(TAG, "Time to scan packages: " 2568 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2569 + " seconds"); 2570 2571 // If the platform SDK has changed since the last time we booted, 2572 // we need to re-grant app permission to catch any new ones that 2573 // appear. This is really a hack, and means that apps can in some 2574 // cases get permissions that the user didn't initially explicitly 2575 // allow... it would be nice to have some better way to handle 2576 // this situation. 2577 int updateFlags = UPDATE_PERMISSIONS_ALL; 2578 if (ver.sdkVersion != mSdkVersion) { 2579 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2580 + mSdkVersion + "; regranting permissions for internal storage"); 2581 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2582 } 2583 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2584 ver.sdkVersion = mSdkVersion; 2585 2586 // If this is the first boot or an update from pre-M, and it is a normal 2587 // boot, then we need to initialize the default preferred apps across 2588 // all defined users. 2589 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2590 for (UserInfo user : sUserManager.getUsers(true)) { 2591 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2592 applyFactoryDefaultBrowserLPw(user.id); 2593 primeDomainVerificationsLPw(user.id); 2594 } 2595 } 2596 2597 // Prepare storage for system user really early during boot, 2598 // since core system apps like SettingsProvider and SystemUI 2599 // can't wait for user to start 2600 final int storageFlags; 2601 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2602 storageFlags = StorageManager.FLAG_STORAGE_DE; 2603 } else { 2604 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2605 } 2606 reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2607 storageFlags); 2608 2609 // If this is first boot after an OTA, and a normal boot, then 2610 // we need to clear code cache directories. 2611 if (mIsUpgrade && !onlyCore) { 2612 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2613 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2614 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2615 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2616 // No apps are running this early, so no need to freeze 2617 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2618 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2619 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2620 } 2621 clearAppProfilesLIF(ps.pkg); 2622 } 2623 ver.fingerprint = Build.FINGERPRINT; 2624 } 2625 2626 checkDefaultBrowser(); 2627 2628 // clear only after permissions and other defaults have been updated 2629 mExistingSystemPackages.clear(); 2630 mPromoteSystemApps = false; 2631 2632 // All the changes are done during package scanning. 2633 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2634 2635 // can downgrade to reader 2636 mSettings.writeLPr(); 2637 2638 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2639 SystemClock.uptimeMillis()); 2640 2641 if (!mOnlyCore) { 2642 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2643 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2644 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2645 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2646 mIntentFilterVerifierComponent); 2647 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2648 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 2649 getRequiredSharedLibraryLPr( 2650 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED); 2651 } else { 2652 mRequiredVerifierPackage = null; 2653 mRequiredInstallerPackage = null; 2654 mIntentFilterVerifierComponent = null; 2655 mIntentFilterVerifier = null; 2656 mServicesSystemSharedLibraryPackageName = null; 2657 } 2658 2659 mInstallerService = new PackageInstallerService(context, this); 2660 2661 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2662 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2663 // both the installer and resolver must be present to enable ephemeral 2664 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2665 if (DEBUG_EPHEMERAL) { 2666 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2667 + " installer:" + ephemeralInstallerComponent); 2668 } 2669 mEphemeralResolverComponent = ephemeralResolverComponent; 2670 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2671 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2672 mEphemeralResolverConnection = 2673 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2674 } else { 2675 if (DEBUG_EPHEMERAL) { 2676 final String missingComponent = 2677 (ephemeralResolverComponent == null) 2678 ? (ephemeralInstallerComponent == null) 2679 ? "resolver and installer" 2680 : "resolver" 2681 : "installer"; 2682 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2683 } 2684 mEphemeralResolverComponent = null; 2685 mEphemeralInstallerComponent = null; 2686 mEphemeralResolverConnection = null; 2687 } 2688 2689 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2690 } // synchronized (mPackages) 2691 } // synchronized (mInstallLock) 2692 2693 // Now after opening every single application zip, make sure they 2694 // are all flushed. Not really needed, but keeps things nice and 2695 // tidy. 2696 Runtime.getRuntime().gc(); 2697 2698 // The initial scanning above does many calls into installd while 2699 // holding the mPackages lock, but we're mostly interested in yelling 2700 // once we have a booted system. 2701 mInstaller.setWarnIfHeld(mPackages); 2702 2703 // Expose private service for system components to use. 2704 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2705 } 2706 2707 @Override 2708 public boolean isFirstBoot() { 2709 return !mRestoredSettings; 2710 } 2711 2712 @Override 2713 public boolean isOnlyCoreApps() { 2714 return mOnlyCore; 2715 } 2716 2717 @Override 2718 public boolean isUpgrade() { 2719 return mIsUpgrade; 2720 } 2721 2722 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2723 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2724 2725 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2726 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2727 UserHandle.USER_SYSTEM); 2728 if (matches.size() == 1) { 2729 return matches.get(0).getComponentInfo().packageName; 2730 } else { 2731 Log.e(TAG, "There should probably be exactly one verifier; found " + matches); 2732 return null; 2733 } 2734 } 2735 2736 private @NonNull String getRequiredSharedLibraryLPr(String libraryName) { 2737 synchronized (mPackages) { 2738 SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName); 2739 if (libraryEntry == null) { 2740 throw new IllegalStateException("Missing required shared library:" + libraryName); 2741 } 2742 return libraryEntry.apk; 2743 } 2744 } 2745 2746 private @NonNull String getRequiredInstallerLPr() { 2747 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2748 intent.addCategory(Intent.CATEGORY_DEFAULT); 2749 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2750 2751 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2752 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2753 UserHandle.USER_SYSTEM); 2754 if (matches.size() == 1) { 2755 ResolveInfo resolveInfo = matches.get(0); 2756 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 2757 throw new RuntimeException("The installer must be a privileged app"); 2758 } 2759 return matches.get(0).getComponentInfo().packageName; 2760 } else { 2761 throw new RuntimeException("There must be exactly one installer; found " + matches); 2762 } 2763 } 2764 2765 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2766 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2767 2768 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2769 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2770 UserHandle.USER_SYSTEM); 2771 ResolveInfo best = null; 2772 final int N = matches.size(); 2773 for (int i = 0; i < N; i++) { 2774 final ResolveInfo cur = matches.get(i); 2775 final String packageName = cur.getComponentInfo().packageName; 2776 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2777 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2778 continue; 2779 } 2780 2781 if (best == null || cur.priority > best.priority) { 2782 best = cur; 2783 } 2784 } 2785 2786 if (best != null) { 2787 return best.getComponentInfo().getComponentName(); 2788 } else { 2789 throw new RuntimeException("There must be at least one intent filter verifier"); 2790 } 2791 } 2792 2793 private @Nullable ComponentName getEphemeralResolverLPr() { 2794 final String[] packageArray = 2795 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2796 if (packageArray.length == 0) { 2797 if (DEBUG_EPHEMERAL) { 2798 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2799 } 2800 return null; 2801 } 2802 2803 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2804 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 2805 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2806 UserHandle.USER_SYSTEM); 2807 2808 final int N = resolvers.size(); 2809 if (N == 0) { 2810 if (DEBUG_EPHEMERAL) { 2811 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2812 } 2813 return null; 2814 } 2815 2816 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2817 for (int i = 0; i < N; i++) { 2818 final ResolveInfo info = resolvers.get(i); 2819 2820 if (info.serviceInfo == null) { 2821 continue; 2822 } 2823 2824 final String packageName = info.serviceInfo.packageName; 2825 if (!possiblePackages.contains(packageName)) { 2826 if (DEBUG_EPHEMERAL) { 2827 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2828 + " pkg: " + packageName + ", info:" + info); 2829 } 2830 continue; 2831 } 2832 2833 if (DEBUG_EPHEMERAL) { 2834 Slog.v(TAG, "Ephemeral resolver found;" 2835 + " pkg: " + packageName + ", info:" + info); 2836 } 2837 return new ComponentName(packageName, info.serviceInfo.name); 2838 } 2839 if (DEBUG_EPHEMERAL) { 2840 Slog.v(TAG, "Ephemeral resolver NOT found"); 2841 } 2842 return null; 2843 } 2844 2845 private @Nullable ComponentName getEphemeralInstallerLPr() { 2846 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2847 intent.addCategory(Intent.CATEGORY_DEFAULT); 2848 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2849 2850 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2851 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2852 UserHandle.USER_SYSTEM); 2853 if (matches.size() == 0) { 2854 return null; 2855 } else if (matches.size() == 1) { 2856 return matches.get(0).getComponentInfo().getComponentName(); 2857 } else { 2858 throw new RuntimeException( 2859 "There must be at most one ephemeral installer; found " + matches); 2860 } 2861 } 2862 2863 private void primeDomainVerificationsLPw(int userId) { 2864 if (DEBUG_DOMAIN_VERIFICATION) { 2865 Slog.d(TAG, "Priming domain verifications in user " + userId); 2866 } 2867 2868 SystemConfig systemConfig = SystemConfig.getInstance(); 2869 ArraySet<String> packages = systemConfig.getLinkedApps(); 2870 ArraySet<String> domains = new ArraySet<String>(); 2871 2872 for (String packageName : packages) { 2873 PackageParser.Package pkg = mPackages.get(packageName); 2874 if (pkg != null) { 2875 if (!pkg.isSystemApp()) { 2876 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2877 continue; 2878 } 2879 2880 domains.clear(); 2881 for (PackageParser.Activity a : pkg.activities) { 2882 for (ActivityIntentInfo filter : a.intents) { 2883 if (hasValidDomains(filter)) { 2884 domains.addAll(filter.getHostsList()); 2885 } 2886 } 2887 } 2888 2889 if (domains.size() > 0) { 2890 if (DEBUG_DOMAIN_VERIFICATION) { 2891 Slog.v(TAG, " + " + packageName); 2892 } 2893 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2894 // state w.r.t. the formal app-linkage "no verification attempted" state; 2895 // and then 'always' in the per-user state actually used for intent resolution. 2896 final IntentFilterVerificationInfo ivi; 2897 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2898 new ArrayList<String>(domains)); 2899 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2900 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2901 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2902 } else { 2903 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2904 + "' does not handle web links"); 2905 } 2906 } else { 2907 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 2908 } 2909 } 2910 2911 scheduleWritePackageRestrictionsLocked(userId); 2912 scheduleWriteSettingsLocked(); 2913 } 2914 2915 private void applyFactoryDefaultBrowserLPw(int userId) { 2916 // The default browser app's package name is stored in a string resource, 2917 // with a product-specific overlay used for vendor customization. 2918 String browserPkg = mContext.getResources().getString( 2919 com.android.internal.R.string.default_browser); 2920 if (!TextUtils.isEmpty(browserPkg)) { 2921 // non-empty string => required to be a known package 2922 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2923 if (ps == null) { 2924 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2925 browserPkg = null; 2926 } else { 2927 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2928 } 2929 } 2930 2931 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2932 // default. If there's more than one, just leave everything alone. 2933 if (browserPkg == null) { 2934 calculateDefaultBrowserLPw(userId); 2935 } 2936 } 2937 2938 private void calculateDefaultBrowserLPw(int userId) { 2939 List<String> allBrowsers = resolveAllBrowserApps(userId); 2940 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2941 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2942 } 2943 2944 private List<String> resolveAllBrowserApps(int userId) { 2945 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2946 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 2947 PackageManager.MATCH_ALL, userId); 2948 2949 final int count = list.size(); 2950 List<String> result = new ArrayList<String>(count); 2951 for (int i=0; i<count; i++) { 2952 ResolveInfo info = list.get(i); 2953 if (info.activityInfo == null 2954 || !info.handleAllWebDataURI 2955 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2956 || result.contains(info.activityInfo.packageName)) { 2957 continue; 2958 } 2959 result.add(info.activityInfo.packageName); 2960 } 2961 2962 return result; 2963 } 2964 2965 private boolean packageIsBrowser(String packageName, int userId) { 2966 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 2967 PackageManager.MATCH_ALL, userId); 2968 final int N = list.size(); 2969 for (int i = 0; i < N; i++) { 2970 ResolveInfo info = list.get(i); 2971 if (packageName.equals(info.activityInfo.packageName)) { 2972 return true; 2973 } 2974 } 2975 return false; 2976 } 2977 2978 private void checkDefaultBrowser() { 2979 final int myUserId = UserHandle.myUserId(); 2980 final String packageName = getDefaultBrowserPackageName(myUserId); 2981 if (packageName != null) { 2982 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2983 if (info == null) { 2984 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2985 synchronized (mPackages) { 2986 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2987 } 2988 } 2989 } 2990 } 2991 2992 @Override 2993 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2994 throws RemoteException { 2995 try { 2996 return super.onTransact(code, data, reply, flags); 2997 } catch (RuntimeException e) { 2998 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2999 Slog.wtf(TAG, "Package Manager Crash", e); 3000 } 3001 throw e; 3002 } 3003 } 3004 3005 static int[] appendInts(int[] cur, int[] add) { 3006 if (add == null) return cur; 3007 if (cur == null) return add; 3008 final int N = add.length; 3009 for (int i=0; i<N; i++) { 3010 cur = appendInt(cur, add[i]); 3011 } 3012 return cur; 3013 } 3014 3015 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3016 if (!sUserManager.exists(userId)) return null; 3017 if (ps == null) { 3018 return null; 3019 } 3020 final PackageParser.Package p = ps.pkg; 3021 if (p == null) { 3022 return null; 3023 } 3024 3025 final PermissionsState permissionsState = ps.getPermissionsState(); 3026 3027 final int[] gids = permissionsState.computeGids(userId); 3028 final Set<String> permissions = permissionsState.getPermissions(userId); 3029 final PackageUserState state = ps.readUserState(userId); 3030 3031 return PackageParser.generatePackageInfo(p, gids, flags, 3032 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3033 } 3034 3035 @Override 3036 public void checkPackageStartable(String packageName, int userId) { 3037 final boolean userKeyUnlocked = isUserKeyUnlocked(userId); 3038 3039 synchronized (mPackages) { 3040 final PackageSetting ps = mSettings.mPackages.get(packageName); 3041 if (ps == null) { 3042 throw new SecurityException("Package " + packageName + " was not found!"); 3043 } 3044 3045 if (!ps.getInstalled(userId)) { 3046 throw new SecurityException( 3047 "Package " + packageName + " was not installed for user " + userId + "!"); 3048 } 3049 3050 if (mSafeMode && !ps.isSystem()) { 3051 throw new SecurityException("Package " + packageName + " not a system app!"); 3052 } 3053 3054 if (mFrozenPackages.contains(packageName)) { 3055 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3056 } 3057 3058 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3059 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3060 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3061 } 3062 } 3063 } 3064 3065 @Override 3066 public boolean isPackageAvailable(String packageName, int userId) { 3067 if (!sUserManager.exists(userId)) return false; 3068 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3069 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3070 synchronized (mPackages) { 3071 PackageParser.Package p = mPackages.get(packageName); 3072 if (p != null) { 3073 final PackageSetting ps = (PackageSetting) p.mExtras; 3074 if (ps != null) { 3075 final PackageUserState state = ps.readUserState(userId); 3076 if (state != null) { 3077 return PackageParser.isAvailable(state); 3078 } 3079 } 3080 } 3081 } 3082 return false; 3083 } 3084 3085 @Override 3086 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3087 if (!sUserManager.exists(userId)) return null; 3088 flags = updateFlagsForPackage(flags, userId, packageName); 3089 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3090 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3091 // reader 3092 synchronized (mPackages) { 3093 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3094 PackageParser.Package p = null; 3095 if (matchFactoryOnly) { 3096 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3097 if (ps != null) { 3098 return generatePackageInfo(ps, flags, userId); 3099 } 3100 } 3101 if (p == null) { 3102 p = mPackages.get(packageName); 3103 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3104 return null; 3105 } 3106 } 3107 if (DEBUG_PACKAGE_INFO) 3108 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3109 if (p != null) { 3110 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3111 } 3112 if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3113 final PackageSetting ps = mSettings.mPackages.get(packageName); 3114 return generatePackageInfo(ps, flags, userId); 3115 } 3116 } 3117 return null; 3118 } 3119 3120 @Override 3121 public String[] currentToCanonicalPackageNames(String[] names) { 3122 String[] out = new String[names.length]; 3123 // reader 3124 synchronized (mPackages) { 3125 for (int i=names.length-1; i>=0; i--) { 3126 PackageSetting ps = mSettings.mPackages.get(names[i]); 3127 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3128 } 3129 } 3130 return out; 3131 } 3132 3133 @Override 3134 public String[] canonicalToCurrentPackageNames(String[] names) { 3135 String[] out = new String[names.length]; 3136 // reader 3137 synchronized (mPackages) { 3138 for (int i=names.length-1; i>=0; i--) { 3139 String cur = mSettings.mRenamedPackages.get(names[i]); 3140 out[i] = cur != null ? cur : names[i]; 3141 } 3142 } 3143 return out; 3144 } 3145 3146 @Override 3147 public int getPackageUid(String packageName, int flags, int userId) { 3148 if (!sUserManager.exists(userId)) return -1; 3149 flags = updateFlagsForPackage(flags, userId, packageName); 3150 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3151 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3152 3153 // reader 3154 synchronized (mPackages) { 3155 final PackageParser.Package p = mPackages.get(packageName); 3156 if (p != null && p.isMatch(flags)) { 3157 return UserHandle.getUid(userId, p.applicationInfo.uid); 3158 } 3159 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3160 final PackageSetting ps = mSettings.mPackages.get(packageName); 3161 if (ps != null && ps.isMatch(flags)) { 3162 return UserHandle.getUid(userId, ps.appId); 3163 } 3164 } 3165 } 3166 3167 return -1; 3168 } 3169 3170 @Override 3171 public int[] getPackageGids(String packageName, int flags, int userId) { 3172 if (!sUserManager.exists(userId)) return null; 3173 flags = updateFlagsForPackage(flags, userId, packageName); 3174 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3175 false /* requireFullPermission */, false /* checkShell */, 3176 "getPackageGids"); 3177 3178 // reader 3179 synchronized (mPackages) { 3180 final PackageParser.Package p = mPackages.get(packageName); 3181 if (p != null && p.isMatch(flags)) { 3182 PackageSetting ps = (PackageSetting) p.mExtras; 3183 return ps.getPermissionsState().computeGids(userId); 3184 } 3185 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3186 final PackageSetting ps = mSettings.mPackages.get(packageName); 3187 if (ps != null && ps.isMatch(flags)) { 3188 return ps.getPermissionsState().computeGids(userId); 3189 } 3190 } 3191 } 3192 3193 return null; 3194 } 3195 3196 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3197 if (bp.perm != null) { 3198 return PackageParser.generatePermissionInfo(bp.perm, flags); 3199 } 3200 PermissionInfo pi = new PermissionInfo(); 3201 pi.name = bp.name; 3202 pi.packageName = bp.sourcePackage; 3203 pi.nonLocalizedLabel = bp.name; 3204 pi.protectionLevel = bp.protectionLevel; 3205 return pi; 3206 } 3207 3208 @Override 3209 public PermissionInfo getPermissionInfo(String name, int flags) { 3210 // reader 3211 synchronized (mPackages) { 3212 final BasePermission p = mSettings.mPermissions.get(name); 3213 if (p != null) { 3214 return generatePermissionInfo(p, flags); 3215 } 3216 return null; 3217 } 3218 } 3219 3220 @Override 3221 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3222 int flags) { 3223 // reader 3224 synchronized (mPackages) { 3225 if (group != null && !mPermissionGroups.containsKey(group)) { 3226 // This is thrown as NameNotFoundException 3227 return null; 3228 } 3229 3230 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3231 for (BasePermission p : mSettings.mPermissions.values()) { 3232 if (group == null) { 3233 if (p.perm == null || p.perm.info.group == null) { 3234 out.add(generatePermissionInfo(p, flags)); 3235 } 3236 } else { 3237 if (p.perm != null && group.equals(p.perm.info.group)) { 3238 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3239 } 3240 } 3241 } 3242 return new ParceledListSlice<>(out); 3243 } 3244 } 3245 3246 @Override 3247 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3248 // reader 3249 synchronized (mPackages) { 3250 return PackageParser.generatePermissionGroupInfo( 3251 mPermissionGroups.get(name), flags); 3252 } 3253 } 3254 3255 @Override 3256 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3257 // reader 3258 synchronized (mPackages) { 3259 final int N = mPermissionGroups.size(); 3260 ArrayList<PermissionGroupInfo> out 3261 = new ArrayList<PermissionGroupInfo>(N); 3262 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3263 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3264 } 3265 return new ParceledListSlice<>(out); 3266 } 3267 } 3268 3269 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3270 int userId) { 3271 if (!sUserManager.exists(userId)) return null; 3272 PackageSetting ps = mSettings.mPackages.get(packageName); 3273 if (ps != null) { 3274 if (ps.pkg == null) { 3275 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3276 if (pInfo != null) { 3277 return pInfo.applicationInfo; 3278 } 3279 return null; 3280 } 3281 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3282 ps.readUserState(userId), userId); 3283 } 3284 return null; 3285 } 3286 3287 @Override 3288 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3289 if (!sUserManager.exists(userId)) return null; 3290 flags = updateFlagsForApplication(flags, userId, packageName); 3291 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3292 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3293 // writer 3294 synchronized (mPackages) { 3295 PackageParser.Package p = mPackages.get(packageName); 3296 if (DEBUG_PACKAGE_INFO) Log.v( 3297 TAG, "getApplicationInfo " + packageName 3298 + ": " + p); 3299 if (p != null) { 3300 PackageSetting ps = mSettings.mPackages.get(packageName); 3301 if (ps == null) return null; 3302 // Note: isEnabledLP() does not apply here - always return info 3303 return PackageParser.generateApplicationInfo( 3304 p, flags, ps.readUserState(userId), userId); 3305 } 3306 if ("android".equals(packageName)||"system".equals(packageName)) { 3307 return mAndroidApplication; 3308 } 3309 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3310 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3311 } 3312 } 3313 return null; 3314 } 3315 3316 @Override 3317 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3318 final IPackageDataObserver observer) { 3319 mContext.enforceCallingOrSelfPermission( 3320 android.Manifest.permission.CLEAR_APP_CACHE, null); 3321 // Queue up an async operation since clearing cache may take a little while. 3322 mHandler.post(new Runnable() { 3323 public void run() { 3324 mHandler.removeCallbacks(this); 3325 boolean success = true; 3326 synchronized (mInstallLock) { 3327 try { 3328 mInstaller.freeCache(volumeUuid, freeStorageSize); 3329 } catch (InstallerException e) { 3330 Slog.w(TAG, "Couldn't clear application caches: " + e); 3331 success = false; 3332 } 3333 } 3334 if (observer != null) { 3335 try { 3336 observer.onRemoveCompleted(null, success); 3337 } catch (RemoteException e) { 3338 Slog.w(TAG, "RemoveException when invoking call back"); 3339 } 3340 } 3341 } 3342 }); 3343 } 3344 3345 @Override 3346 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3347 final IntentSender pi) { 3348 mContext.enforceCallingOrSelfPermission( 3349 android.Manifest.permission.CLEAR_APP_CACHE, null); 3350 // Queue up an async operation since clearing cache may take a little while. 3351 mHandler.post(new Runnable() { 3352 public void run() { 3353 mHandler.removeCallbacks(this); 3354 boolean success = true; 3355 synchronized (mInstallLock) { 3356 try { 3357 mInstaller.freeCache(volumeUuid, freeStorageSize); 3358 } catch (InstallerException e) { 3359 Slog.w(TAG, "Couldn't clear application caches: " + e); 3360 success = false; 3361 } 3362 } 3363 if(pi != null) { 3364 try { 3365 // Callback via pending intent 3366 int code = success ? 1 : 0; 3367 pi.sendIntent(null, code, null, 3368 null, null); 3369 } catch (SendIntentException e1) { 3370 Slog.i(TAG, "Failed to send pending intent"); 3371 } 3372 } 3373 } 3374 }); 3375 } 3376 3377 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3378 synchronized (mInstallLock) { 3379 try { 3380 mInstaller.freeCache(volumeUuid, freeStorageSize); 3381 } catch (InstallerException e) { 3382 throw new IOException("Failed to free enough space", e); 3383 } 3384 } 3385 } 3386 3387 /** 3388 * Return if the user key is currently unlocked. 3389 */ 3390 private boolean isUserKeyUnlocked(int userId) { 3391 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 3392 final IMountService mount = IMountService.Stub 3393 .asInterface(ServiceManager.getService("mount")); 3394 if (mount == null) { 3395 Slog.w(TAG, "Early during boot, assuming locked"); 3396 return false; 3397 } 3398 final long token = Binder.clearCallingIdentity(); 3399 try { 3400 return mount.isUserKeyUnlocked(userId); 3401 } catch (RemoteException e) { 3402 throw e.rethrowAsRuntimeException(); 3403 } finally { 3404 Binder.restoreCallingIdentity(token); 3405 } 3406 } else { 3407 return true; 3408 } 3409 } 3410 3411 /** 3412 * Update given flags based on encryption status of current user. 3413 */ 3414 private int updateFlags(int flags, int userId) { 3415 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3416 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3417 // Caller expressed an explicit opinion about what encryption 3418 // aware/unaware components they want to see, so fall through and 3419 // give them what they want 3420 } else { 3421 // Caller expressed no opinion, so match based on user state 3422 if (isUserKeyUnlocked(userId)) { 3423 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3424 } else { 3425 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3426 } 3427 } 3428 return flags; 3429 } 3430 3431 /** 3432 * Update given flags when being used to request {@link PackageInfo}. 3433 */ 3434 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3435 boolean triaged = true; 3436 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3437 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3438 // Caller is asking for component details, so they'd better be 3439 // asking for specific encryption matching behavior, or be triaged 3440 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3441 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3442 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3443 triaged = false; 3444 } 3445 } 3446 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3447 | PackageManager.MATCH_SYSTEM_ONLY 3448 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3449 triaged = false; 3450 } 3451 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3452 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3453 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3454 } 3455 return updateFlags(flags, userId); 3456 } 3457 3458 /** 3459 * Update given flags when being used to request {@link ApplicationInfo}. 3460 */ 3461 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3462 return updateFlagsForPackage(flags, userId, cookie); 3463 } 3464 3465 /** 3466 * Update given flags when being used to request {@link ComponentInfo}. 3467 */ 3468 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3469 if (cookie instanceof Intent) { 3470 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3471 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3472 } 3473 } 3474 3475 boolean triaged = true; 3476 // Caller is asking for component details, so they'd better be 3477 // asking for specific encryption matching behavior, or be triaged 3478 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3479 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3480 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3481 triaged = false; 3482 } 3483 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3484 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3485 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3486 } 3487 3488 return updateFlags(flags, userId); 3489 } 3490 3491 /** 3492 * Update given flags when being used to request {@link ResolveInfo}. 3493 */ 3494 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3495 // Safe mode means we shouldn't match any third-party components 3496 if (mSafeMode) { 3497 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3498 } 3499 3500 return updateFlagsForComponent(flags, userId, cookie); 3501 } 3502 3503 @Override 3504 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3505 if (!sUserManager.exists(userId)) return null; 3506 flags = updateFlagsForComponent(flags, userId, component); 3507 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3508 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3509 synchronized (mPackages) { 3510 PackageParser.Activity a = mActivities.mActivities.get(component); 3511 3512 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3513 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3514 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3515 if (ps == null) return null; 3516 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3517 userId); 3518 } 3519 if (mResolveComponentName.equals(component)) { 3520 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3521 new PackageUserState(), userId); 3522 } 3523 } 3524 return null; 3525 } 3526 3527 @Override 3528 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3529 String resolvedType) { 3530 synchronized (mPackages) { 3531 if (component.equals(mResolveComponentName)) { 3532 // The resolver supports EVERYTHING! 3533 return true; 3534 } 3535 PackageParser.Activity a = mActivities.mActivities.get(component); 3536 if (a == null) { 3537 return false; 3538 } 3539 for (int i=0; i<a.intents.size(); i++) { 3540 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3541 intent.getData(), intent.getCategories(), TAG) >= 0) { 3542 return true; 3543 } 3544 } 3545 return false; 3546 } 3547 } 3548 3549 @Override 3550 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3551 if (!sUserManager.exists(userId)) return null; 3552 flags = updateFlagsForComponent(flags, userId, component); 3553 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3554 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3555 synchronized (mPackages) { 3556 PackageParser.Activity a = mReceivers.mActivities.get(component); 3557 if (DEBUG_PACKAGE_INFO) Log.v( 3558 TAG, "getReceiverInfo " + component + ": " + a); 3559 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3560 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3561 if (ps == null) return null; 3562 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3563 userId); 3564 } 3565 } 3566 return null; 3567 } 3568 3569 @Override 3570 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3571 if (!sUserManager.exists(userId)) return null; 3572 flags = updateFlagsForComponent(flags, userId, component); 3573 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3574 false /* requireFullPermission */, false /* checkShell */, "get service info"); 3575 synchronized (mPackages) { 3576 PackageParser.Service s = mServices.mServices.get(component); 3577 if (DEBUG_PACKAGE_INFO) Log.v( 3578 TAG, "getServiceInfo " + component + ": " + s); 3579 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3580 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3581 if (ps == null) return null; 3582 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3583 userId); 3584 } 3585 } 3586 return null; 3587 } 3588 3589 @Override 3590 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3591 if (!sUserManager.exists(userId)) return null; 3592 flags = updateFlagsForComponent(flags, userId, component); 3593 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3594 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 3595 synchronized (mPackages) { 3596 PackageParser.Provider p = mProviders.mProviders.get(component); 3597 if (DEBUG_PACKAGE_INFO) Log.v( 3598 TAG, "getProviderInfo " + component + ": " + p); 3599 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3600 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3601 if (ps == null) return null; 3602 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3603 userId); 3604 } 3605 } 3606 return null; 3607 } 3608 3609 @Override 3610 public String[] getSystemSharedLibraryNames() { 3611 Set<String> libSet; 3612 synchronized (mPackages) { 3613 libSet = mSharedLibraries.keySet(); 3614 int size = libSet.size(); 3615 if (size > 0) { 3616 String[] libs = new String[size]; 3617 libSet.toArray(libs); 3618 return libs; 3619 } 3620 } 3621 return null; 3622 } 3623 3624 @Override 3625 public @NonNull String getServicesSystemSharedLibraryPackageName() { 3626 synchronized (mPackages) { 3627 return mServicesSystemSharedLibraryPackageName; 3628 } 3629 } 3630 3631 @Override 3632 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 3633 synchronized (mPackages) { 3634 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values()); 3635 3636 final FeatureInfo fi = new FeatureInfo(); 3637 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3638 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3639 res.add(fi); 3640 3641 return new ParceledListSlice<>(res); 3642 } 3643 } 3644 3645 @Override 3646 public boolean hasSystemFeature(String name, int version) { 3647 synchronized (mPackages) { 3648 final FeatureInfo feat = mAvailableFeatures.get(name); 3649 if (feat == null) { 3650 return false; 3651 } else { 3652 return feat.version >= version; 3653 } 3654 } 3655 } 3656 3657 @Override 3658 public int checkPermission(String permName, String pkgName, int userId) { 3659 if (!sUserManager.exists(userId)) { 3660 return PackageManager.PERMISSION_DENIED; 3661 } 3662 3663 synchronized (mPackages) { 3664 final PackageParser.Package p = mPackages.get(pkgName); 3665 if (p != null && p.mExtras != null) { 3666 final PackageSetting ps = (PackageSetting) p.mExtras; 3667 final PermissionsState permissionsState = ps.getPermissionsState(); 3668 if (permissionsState.hasPermission(permName, userId)) { 3669 return PackageManager.PERMISSION_GRANTED; 3670 } 3671 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3672 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3673 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3674 return PackageManager.PERMISSION_GRANTED; 3675 } 3676 } 3677 } 3678 3679 return PackageManager.PERMISSION_DENIED; 3680 } 3681 3682 @Override 3683 public int checkUidPermission(String permName, int uid) { 3684 final int userId = UserHandle.getUserId(uid); 3685 3686 if (!sUserManager.exists(userId)) { 3687 return PackageManager.PERMISSION_DENIED; 3688 } 3689 3690 synchronized (mPackages) { 3691 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3692 if (obj != null) { 3693 final SettingBase ps = (SettingBase) obj; 3694 final PermissionsState permissionsState = ps.getPermissionsState(); 3695 if (permissionsState.hasPermission(permName, userId)) { 3696 return PackageManager.PERMISSION_GRANTED; 3697 } 3698 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3699 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3700 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3701 return PackageManager.PERMISSION_GRANTED; 3702 } 3703 } else { 3704 ArraySet<String> perms = mSystemPermissions.get(uid); 3705 if (perms != null) { 3706 if (perms.contains(permName)) { 3707 return PackageManager.PERMISSION_GRANTED; 3708 } 3709 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3710 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3711 return PackageManager.PERMISSION_GRANTED; 3712 } 3713 } 3714 } 3715 } 3716 3717 return PackageManager.PERMISSION_DENIED; 3718 } 3719 3720 @Override 3721 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3722 if (UserHandle.getCallingUserId() != userId) { 3723 mContext.enforceCallingPermission( 3724 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3725 "isPermissionRevokedByPolicy for user " + userId); 3726 } 3727 3728 if (checkPermission(permission, packageName, userId) 3729 == PackageManager.PERMISSION_GRANTED) { 3730 return false; 3731 } 3732 3733 final long identity = Binder.clearCallingIdentity(); 3734 try { 3735 final int flags = getPermissionFlags(permission, packageName, userId); 3736 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3737 } finally { 3738 Binder.restoreCallingIdentity(identity); 3739 } 3740 } 3741 3742 @Override 3743 public String getPermissionControllerPackageName() { 3744 synchronized (mPackages) { 3745 return mRequiredInstallerPackage; 3746 } 3747 } 3748 3749 /** 3750 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3751 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3752 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3753 * @param message the message to log on security exception 3754 */ 3755 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3756 boolean checkShell, String message) { 3757 if (userId < 0) { 3758 throw new IllegalArgumentException("Invalid userId " + userId); 3759 } 3760 if (checkShell) { 3761 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3762 } 3763 if (userId == UserHandle.getUserId(callingUid)) return; 3764 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3765 if (requireFullPermission) { 3766 mContext.enforceCallingOrSelfPermission( 3767 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3768 } else { 3769 try { 3770 mContext.enforceCallingOrSelfPermission( 3771 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3772 } catch (SecurityException se) { 3773 mContext.enforceCallingOrSelfPermission( 3774 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3775 } 3776 } 3777 } 3778 } 3779 3780 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3781 if (callingUid == Process.SHELL_UID) { 3782 if (userHandle >= 0 3783 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3784 throw new SecurityException("Shell does not have permission to access user " 3785 + userHandle); 3786 } else if (userHandle < 0) { 3787 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3788 + Debug.getCallers(3)); 3789 } 3790 } 3791 } 3792 3793 private BasePermission findPermissionTreeLP(String permName) { 3794 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3795 if (permName.startsWith(bp.name) && 3796 permName.length() > bp.name.length() && 3797 permName.charAt(bp.name.length()) == '.') { 3798 return bp; 3799 } 3800 } 3801 return null; 3802 } 3803 3804 private BasePermission checkPermissionTreeLP(String permName) { 3805 if (permName != null) { 3806 BasePermission bp = findPermissionTreeLP(permName); 3807 if (bp != null) { 3808 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3809 return bp; 3810 } 3811 throw new SecurityException("Calling uid " 3812 + Binder.getCallingUid() 3813 + " is not allowed to add to permission tree " 3814 + bp.name + " owned by uid " + bp.uid); 3815 } 3816 } 3817 throw new SecurityException("No permission tree found for " + permName); 3818 } 3819 3820 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3821 if (s1 == null) { 3822 return s2 == null; 3823 } 3824 if (s2 == null) { 3825 return false; 3826 } 3827 if (s1.getClass() != s2.getClass()) { 3828 return false; 3829 } 3830 return s1.equals(s2); 3831 } 3832 3833 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3834 if (pi1.icon != pi2.icon) return false; 3835 if (pi1.logo != pi2.logo) return false; 3836 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3837 if (!compareStrings(pi1.name, pi2.name)) return false; 3838 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3839 // We'll take care of setting this one. 3840 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3841 // These are not currently stored in settings. 3842 //if (!compareStrings(pi1.group, pi2.group)) return false; 3843 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3844 //if (pi1.labelRes != pi2.labelRes) return false; 3845 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3846 return true; 3847 } 3848 3849 int permissionInfoFootprint(PermissionInfo info) { 3850 int size = info.name.length(); 3851 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3852 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3853 return size; 3854 } 3855 3856 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3857 int size = 0; 3858 for (BasePermission perm : mSettings.mPermissions.values()) { 3859 if (perm.uid == tree.uid) { 3860 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3861 } 3862 } 3863 return size; 3864 } 3865 3866 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3867 // We calculate the max size of permissions defined by this uid and throw 3868 // if that plus the size of 'info' would exceed our stated maximum. 3869 if (tree.uid != Process.SYSTEM_UID) { 3870 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3871 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3872 throw new SecurityException("Permission tree size cap exceeded"); 3873 } 3874 } 3875 } 3876 3877 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3878 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3879 throw new SecurityException("Label must be specified in permission"); 3880 } 3881 BasePermission tree = checkPermissionTreeLP(info.name); 3882 BasePermission bp = mSettings.mPermissions.get(info.name); 3883 boolean added = bp == null; 3884 boolean changed = true; 3885 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3886 if (added) { 3887 enforcePermissionCapLocked(info, tree); 3888 bp = new BasePermission(info.name, tree.sourcePackage, 3889 BasePermission.TYPE_DYNAMIC); 3890 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3891 throw new SecurityException( 3892 "Not allowed to modify non-dynamic permission " 3893 + info.name); 3894 } else { 3895 if (bp.protectionLevel == fixedLevel 3896 && bp.perm.owner.equals(tree.perm.owner) 3897 && bp.uid == tree.uid 3898 && comparePermissionInfos(bp.perm.info, info)) { 3899 changed = false; 3900 } 3901 } 3902 bp.protectionLevel = fixedLevel; 3903 info = new PermissionInfo(info); 3904 info.protectionLevel = fixedLevel; 3905 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3906 bp.perm.info.packageName = tree.perm.info.packageName; 3907 bp.uid = tree.uid; 3908 if (added) { 3909 mSettings.mPermissions.put(info.name, bp); 3910 } 3911 if (changed) { 3912 if (!async) { 3913 mSettings.writeLPr(); 3914 } else { 3915 scheduleWriteSettingsLocked(); 3916 } 3917 } 3918 return added; 3919 } 3920 3921 @Override 3922 public boolean addPermission(PermissionInfo info) { 3923 synchronized (mPackages) { 3924 return addPermissionLocked(info, false); 3925 } 3926 } 3927 3928 @Override 3929 public boolean addPermissionAsync(PermissionInfo info) { 3930 synchronized (mPackages) { 3931 return addPermissionLocked(info, true); 3932 } 3933 } 3934 3935 @Override 3936 public void removePermission(String name) { 3937 synchronized (mPackages) { 3938 checkPermissionTreeLP(name); 3939 BasePermission bp = mSettings.mPermissions.get(name); 3940 if (bp != null) { 3941 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3942 throw new SecurityException( 3943 "Not allowed to modify non-dynamic permission " 3944 + name); 3945 } 3946 mSettings.mPermissions.remove(name); 3947 mSettings.writeLPr(); 3948 } 3949 } 3950 } 3951 3952 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 3953 BasePermission bp) { 3954 int index = pkg.requestedPermissions.indexOf(bp.name); 3955 if (index == -1) { 3956 throw new SecurityException("Package " + pkg.packageName 3957 + " has not requested permission " + bp.name); 3958 } 3959 if (!bp.isRuntime() && !bp.isDevelopment()) { 3960 throw new SecurityException("Permission " + bp.name 3961 + " is not a changeable permission type"); 3962 } 3963 } 3964 3965 @Override 3966 public void grantRuntimePermission(String packageName, String name, final int userId) { 3967 if (!sUserManager.exists(userId)) { 3968 Log.e(TAG, "No such user:" + userId); 3969 return; 3970 } 3971 3972 mContext.enforceCallingOrSelfPermission( 3973 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 3974 "grantRuntimePermission"); 3975 3976 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3977 true /* requireFullPermission */, true /* checkShell */, 3978 "grantRuntimePermission"); 3979 3980 final int uid; 3981 final SettingBase sb; 3982 3983 synchronized (mPackages) { 3984 final PackageParser.Package pkg = mPackages.get(packageName); 3985 if (pkg == null) { 3986 throw new IllegalArgumentException("Unknown package: " + packageName); 3987 } 3988 3989 final BasePermission bp = mSettings.mPermissions.get(name); 3990 if (bp == null) { 3991 throw new IllegalArgumentException("Unknown permission: " + name); 3992 } 3993 3994 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3995 3996 // If a permission review is required for legacy apps we represent 3997 // their permissions as always granted runtime ones since we need 3998 // to keep the review required permission flag per user while an 3999 // install permission's state is shared across all users. 4000 if (Build.PERMISSIONS_REVIEW_REQUIRED 4001 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4002 && bp.isRuntime()) { 4003 return; 4004 } 4005 4006 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4007 sb = (SettingBase) pkg.mExtras; 4008 if (sb == null) { 4009 throw new IllegalArgumentException("Unknown package: " + packageName); 4010 } 4011 4012 final PermissionsState permissionsState = sb.getPermissionsState(); 4013 4014 final int flags = permissionsState.getPermissionFlags(name, userId); 4015 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4016 throw new SecurityException("Cannot grant system fixed permission " 4017 + name + " for package " + packageName); 4018 } 4019 4020 if (bp.isDevelopment()) { 4021 // Development permissions must be handled specially, since they are not 4022 // normal runtime permissions. For now they apply to all users. 4023 if (permissionsState.grantInstallPermission(bp) != 4024 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4025 scheduleWriteSettingsLocked(); 4026 } 4027 return; 4028 } 4029 4030 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4031 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4032 return; 4033 } 4034 4035 final int result = permissionsState.grantRuntimePermission(bp, userId); 4036 switch (result) { 4037 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4038 return; 4039 } 4040 4041 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4042 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4043 mHandler.post(new Runnable() { 4044 @Override 4045 public void run() { 4046 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4047 } 4048 }); 4049 } 4050 break; 4051 } 4052 4053 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4054 4055 // Not critical if that is lost - app has to request again. 4056 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4057 } 4058 4059 // Only need to do this if user is initialized. Otherwise it's a new user 4060 // and there are no processes running as the user yet and there's no need 4061 // to make an expensive call to remount processes for the changed permissions. 4062 if (READ_EXTERNAL_STORAGE.equals(name) 4063 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4064 final long token = Binder.clearCallingIdentity(); 4065 try { 4066 if (sUserManager.isInitialized(userId)) { 4067 MountServiceInternal mountServiceInternal = LocalServices.getService( 4068 MountServiceInternal.class); 4069 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 4070 } 4071 } finally { 4072 Binder.restoreCallingIdentity(token); 4073 } 4074 } 4075 } 4076 4077 @Override 4078 public void revokeRuntimePermission(String packageName, String name, int userId) { 4079 if (!sUserManager.exists(userId)) { 4080 Log.e(TAG, "No such user:" + userId); 4081 return; 4082 } 4083 4084 mContext.enforceCallingOrSelfPermission( 4085 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4086 "revokeRuntimePermission"); 4087 4088 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4089 true /* requireFullPermission */, true /* checkShell */, 4090 "revokeRuntimePermission"); 4091 4092 final int appId; 4093 4094 synchronized (mPackages) { 4095 final PackageParser.Package pkg = mPackages.get(packageName); 4096 if (pkg == null) { 4097 throw new IllegalArgumentException("Unknown package: " + packageName); 4098 } 4099 4100 final BasePermission bp = mSettings.mPermissions.get(name); 4101 if (bp == null) { 4102 throw new IllegalArgumentException("Unknown permission: " + name); 4103 } 4104 4105 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4106 4107 // If a permission review is required for legacy apps we represent 4108 // their permissions as always granted runtime ones since we need 4109 // to keep the review required permission flag per user while an 4110 // install permission's state is shared across all users. 4111 if (Build.PERMISSIONS_REVIEW_REQUIRED 4112 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4113 && bp.isRuntime()) { 4114 return; 4115 } 4116 4117 SettingBase sb = (SettingBase) pkg.mExtras; 4118 if (sb == null) { 4119 throw new IllegalArgumentException("Unknown package: " + packageName); 4120 } 4121 4122 final PermissionsState permissionsState = sb.getPermissionsState(); 4123 4124 final int flags = permissionsState.getPermissionFlags(name, userId); 4125 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4126 throw new SecurityException("Cannot revoke system fixed permission " 4127 + name + " for package " + packageName); 4128 } 4129 4130 if (bp.isDevelopment()) { 4131 // Development permissions must be handled specially, since they are not 4132 // normal runtime permissions. For now they apply to all users. 4133 if (permissionsState.revokeInstallPermission(bp) != 4134 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4135 scheduleWriteSettingsLocked(); 4136 } 4137 return; 4138 } 4139 4140 if (permissionsState.revokeRuntimePermission(bp, userId) == 4141 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4142 return; 4143 } 4144 4145 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4146 4147 // Critical, after this call app should never have the permission. 4148 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4149 4150 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4151 } 4152 4153 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4154 } 4155 4156 @Override 4157 public void resetRuntimePermissions() { 4158 mContext.enforceCallingOrSelfPermission( 4159 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4160 "revokeRuntimePermission"); 4161 4162 int callingUid = Binder.getCallingUid(); 4163 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4164 mContext.enforceCallingOrSelfPermission( 4165 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4166 "resetRuntimePermissions"); 4167 } 4168 4169 synchronized (mPackages) { 4170 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4171 for (int userId : UserManagerService.getInstance().getUserIds()) { 4172 final int packageCount = mPackages.size(); 4173 for (int i = 0; i < packageCount; i++) { 4174 PackageParser.Package pkg = mPackages.valueAt(i); 4175 if (!(pkg.mExtras instanceof PackageSetting)) { 4176 continue; 4177 } 4178 PackageSetting ps = (PackageSetting) pkg.mExtras; 4179 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4180 } 4181 } 4182 } 4183 } 4184 4185 @Override 4186 public int getPermissionFlags(String name, String packageName, int userId) { 4187 if (!sUserManager.exists(userId)) { 4188 return 0; 4189 } 4190 4191 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4192 4193 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4194 true /* requireFullPermission */, false /* checkShell */, 4195 "getPermissionFlags"); 4196 4197 synchronized (mPackages) { 4198 final PackageParser.Package pkg = mPackages.get(packageName); 4199 if (pkg == null) { 4200 throw new IllegalArgumentException("Unknown package: " + packageName); 4201 } 4202 4203 final BasePermission bp = mSettings.mPermissions.get(name); 4204 if (bp == null) { 4205 throw new IllegalArgumentException("Unknown permission: " + name); 4206 } 4207 4208 SettingBase sb = (SettingBase) pkg.mExtras; 4209 if (sb == null) { 4210 throw new IllegalArgumentException("Unknown package: " + packageName); 4211 } 4212 4213 PermissionsState permissionsState = sb.getPermissionsState(); 4214 return permissionsState.getPermissionFlags(name, userId); 4215 } 4216 } 4217 4218 @Override 4219 public void updatePermissionFlags(String name, String packageName, int flagMask, 4220 int flagValues, int userId) { 4221 if (!sUserManager.exists(userId)) { 4222 return; 4223 } 4224 4225 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4226 4227 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4228 true /* requireFullPermission */, true /* checkShell */, 4229 "updatePermissionFlags"); 4230 4231 // Only the system can change these flags and nothing else. 4232 if (getCallingUid() != Process.SYSTEM_UID) { 4233 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4234 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4235 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4236 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4237 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4238 } 4239 4240 synchronized (mPackages) { 4241 final PackageParser.Package pkg = mPackages.get(packageName); 4242 if (pkg == null) { 4243 throw new IllegalArgumentException("Unknown package: " + packageName); 4244 } 4245 4246 final BasePermission bp = mSettings.mPermissions.get(name); 4247 if (bp == null) { 4248 throw new IllegalArgumentException("Unknown permission: " + name); 4249 } 4250 4251 SettingBase sb = (SettingBase) pkg.mExtras; 4252 if (sb == null) { 4253 throw new IllegalArgumentException("Unknown package: " + packageName); 4254 } 4255 4256 PermissionsState permissionsState = sb.getPermissionsState(); 4257 4258 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4259 4260 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4261 // Install and runtime permissions are stored in different places, 4262 // so figure out what permission changed and persist the change. 4263 if (permissionsState.getInstallPermissionState(name) != null) { 4264 scheduleWriteSettingsLocked(); 4265 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4266 || hadState) { 4267 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4268 } 4269 } 4270 } 4271 } 4272 4273 /** 4274 * Update the permission flags for all packages and runtime permissions of a user in order 4275 * to allow device or profile owner to remove POLICY_FIXED. 4276 */ 4277 @Override 4278 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4279 if (!sUserManager.exists(userId)) { 4280 return; 4281 } 4282 4283 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4284 4285 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4286 true /* requireFullPermission */, true /* checkShell */, 4287 "updatePermissionFlagsForAllApps"); 4288 4289 // Only the system can change system fixed flags. 4290 if (getCallingUid() != Process.SYSTEM_UID) { 4291 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4292 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4293 } 4294 4295 synchronized (mPackages) { 4296 boolean changed = false; 4297 final int packageCount = mPackages.size(); 4298 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4299 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4300 SettingBase sb = (SettingBase) pkg.mExtras; 4301 if (sb == null) { 4302 continue; 4303 } 4304 PermissionsState permissionsState = sb.getPermissionsState(); 4305 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4306 userId, flagMask, flagValues); 4307 } 4308 if (changed) { 4309 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4310 } 4311 } 4312 } 4313 4314 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4315 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4316 != PackageManager.PERMISSION_GRANTED 4317 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4318 != PackageManager.PERMISSION_GRANTED) { 4319 throw new SecurityException(message + " requires " 4320 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4321 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4322 } 4323 } 4324 4325 @Override 4326 public boolean shouldShowRequestPermissionRationale(String permissionName, 4327 String packageName, int userId) { 4328 if (UserHandle.getCallingUserId() != userId) { 4329 mContext.enforceCallingPermission( 4330 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4331 "canShowRequestPermissionRationale for user " + userId); 4332 } 4333 4334 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4335 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4336 return false; 4337 } 4338 4339 if (checkPermission(permissionName, packageName, userId) 4340 == PackageManager.PERMISSION_GRANTED) { 4341 return false; 4342 } 4343 4344 final int flags; 4345 4346 final long identity = Binder.clearCallingIdentity(); 4347 try { 4348 flags = getPermissionFlags(permissionName, 4349 packageName, userId); 4350 } finally { 4351 Binder.restoreCallingIdentity(identity); 4352 } 4353 4354 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4355 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4356 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4357 4358 if ((flags & fixedFlags) != 0) { 4359 return false; 4360 } 4361 4362 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4363 } 4364 4365 @Override 4366 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4367 mContext.enforceCallingOrSelfPermission( 4368 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4369 "addOnPermissionsChangeListener"); 4370 4371 synchronized (mPackages) { 4372 mOnPermissionChangeListeners.addListenerLocked(listener); 4373 } 4374 } 4375 4376 @Override 4377 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4378 synchronized (mPackages) { 4379 mOnPermissionChangeListeners.removeListenerLocked(listener); 4380 } 4381 } 4382 4383 @Override 4384 public boolean isProtectedBroadcast(String actionName) { 4385 synchronized (mPackages) { 4386 if (mProtectedBroadcasts.contains(actionName)) { 4387 return true; 4388 } else if (actionName != null) { 4389 // TODO: remove these terrible hacks 4390 if (actionName.startsWith("android.net.netmon.lingerExpired") 4391 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4392 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 4393 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 4394 return true; 4395 } 4396 } 4397 } 4398 return false; 4399 } 4400 4401 @Override 4402 public int checkSignatures(String pkg1, String pkg2) { 4403 synchronized (mPackages) { 4404 final PackageParser.Package p1 = mPackages.get(pkg1); 4405 final PackageParser.Package p2 = mPackages.get(pkg2); 4406 if (p1 == null || p1.mExtras == null 4407 || p2 == null || p2.mExtras == null) { 4408 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4409 } 4410 return compareSignatures(p1.mSignatures, p2.mSignatures); 4411 } 4412 } 4413 4414 @Override 4415 public int checkUidSignatures(int uid1, int uid2) { 4416 // Map to base uids. 4417 uid1 = UserHandle.getAppId(uid1); 4418 uid2 = UserHandle.getAppId(uid2); 4419 // reader 4420 synchronized (mPackages) { 4421 Signature[] s1; 4422 Signature[] s2; 4423 Object obj = mSettings.getUserIdLPr(uid1); 4424 if (obj != null) { 4425 if (obj instanceof SharedUserSetting) { 4426 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4427 } else if (obj instanceof PackageSetting) { 4428 s1 = ((PackageSetting)obj).signatures.mSignatures; 4429 } else { 4430 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4431 } 4432 } else { 4433 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4434 } 4435 obj = mSettings.getUserIdLPr(uid2); 4436 if (obj != null) { 4437 if (obj instanceof SharedUserSetting) { 4438 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4439 } else if (obj instanceof PackageSetting) { 4440 s2 = ((PackageSetting)obj).signatures.mSignatures; 4441 } else { 4442 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4443 } 4444 } else { 4445 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4446 } 4447 return compareSignatures(s1, s2); 4448 } 4449 } 4450 4451 /** 4452 * This method should typically only be used when granting or revoking 4453 * permissions, since the app may immediately restart after this call. 4454 * <p> 4455 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 4456 * guard your work against the app being relaunched. 4457 */ 4458 private void killUid(int appId, int userId, String reason) { 4459 final long identity = Binder.clearCallingIdentity(); 4460 try { 4461 IActivityManager am = ActivityManagerNative.getDefault(); 4462 if (am != null) { 4463 try { 4464 am.killUid(appId, userId, reason); 4465 } catch (RemoteException e) { 4466 /* ignore - same process */ 4467 } 4468 } 4469 } finally { 4470 Binder.restoreCallingIdentity(identity); 4471 } 4472 } 4473 4474 /** 4475 * Compares two sets of signatures. Returns: 4476 * <br /> 4477 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4478 * <br /> 4479 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4480 * <br /> 4481 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4482 * <br /> 4483 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4484 * <br /> 4485 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4486 */ 4487 static int compareSignatures(Signature[] s1, Signature[] s2) { 4488 if (s1 == null) { 4489 return s2 == null 4490 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4491 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4492 } 4493 4494 if (s2 == null) { 4495 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4496 } 4497 4498 if (s1.length != s2.length) { 4499 return PackageManager.SIGNATURE_NO_MATCH; 4500 } 4501 4502 // Since both signature sets are of size 1, we can compare without HashSets. 4503 if (s1.length == 1) { 4504 return s1[0].equals(s2[0]) ? 4505 PackageManager.SIGNATURE_MATCH : 4506 PackageManager.SIGNATURE_NO_MATCH; 4507 } 4508 4509 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4510 for (Signature sig : s1) { 4511 set1.add(sig); 4512 } 4513 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4514 for (Signature sig : s2) { 4515 set2.add(sig); 4516 } 4517 // Make sure s2 contains all signatures in s1. 4518 if (set1.equals(set2)) { 4519 return PackageManager.SIGNATURE_MATCH; 4520 } 4521 return PackageManager.SIGNATURE_NO_MATCH; 4522 } 4523 4524 /** 4525 * If the database version for this type of package (internal storage or 4526 * external storage) is less than the version where package signatures 4527 * were updated, return true. 4528 */ 4529 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4530 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4531 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4532 } 4533 4534 /** 4535 * Used for backward compatibility to make sure any packages with 4536 * certificate chains get upgraded to the new style. {@code existingSigs} 4537 * will be in the old format (since they were stored on disk from before the 4538 * system upgrade) and {@code scannedSigs} will be in the newer format. 4539 */ 4540 private int compareSignaturesCompat(PackageSignatures existingSigs, 4541 PackageParser.Package scannedPkg) { 4542 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4543 return PackageManager.SIGNATURE_NO_MATCH; 4544 } 4545 4546 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4547 for (Signature sig : existingSigs.mSignatures) { 4548 existingSet.add(sig); 4549 } 4550 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4551 for (Signature sig : scannedPkg.mSignatures) { 4552 try { 4553 Signature[] chainSignatures = sig.getChainSignatures(); 4554 for (Signature chainSig : chainSignatures) { 4555 scannedCompatSet.add(chainSig); 4556 } 4557 } catch (CertificateEncodingException e) { 4558 scannedCompatSet.add(sig); 4559 } 4560 } 4561 /* 4562 * Make sure the expanded scanned set contains all signatures in the 4563 * existing one. 4564 */ 4565 if (scannedCompatSet.equals(existingSet)) { 4566 // Migrate the old signatures to the new scheme. 4567 existingSigs.assignSignatures(scannedPkg.mSignatures); 4568 // The new KeySets will be re-added later in the scanning process. 4569 synchronized (mPackages) { 4570 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4571 } 4572 return PackageManager.SIGNATURE_MATCH; 4573 } 4574 return PackageManager.SIGNATURE_NO_MATCH; 4575 } 4576 4577 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4578 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4579 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4580 } 4581 4582 private int compareSignaturesRecover(PackageSignatures existingSigs, 4583 PackageParser.Package scannedPkg) { 4584 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4585 return PackageManager.SIGNATURE_NO_MATCH; 4586 } 4587 4588 String msg = null; 4589 try { 4590 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4591 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4592 + scannedPkg.packageName); 4593 return PackageManager.SIGNATURE_MATCH; 4594 } 4595 } catch (CertificateException e) { 4596 msg = e.getMessage(); 4597 } 4598 4599 logCriticalInfo(Log.INFO, 4600 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4601 return PackageManager.SIGNATURE_NO_MATCH; 4602 } 4603 4604 @Override 4605 public List<String> getAllPackages() { 4606 synchronized (mPackages) { 4607 return new ArrayList<String>(mPackages.keySet()); 4608 } 4609 } 4610 4611 @Override 4612 public String[] getPackagesForUid(int uid) { 4613 uid = UserHandle.getAppId(uid); 4614 // reader 4615 synchronized (mPackages) { 4616 Object obj = mSettings.getUserIdLPr(uid); 4617 if (obj instanceof SharedUserSetting) { 4618 final SharedUserSetting sus = (SharedUserSetting) obj; 4619 final int N = sus.packages.size(); 4620 final String[] res = new String[N]; 4621 final Iterator<PackageSetting> it = sus.packages.iterator(); 4622 int i = 0; 4623 while (it.hasNext()) { 4624 res[i++] = it.next().name; 4625 } 4626 return res; 4627 } else if (obj instanceof PackageSetting) { 4628 final PackageSetting ps = (PackageSetting) obj; 4629 return new String[] { ps.name }; 4630 } 4631 } 4632 return null; 4633 } 4634 4635 @Override 4636 public String getNameForUid(int uid) { 4637 // reader 4638 synchronized (mPackages) { 4639 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4640 if (obj instanceof SharedUserSetting) { 4641 final SharedUserSetting sus = (SharedUserSetting) obj; 4642 return sus.name + ":" + sus.userId; 4643 } else if (obj instanceof PackageSetting) { 4644 final PackageSetting ps = (PackageSetting) obj; 4645 return ps.name; 4646 } 4647 } 4648 return null; 4649 } 4650 4651 @Override 4652 public int getUidForSharedUser(String sharedUserName) { 4653 if(sharedUserName == null) { 4654 return -1; 4655 } 4656 // reader 4657 synchronized (mPackages) { 4658 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4659 if (suid == null) { 4660 return -1; 4661 } 4662 return suid.userId; 4663 } 4664 } 4665 4666 @Override 4667 public int getFlagsForUid(int uid) { 4668 synchronized (mPackages) { 4669 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4670 if (obj instanceof SharedUserSetting) { 4671 final SharedUserSetting sus = (SharedUserSetting) obj; 4672 return sus.pkgFlags; 4673 } else if (obj instanceof PackageSetting) { 4674 final PackageSetting ps = (PackageSetting) obj; 4675 return ps.pkgFlags; 4676 } 4677 } 4678 return 0; 4679 } 4680 4681 @Override 4682 public int getPrivateFlagsForUid(int uid) { 4683 synchronized (mPackages) { 4684 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4685 if (obj instanceof SharedUserSetting) { 4686 final SharedUserSetting sus = (SharedUserSetting) obj; 4687 return sus.pkgPrivateFlags; 4688 } else if (obj instanceof PackageSetting) { 4689 final PackageSetting ps = (PackageSetting) obj; 4690 return ps.pkgPrivateFlags; 4691 } 4692 } 4693 return 0; 4694 } 4695 4696 @Override 4697 public boolean isUidPrivileged(int uid) { 4698 uid = UserHandle.getAppId(uid); 4699 // reader 4700 synchronized (mPackages) { 4701 Object obj = mSettings.getUserIdLPr(uid); 4702 if (obj instanceof SharedUserSetting) { 4703 final SharedUserSetting sus = (SharedUserSetting) obj; 4704 final Iterator<PackageSetting> it = sus.packages.iterator(); 4705 while (it.hasNext()) { 4706 if (it.next().isPrivileged()) { 4707 return true; 4708 } 4709 } 4710 } else if (obj instanceof PackageSetting) { 4711 final PackageSetting ps = (PackageSetting) obj; 4712 return ps.isPrivileged(); 4713 } 4714 } 4715 return false; 4716 } 4717 4718 @Override 4719 public String[] getAppOpPermissionPackages(String permissionName) { 4720 synchronized (mPackages) { 4721 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4722 if (pkgs == null) { 4723 return null; 4724 } 4725 return pkgs.toArray(new String[pkgs.size()]); 4726 } 4727 } 4728 4729 @Override 4730 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4731 int flags, int userId) { 4732 try { 4733 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 4734 4735 if (!sUserManager.exists(userId)) return null; 4736 flags = updateFlagsForResolve(flags, userId, intent); 4737 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4738 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 4739 4740 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 4741 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 4742 flags, userId); 4743 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4744 4745 final ResolveInfo bestChoice = 4746 chooseBestActivity(intent, resolvedType, flags, query, userId); 4747 4748 if (isEphemeralAllowed(intent, query, userId)) { 4749 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 4750 final EphemeralResolveInfo ai = 4751 getEphemeralResolveInfo(intent, resolvedType, userId); 4752 if (ai != null) { 4753 if (DEBUG_EPHEMERAL) { 4754 Slog.v(TAG, "Returning an EphemeralResolveInfo"); 4755 } 4756 bestChoice.ephemeralInstaller = mEphemeralInstallerInfo; 4757 bestChoice.ephemeralResolveInfo = ai; 4758 } 4759 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4760 } 4761 return bestChoice; 4762 } finally { 4763 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4764 } 4765 } 4766 4767 @Override 4768 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4769 IntentFilter filter, int match, ComponentName activity) { 4770 final int userId = UserHandle.getCallingUserId(); 4771 if (DEBUG_PREFERRED) { 4772 Log.v(TAG, "setLastChosenActivity intent=" + intent 4773 + " resolvedType=" + resolvedType 4774 + " flags=" + flags 4775 + " filter=" + filter 4776 + " match=" + match 4777 + " activity=" + activity); 4778 filter.dump(new PrintStreamPrinter(System.out), " "); 4779 } 4780 intent.setComponent(null); 4781 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4782 userId); 4783 // Find any earlier preferred or last chosen entries and nuke them 4784 findPreferredActivity(intent, resolvedType, 4785 flags, query, 0, false, true, false, userId); 4786 // Add the new activity as the last chosen for this filter 4787 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4788 "Setting last chosen"); 4789 } 4790 4791 @Override 4792 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4793 final int userId = UserHandle.getCallingUserId(); 4794 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4795 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4796 userId); 4797 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4798 false, false, false, userId); 4799 } 4800 4801 4802 private boolean isEphemeralAllowed( 4803 Intent intent, List<ResolveInfo> resolvedActivites, int userId) { 4804 // Short circuit and return early if possible. 4805 if (DISABLE_EPHEMERAL_APPS) { 4806 return false; 4807 } 4808 final int callingUser = UserHandle.getCallingUserId(); 4809 if (callingUser != UserHandle.USER_SYSTEM) { 4810 return false; 4811 } 4812 if (mEphemeralResolverConnection == null) { 4813 return false; 4814 } 4815 if (intent.getComponent() != null) { 4816 return false; 4817 } 4818 if (intent.getPackage() != null) { 4819 return false; 4820 } 4821 final boolean isWebUri = hasWebURI(intent); 4822 if (!isWebUri) { 4823 return false; 4824 } 4825 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4826 synchronized (mPackages) { 4827 final int count = resolvedActivites.size(); 4828 for (int n = 0; n < count; n++) { 4829 ResolveInfo info = resolvedActivites.get(n); 4830 String packageName = info.activityInfo.packageName; 4831 PackageSetting ps = mSettings.mPackages.get(packageName); 4832 if (ps != null) { 4833 // Try to get the status from User settings first 4834 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4835 int status = (int) (packedStatus >> 32); 4836 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4837 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4838 if (DEBUG_EPHEMERAL) { 4839 Slog.v(TAG, "DENY ephemeral apps;" 4840 + " pkg: " + packageName + ", status: " + status); 4841 } 4842 return false; 4843 } 4844 } 4845 } 4846 } 4847 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4848 return true; 4849 } 4850 4851 private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType, 4852 int userId) { 4853 MessageDigest digest = null; 4854 try { 4855 digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM); 4856 } catch (NoSuchAlgorithmException e) { 4857 // If we can't create a digest, ignore ephemeral apps. 4858 return null; 4859 } 4860 4861 final byte[] hostBytes = intent.getData().getHost().getBytes(); 4862 final byte[] digestBytes = digest.digest(hostBytes); 4863 int shaPrefix = 4864 digestBytes[0] << 24 4865 | digestBytes[1] << 16 4866 | digestBytes[2] << 8 4867 | digestBytes[3] << 0; 4868 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4869 mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix); 4870 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4871 // No hash prefix match; there are no ephemeral apps for this domain. 4872 return null; 4873 } 4874 for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) { 4875 EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i); 4876 if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) { 4877 continue; 4878 } 4879 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 4880 // No filters; this should never happen. 4881 if (filters.isEmpty()) { 4882 continue; 4883 } 4884 // We have a domain match; resolve the filters to see if anything matches. 4885 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4886 for (int j = filters.size() - 1; j >= 0; --j) { 4887 final EphemeralResolveIntentInfo intentInfo = 4888 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 4889 ephemeralResolver.addFilter(intentInfo); 4890 } 4891 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 4892 intent, resolvedType, false /*defaultOnly*/, userId); 4893 if (!matchedResolveInfoList.isEmpty()) { 4894 return matchedResolveInfoList.get(0); 4895 } 4896 } 4897 // Hash or filter mis-match; no ephemeral apps for this domain. 4898 return null; 4899 } 4900 4901 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4902 int flags, List<ResolveInfo> query, int userId) { 4903 if (query != null) { 4904 final int N = query.size(); 4905 if (N == 1) { 4906 return query.get(0); 4907 } else if (N > 1) { 4908 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4909 // If there is more than one activity with the same priority, 4910 // then let the user decide between them. 4911 ResolveInfo r0 = query.get(0); 4912 ResolveInfo r1 = query.get(1); 4913 if (DEBUG_INTENT_MATCHING || debug) { 4914 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4915 + r1.activityInfo.name + "=" + r1.priority); 4916 } 4917 // If the first activity has a higher priority, or a different 4918 // default, then it is always desirable to pick it. 4919 if (r0.priority != r1.priority 4920 || r0.preferredOrder != r1.preferredOrder 4921 || r0.isDefault != r1.isDefault) { 4922 return query.get(0); 4923 } 4924 // If we have saved a preference for a preferred activity for 4925 // this Intent, use that. 4926 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4927 flags, query, r0.priority, true, false, debug, userId); 4928 if (ri != null) { 4929 return ri; 4930 } 4931 ri = new ResolveInfo(mResolveInfo); 4932 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4933 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 4934 ri.activityInfo.applicationInfo = new ApplicationInfo( 4935 ri.activityInfo.applicationInfo); 4936 if (userId != 0) { 4937 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4938 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4939 } 4940 // Make sure that the resolver is displayable in car mode 4941 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 4942 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 4943 return ri; 4944 } 4945 } 4946 return null; 4947 } 4948 4949 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4950 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4951 final int N = query.size(); 4952 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4953 .get(userId); 4954 // Get the list of persistent preferred activities that handle the intent 4955 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4956 List<PersistentPreferredActivity> pprefs = ppir != null 4957 ? ppir.queryIntent(intent, resolvedType, 4958 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4959 : null; 4960 if (pprefs != null && pprefs.size() > 0) { 4961 final int M = pprefs.size(); 4962 for (int i=0; i<M; i++) { 4963 final PersistentPreferredActivity ppa = pprefs.get(i); 4964 if (DEBUG_PREFERRED || debug) { 4965 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4966 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4967 + "\n component=" + ppa.mComponent); 4968 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4969 } 4970 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4971 flags | MATCH_DISABLED_COMPONENTS, userId); 4972 if (DEBUG_PREFERRED || debug) { 4973 Slog.v(TAG, "Found persistent preferred activity:"); 4974 if (ai != null) { 4975 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4976 } else { 4977 Slog.v(TAG, " null"); 4978 } 4979 } 4980 if (ai == null) { 4981 // This previously registered persistent preferred activity 4982 // component is no longer known. Ignore it and do NOT remove it. 4983 continue; 4984 } 4985 for (int j=0; j<N; j++) { 4986 final ResolveInfo ri = query.get(j); 4987 if (!ri.activityInfo.applicationInfo.packageName 4988 .equals(ai.applicationInfo.packageName)) { 4989 continue; 4990 } 4991 if (!ri.activityInfo.name.equals(ai.name)) { 4992 continue; 4993 } 4994 // Found a persistent preference that can handle the intent. 4995 if (DEBUG_PREFERRED || debug) { 4996 Slog.v(TAG, "Returning persistent preferred activity: " + 4997 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4998 } 4999 return ri; 5000 } 5001 } 5002 } 5003 return null; 5004 } 5005 5006 // TODO: handle preferred activities missing while user has amnesia 5007 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5008 List<ResolveInfo> query, int priority, boolean always, 5009 boolean removeMatches, boolean debug, int userId) { 5010 if (!sUserManager.exists(userId)) return null; 5011 flags = updateFlagsForResolve(flags, userId, intent); 5012 // writer 5013 synchronized (mPackages) { 5014 if (intent.getSelector() != null) { 5015 intent = intent.getSelector(); 5016 } 5017 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 5018 5019 // Try to find a matching persistent preferred activity. 5020 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5021 debug, userId); 5022 5023 // If a persistent preferred activity matched, use it. 5024 if (pri != null) { 5025 return pri; 5026 } 5027 5028 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5029 // Get the list of preferred activities that handle the intent 5030 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5031 List<PreferredActivity> prefs = pir != null 5032 ? pir.queryIntent(intent, resolvedType, 5033 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5034 : null; 5035 if (prefs != null && prefs.size() > 0) { 5036 boolean changed = false; 5037 try { 5038 // First figure out how good the original match set is. 5039 // We will only allow preferred activities that came 5040 // from the same match quality. 5041 int match = 0; 5042 5043 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5044 5045 final int N = query.size(); 5046 for (int j=0; j<N; j++) { 5047 final ResolveInfo ri = query.get(j); 5048 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5049 + ": 0x" + Integer.toHexString(match)); 5050 if (ri.match > match) { 5051 match = ri.match; 5052 } 5053 } 5054 5055 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5056 + Integer.toHexString(match)); 5057 5058 match &= IntentFilter.MATCH_CATEGORY_MASK; 5059 final int M = prefs.size(); 5060 for (int i=0; i<M; i++) { 5061 final PreferredActivity pa = prefs.get(i); 5062 if (DEBUG_PREFERRED || debug) { 5063 Slog.v(TAG, "Checking PreferredActivity ds=" 5064 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5065 + "\n component=" + pa.mPref.mComponent); 5066 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5067 } 5068 if (pa.mPref.mMatch != match) { 5069 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5070 + Integer.toHexString(pa.mPref.mMatch)); 5071 continue; 5072 } 5073 // If it's not an "always" type preferred activity and that's what we're 5074 // looking for, skip it. 5075 if (always && !pa.mPref.mAlways) { 5076 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5077 continue; 5078 } 5079 final ActivityInfo ai = getActivityInfo( 5080 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5081 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5082 userId); 5083 if (DEBUG_PREFERRED || debug) { 5084 Slog.v(TAG, "Found preferred activity:"); 5085 if (ai != null) { 5086 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5087 } else { 5088 Slog.v(TAG, " null"); 5089 } 5090 } 5091 if (ai == null) { 5092 // This previously registered preferred activity 5093 // component is no longer known. Most likely an update 5094 // to the app was installed and in the new version this 5095 // component no longer exists. Clean it up by removing 5096 // it from the preferred activities list, and skip it. 5097 Slog.w(TAG, "Removing dangling preferred activity: " 5098 + pa.mPref.mComponent); 5099 pir.removeFilter(pa); 5100 changed = true; 5101 continue; 5102 } 5103 for (int j=0; j<N; j++) { 5104 final ResolveInfo ri = query.get(j); 5105 if (!ri.activityInfo.applicationInfo.packageName 5106 .equals(ai.applicationInfo.packageName)) { 5107 continue; 5108 } 5109 if (!ri.activityInfo.name.equals(ai.name)) { 5110 continue; 5111 } 5112 5113 if (removeMatches) { 5114 pir.removeFilter(pa); 5115 changed = true; 5116 if (DEBUG_PREFERRED) { 5117 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 5118 } 5119 break; 5120 } 5121 5122 // Okay we found a previously set preferred or last chosen app. 5123 // If the result set is different from when this 5124 // was created, we need to clear it and re-ask the 5125 // user their preference, if we're looking for an "always" type entry. 5126 if (always && !pa.mPref.sameSet(query)) { 5127 Slog.i(TAG, "Result set changed, dropping preferred activity for " 5128 + intent + " type " + resolvedType); 5129 if (DEBUG_PREFERRED) { 5130 Slog.v(TAG, "Removing preferred activity since set changed " 5131 + pa.mPref.mComponent); 5132 } 5133 pir.removeFilter(pa); 5134 // Re-add the filter as a "last chosen" entry (!always) 5135 PreferredActivity lastChosen = new PreferredActivity( 5136 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5137 pir.addFilter(lastChosen); 5138 changed = true; 5139 return null; 5140 } 5141 5142 // Yay! Either the set matched or we're looking for the last chosen 5143 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5144 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5145 return ri; 5146 } 5147 } 5148 } finally { 5149 if (changed) { 5150 if (DEBUG_PREFERRED) { 5151 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5152 } 5153 scheduleWritePackageRestrictionsLocked(userId); 5154 } 5155 } 5156 } 5157 } 5158 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5159 return null; 5160 } 5161 5162 /* 5163 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5164 */ 5165 @Override 5166 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5167 int targetUserId) { 5168 mContext.enforceCallingOrSelfPermission( 5169 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5170 List<CrossProfileIntentFilter> matches = 5171 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5172 if (matches != null) { 5173 int size = matches.size(); 5174 for (int i = 0; i < size; i++) { 5175 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5176 } 5177 } 5178 if (hasWebURI(intent)) { 5179 // cross-profile app linking works only towards the parent. 5180 final UserInfo parent = getProfileParent(sourceUserId); 5181 synchronized(mPackages) { 5182 int flags = updateFlagsForResolve(0, parent.id, intent); 5183 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5184 intent, resolvedType, flags, sourceUserId, parent.id); 5185 return xpDomainInfo != null; 5186 } 5187 } 5188 return false; 5189 } 5190 5191 private UserInfo getProfileParent(int userId) { 5192 final long identity = Binder.clearCallingIdentity(); 5193 try { 5194 return sUserManager.getProfileParent(userId); 5195 } finally { 5196 Binder.restoreCallingIdentity(identity); 5197 } 5198 } 5199 5200 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5201 String resolvedType, int userId) { 5202 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5203 if (resolver != null) { 5204 return resolver.queryIntent(intent, resolvedType, false, userId); 5205 } 5206 return null; 5207 } 5208 5209 @Override 5210 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5211 String resolvedType, int flags, int userId) { 5212 try { 5213 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5214 5215 return new ParceledListSlice<>( 5216 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5217 } finally { 5218 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5219 } 5220 } 5221 5222 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5223 String resolvedType, int flags, int userId) { 5224 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5225 flags = updateFlagsForResolve(flags, userId, intent); 5226 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5227 false /* requireFullPermission */, false /* checkShell */, 5228 "query intent activities"); 5229 ComponentName comp = intent.getComponent(); 5230 if (comp == null) { 5231 if (intent.getSelector() != null) { 5232 intent = intent.getSelector(); 5233 comp = intent.getComponent(); 5234 } 5235 } 5236 5237 if (comp != null) { 5238 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5239 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5240 if (ai != null) { 5241 final ResolveInfo ri = new ResolveInfo(); 5242 ri.activityInfo = ai; 5243 list.add(ri); 5244 } 5245 return list; 5246 } 5247 5248 // reader 5249 synchronized (mPackages) { 5250 final String pkgName = intent.getPackage(); 5251 if (pkgName == null) { 5252 List<CrossProfileIntentFilter> matchingFilters = 5253 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5254 // Check for results that need to skip the current profile. 5255 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5256 resolvedType, flags, userId); 5257 if (xpResolveInfo != null) { 5258 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 5259 result.add(xpResolveInfo); 5260 return filterIfNotSystemUser(result, userId); 5261 } 5262 5263 // Check for results in the current profile. 5264 List<ResolveInfo> result = mActivities.queryIntent( 5265 intent, resolvedType, flags, userId); 5266 result = filterIfNotSystemUser(result, userId); 5267 5268 // Check for cross profile results. 5269 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5270 xpResolveInfo = queryCrossProfileIntents( 5271 matchingFilters, intent, resolvedType, flags, userId, 5272 hasNonNegativePriorityResult); 5273 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5274 boolean isVisibleToUser = filterIfNotSystemUser( 5275 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5276 if (isVisibleToUser) { 5277 result.add(xpResolveInfo); 5278 Collections.sort(result, mResolvePrioritySorter); 5279 } 5280 } 5281 if (hasWebURI(intent)) { 5282 CrossProfileDomainInfo xpDomainInfo = null; 5283 final UserInfo parent = getProfileParent(userId); 5284 if (parent != null) { 5285 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5286 flags, userId, parent.id); 5287 } 5288 if (xpDomainInfo != null) { 5289 if (xpResolveInfo != null) { 5290 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5291 // in the result. 5292 result.remove(xpResolveInfo); 5293 } 5294 if (result.size() == 0) { 5295 result.add(xpDomainInfo.resolveInfo); 5296 return result; 5297 } 5298 } else if (result.size() <= 1) { 5299 return result; 5300 } 5301 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 5302 xpDomainInfo, userId); 5303 Collections.sort(result, mResolvePrioritySorter); 5304 } 5305 return result; 5306 } 5307 final PackageParser.Package pkg = mPackages.get(pkgName); 5308 if (pkg != null) { 5309 return filterIfNotSystemUser( 5310 mActivities.queryIntentForPackage( 5311 intent, resolvedType, flags, pkg.activities, userId), 5312 userId); 5313 } 5314 return new ArrayList<ResolveInfo>(); 5315 } 5316 } 5317 5318 private static class CrossProfileDomainInfo { 5319 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5320 ResolveInfo resolveInfo; 5321 /* Best domain verification status of the activities found in the other profile */ 5322 int bestDomainVerificationStatus; 5323 } 5324 5325 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5326 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5327 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5328 sourceUserId)) { 5329 return null; 5330 } 5331 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5332 resolvedType, flags, parentUserId); 5333 5334 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5335 return null; 5336 } 5337 CrossProfileDomainInfo result = null; 5338 int size = resultTargetUser.size(); 5339 for (int i = 0; i < size; i++) { 5340 ResolveInfo riTargetUser = resultTargetUser.get(i); 5341 // Intent filter verification is only for filters that specify a host. So don't return 5342 // those that handle all web uris. 5343 if (riTargetUser.handleAllWebDataURI) { 5344 continue; 5345 } 5346 String packageName = riTargetUser.activityInfo.packageName; 5347 PackageSetting ps = mSettings.mPackages.get(packageName); 5348 if (ps == null) { 5349 continue; 5350 } 5351 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5352 int status = (int)(verificationState >> 32); 5353 if (result == null) { 5354 result = new CrossProfileDomainInfo(); 5355 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5356 sourceUserId, parentUserId); 5357 result.bestDomainVerificationStatus = status; 5358 } else { 5359 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5360 result.bestDomainVerificationStatus); 5361 } 5362 } 5363 // Don't consider matches with status NEVER across profiles. 5364 if (result != null && result.bestDomainVerificationStatus 5365 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5366 return null; 5367 } 5368 return result; 5369 } 5370 5371 /** 5372 * Verification statuses are ordered from the worse to the best, except for 5373 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5374 */ 5375 private int bestDomainVerificationStatus(int status1, int status2) { 5376 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5377 return status2; 5378 } 5379 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5380 return status1; 5381 } 5382 return (int) MathUtils.max(status1, status2); 5383 } 5384 5385 private boolean isUserEnabled(int userId) { 5386 long callingId = Binder.clearCallingIdentity(); 5387 try { 5388 UserInfo userInfo = sUserManager.getUserInfo(userId); 5389 return userInfo != null && userInfo.isEnabled(); 5390 } finally { 5391 Binder.restoreCallingIdentity(callingId); 5392 } 5393 } 5394 5395 /** 5396 * Filter out activities with systemUserOnly flag set, when current user is not System. 5397 * 5398 * @return filtered list 5399 */ 5400 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5401 if (userId == UserHandle.USER_SYSTEM) { 5402 return resolveInfos; 5403 } 5404 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5405 ResolveInfo info = resolveInfos.get(i); 5406 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5407 resolveInfos.remove(i); 5408 } 5409 } 5410 return resolveInfos; 5411 } 5412 5413 /** 5414 * @param resolveInfos list of resolve infos in descending priority order 5415 * @return if the list contains a resolve info with non-negative priority 5416 */ 5417 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5418 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5419 } 5420 5421 private static boolean hasWebURI(Intent intent) { 5422 if (intent.getData() == null) { 5423 return false; 5424 } 5425 final String scheme = intent.getScheme(); 5426 if (TextUtils.isEmpty(scheme)) { 5427 return false; 5428 } 5429 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5430 } 5431 5432 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5433 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5434 int userId) { 5435 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5436 5437 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5438 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5439 candidates.size()); 5440 } 5441 5442 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5443 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5444 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5445 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5446 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5447 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5448 5449 synchronized (mPackages) { 5450 final int count = candidates.size(); 5451 // First, try to use linked apps. Partition the candidates into four lists: 5452 // one for the final results, one for the "do not use ever", one for "undefined status" 5453 // and finally one for "browser app type". 5454 for (int n=0; n<count; n++) { 5455 ResolveInfo info = candidates.get(n); 5456 String packageName = info.activityInfo.packageName; 5457 PackageSetting ps = mSettings.mPackages.get(packageName); 5458 if (ps != null) { 5459 // Add to the special match all list (Browser use case) 5460 if (info.handleAllWebDataURI) { 5461 matchAllList.add(info); 5462 continue; 5463 } 5464 // Try to get the status from User settings first 5465 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5466 int status = (int)(packedStatus >> 32); 5467 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5468 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5469 if (DEBUG_DOMAIN_VERIFICATION) { 5470 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5471 + " : linkgen=" + linkGeneration); 5472 } 5473 // Use link-enabled generation as preferredOrder, i.e. 5474 // prefer newly-enabled over earlier-enabled. 5475 info.preferredOrder = linkGeneration; 5476 alwaysList.add(info); 5477 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5478 if (DEBUG_DOMAIN_VERIFICATION) { 5479 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5480 } 5481 neverList.add(info); 5482 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5483 if (DEBUG_DOMAIN_VERIFICATION) { 5484 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5485 } 5486 alwaysAskList.add(info); 5487 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5488 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5489 if (DEBUG_DOMAIN_VERIFICATION) { 5490 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5491 } 5492 undefinedList.add(info); 5493 } 5494 } 5495 } 5496 5497 // We'll want to include browser possibilities in a few cases 5498 boolean includeBrowser = false; 5499 5500 // First try to add the "always" resolution(s) for the current user, if any 5501 if (alwaysList.size() > 0) { 5502 result.addAll(alwaysList); 5503 } else { 5504 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5505 result.addAll(undefinedList); 5506 // Maybe add one for the other profile. 5507 if (xpDomainInfo != null && ( 5508 xpDomainInfo.bestDomainVerificationStatus 5509 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5510 result.add(xpDomainInfo.resolveInfo); 5511 } 5512 includeBrowser = true; 5513 } 5514 5515 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5516 // If there were 'always' entries their preferred order has been set, so we also 5517 // back that off to make the alternatives equivalent 5518 if (alwaysAskList.size() > 0) { 5519 for (ResolveInfo i : result) { 5520 i.preferredOrder = 0; 5521 } 5522 result.addAll(alwaysAskList); 5523 includeBrowser = true; 5524 } 5525 5526 if (includeBrowser) { 5527 // Also add browsers (all of them or only the default one) 5528 if (DEBUG_DOMAIN_VERIFICATION) { 5529 Slog.v(TAG, " ...including browsers in candidate set"); 5530 } 5531 if ((matchFlags & MATCH_ALL) != 0) { 5532 result.addAll(matchAllList); 5533 } else { 5534 // Browser/generic handling case. If there's a default browser, go straight 5535 // to that (but only if there is no other higher-priority match). 5536 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5537 int maxMatchPrio = 0; 5538 ResolveInfo defaultBrowserMatch = null; 5539 final int numCandidates = matchAllList.size(); 5540 for (int n = 0; n < numCandidates; n++) { 5541 ResolveInfo info = matchAllList.get(n); 5542 // track the highest overall match priority... 5543 if (info.priority > maxMatchPrio) { 5544 maxMatchPrio = info.priority; 5545 } 5546 // ...and the highest-priority default browser match 5547 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5548 if (defaultBrowserMatch == null 5549 || (defaultBrowserMatch.priority < info.priority)) { 5550 if (debug) { 5551 Slog.v(TAG, "Considering default browser match " + info); 5552 } 5553 defaultBrowserMatch = info; 5554 } 5555 } 5556 } 5557 if (defaultBrowserMatch != null 5558 && defaultBrowserMatch.priority >= maxMatchPrio 5559 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5560 { 5561 if (debug) { 5562 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5563 } 5564 result.add(defaultBrowserMatch); 5565 } else { 5566 result.addAll(matchAllList); 5567 } 5568 } 5569 5570 // If there is nothing selected, add all candidates and remove the ones that the user 5571 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5572 if (result.size() == 0) { 5573 result.addAll(candidates); 5574 result.removeAll(neverList); 5575 } 5576 } 5577 } 5578 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5579 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5580 result.size()); 5581 for (ResolveInfo info : result) { 5582 Slog.v(TAG, " + " + info.activityInfo); 5583 } 5584 } 5585 return result; 5586 } 5587 5588 // Returns a packed value as a long: 5589 // 5590 // high 'int'-sized word: link status: undefined/ask/never/always. 5591 // low 'int'-sized word: relative priority among 'always' results. 5592 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5593 long result = ps.getDomainVerificationStatusForUser(userId); 5594 // if none available, get the master status 5595 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5596 if (ps.getIntentFilterVerificationInfo() != null) { 5597 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5598 } 5599 } 5600 return result; 5601 } 5602 5603 private ResolveInfo querySkipCurrentProfileIntents( 5604 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5605 int flags, int sourceUserId) { 5606 if (matchingFilters != null) { 5607 int size = matchingFilters.size(); 5608 for (int i = 0; i < size; i ++) { 5609 CrossProfileIntentFilter filter = matchingFilters.get(i); 5610 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5611 // Checking if there are activities in the target user that can handle the 5612 // intent. 5613 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5614 resolvedType, flags, sourceUserId); 5615 if (resolveInfo != null) { 5616 return resolveInfo; 5617 } 5618 } 5619 } 5620 } 5621 return null; 5622 } 5623 5624 // Return matching ResolveInfo in target user if any. 5625 private ResolveInfo queryCrossProfileIntents( 5626 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5627 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5628 if (matchingFilters != null) { 5629 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5630 // match the same intent. For performance reasons, it is better not to 5631 // run queryIntent twice for the same userId 5632 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5633 int size = matchingFilters.size(); 5634 for (int i = 0; i < size; i++) { 5635 CrossProfileIntentFilter filter = matchingFilters.get(i); 5636 int targetUserId = filter.getTargetUserId(); 5637 boolean skipCurrentProfile = 5638 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5639 boolean skipCurrentProfileIfNoMatchFound = 5640 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5641 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5642 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5643 // Checking if there are activities in the target user that can handle the 5644 // intent. 5645 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5646 resolvedType, flags, sourceUserId); 5647 if (resolveInfo != null) return resolveInfo; 5648 alreadyTriedUserIds.put(targetUserId, true); 5649 } 5650 } 5651 } 5652 return null; 5653 } 5654 5655 /** 5656 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5657 * will forward the intent to the filter's target user. 5658 * Otherwise, returns null. 5659 */ 5660 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5661 String resolvedType, int flags, int sourceUserId) { 5662 int targetUserId = filter.getTargetUserId(); 5663 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5664 resolvedType, flags, targetUserId); 5665 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5666 // If all the matches in the target profile are suspended, return null. 5667 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5668 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5669 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5670 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5671 targetUserId); 5672 } 5673 } 5674 } 5675 return null; 5676 } 5677 5678 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5679 int sourceUserId, int targetUserId) { 5680 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5681 long ident = Binder.clearCallingIdentity(); 5682 boolean targetIsProfile; 5683 try { 5684 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5685 } finally { 5686 Binder.restoreCallingIdentity(ident); 5687 } 5688 String className; 5689 if (targetIsProfile) { 5690 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5691 } else { 5692 className = FORWARD_INTENT_TO_PARENT; 5693 } 5694 ComponentName forwardingActivityComponentName = new ComponentName( 5695 mAndroidApplication.packageName, className); 5696 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5697 sourceUserId); 5698 if (!targetIsProfile) { 5699 forwardingActivityInfo.showUserIcon = targetUserId; 5700 forwardingResolveInfo.noResourceId = true; 5701 } 5702 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5703 forwardingResolveInfo.priority = 0; 5704 forwardingResolveInfo.preferredOrder = 0; 5705 forwardingResolveInfo.match = 0; 5706 forwardingResolveInfo.isDefault = true; 5707 forwardingResolveInfo.filter = filter; 5708 forwardingResolveInfo.targetUserId = targetUserId; 5709 return forwardingResolveInfo; 5710 } 5711 5712 @Override 5713 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5714 Intent[] specifics, String[] specificTypes, Intent intent, 5715 String resolvedType, int flags, int userId) { 5716 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 5717 specificTypes, intent, resolvedType, flags, userId)); 5718 } 5719 5720 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 5721 Intent[] specifics, String[] specificTypes, Intent intent, 5722 String resolvedType, int flags, int userId) { 5723 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5724 flags = updateFlagsForResolve(flags, userId, intent); 5725 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5726 false /* requireFullPermission */, false /* checkShell */, 5727 "query intent activity options"); 5728 final String resultsAction = intent.getAction(); 5729 5730 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 5731 | PackageManager.GET_RESOLVED_FILTER, userId); 5732 5733 if (DEBUG_INTENT_MATCHING) { 5734 Log.v(TAG, "Query " + intent + ": " + results); 5735 } 5736 5737 int specificsPos = 0; 5738 int N; 5739 5740 // todo: note that the algorithm used here is O(N^2). This 5741 // isn't a problem in our current environment, but if we start running 5742 // into situations where we have more than 5 or 10 matches then this 5743 // should probably be changed to something smarter... 5744 5745 // First we go through and resolve each of the specific items 5746 // that were supplied, taking care of removing any corresponding 5747 // duplicate items in the generic resolve list. 5748 if (specifics != null) { 5749 for (int i=0; i<specifics.length; i++) { 5750 final Intent sintent = specifics[i]; 5751 if (sintent == null) { 5752 continue; 5753 } 5754 5755 if (DEBUG_INTENT_MATCHING) { 5756 Log.v(TAG, "Specific #" + i + ": " + sintent); 5757 } 5758 5759 String action = sintent.getAction(); 5760 if (resultsAction != null && resultsAction.equals(action)) { 5761 // If this action was explicitly requested, then don't 5762 // remove things that have it. 5763 action = null; 5764 } 5765 5766 ResolveInfo ri = null; 5767 ActivityInfo ai = null; 5768 5769 ComponentName comp = sintent.getComponent(); 5770 if (comp == null) { 5771 ri = resolveIntent( 5772 sintent, 5773 specificTypes != null ? specificTypes[i] : null, 5774 flags, userId); 5775 if (ri == null) { 5776 continue; 5777 } 5778 if (ri == mResolveInfo) { 5779 // ACK! Must do something better with this. 5780 } 5781 ai = ri.activityInfo; 5782 comp = new ComponentName(ai.applicationInfo.packageName, 5783 ai.name); 5784 } else { 5785 ai = getActivityInfo(comp, flags, userId); 5786 if (ai == null) { 5787 continue; 5788 } 5789 } 5790 5791 // Look for any generic query activities that are duplicates 5792 // of this specific one, and remove them from the results. 5793 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5794 N = results.size(); 5795 int j; 5796 for (j=specificsPos; j<N; j++) { 5797 ResolveInfo sri = results.get(j); 5798 if ((sri.activityInfo.name.equals(comp.getClassName()) 5799 && sri.activityInfo.applicationInfo.packageName.equals( 5800 comp.getPackageName())) 5801 || (action != null && sri.filter.matchAction(action))) { 5802 results.remove(j); 5803 if (DEBUG_INTENT_MATCHING) Log.v( 5804 TAG, "Removing duplicate item from " + j 5805 + " due to specific " + specificsPos); 5806 if (ri == null) { 5807 ri = sri; 5808 } 5809 j--; 5810 N--; 5811 } 5812 } 5813 5814 // Add this specific item to its proper place. 5815 if (ri == null) { 5816 ri = new ResolveInfo(); 5817 ri.activityInfo = ai; 5818 } 5819 results.add(specificsPos, ri); 5820 ri.specificIndex = i; 5821 specificsPos++; 5822 } 5823 } 5824 5825 // Now we go through the remaining generic results and remove any 5826 // duplicate actions that are found here. 5827 N = results.size(); 5828 for (int i=specificsPos; i<N-1; i++) { 5829 final ResolveInfo rii = results.get(i); 5830 if (rii.filter == null) { 5831 continue; 5832 } 5833 5834 // Iterate over all of the actions of this result's intent 5835 // filter... typically this should be just one. 5836 final Iterator<String> it = rii.filter.actionsIterator(); 5837 if (it == null) { 5838 continue; 5839 } 5840 while (it.hasNext()) { 5841 final String action = it.next(); 5842 if (resultsAction != null && resultsAction.equals(action)) { 5843 // If this action was explicitly requested, then don't 5844 // remove things that have it. 5845 continue; 5846 } 5847 for (int j=i+1; j<N; j++) { 5848 final ResolveInfo rij = results.get(j); 5849 if (rij.filter != null && rij.filter.hasAction(action)) { 5850 results.remove(j); 5851 if (DEBUG_INTENT_MATCHING) Log.v( 5852 TAG, "Removing duplicate item from " + j 5853 + " due to action " + action + " at " + i); 5854 j--; 5855 N--; 5856 } 5857 } 5858 } 5859 5860 // If the caller didn't request filter information, drop it now 5861 // so we don't have to marshall/unmarshall it. 5862 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5863 rii.filter = null; 5864 } 5865 } 5866 5867 // Filter out the caller activity if so requested. 5868 if (caller != null) { 5869 N = results.size(); 5870 for (int i=0; i<N; i++) { 5871 ActivityInfo ainfo = results.get(i).activityInfo; 5872 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5873 && caller.getClassName().equals(ainfo.name)) { 5874 results.remove(i); 5875 break; 5876 } 5877 } 5878 } 5879 5880 // If the caller didn't request filter information, 5881 // drop them now so we don't have to 5882 // marshall/unmarshall it. 5883 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5884 N = results.size(); 5885 for (int i=0; i<N; i++) { 5886 results.get(i).filter = null; 5887 } 5888 } 5889 5890 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5891 return results; 5892 } 5893 5894 @Override 5895 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 5896 String resolvedType, int flags, int userId) { 5897 return new ParceledListSlice<>( 5898 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 5899 } 5900 5901 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 5902 String resolvedType, int flags, int userId) { 5903 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5904 flags = updateFlagsForResolve(flags, userId, intent); 5905 ComponentName comp = intent.getComponent(); 5906 if (comp == null) { 5907 if (intent.getSelector() != null) { 5908 intent = intent.getSelector(); 5909 comp = intent.getComponent(); 5910 } 5911 } 5912 if (comp != null) { 5913 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5914 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5915 if (ai != null) { 5916 ResolveInfo ri = new ResolveInfo(); 5917 ri.activityInfo = ai; 5918 list.add(ri); 5919 } 5920 return list; 5921 } 5922 5923 // reader 5924 synchronized (mPackages) { 5925 String pkgName = intent.getPackage(); 5926 if (pkgName == null) { 5927 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5928 } 5929 final PackageParser.Package pkg = mPackages.get(pkgName); 5930 if (pkg != null) { 5931 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5932 userId); 5933 } 5934 return Collections.emptyList(); 5935 } 5936 } 5937 5938 @Override 5939 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5940 if (!sUserManager.exists(userId)) return null; 5941 flags = updateFlagsForResolve(flags, userId, intent); 5942 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 5943 if (query != null) { 5944 if (query.size() >= 1) { 5945 // If there is more than one service with the same priority, 5946 // just arbitrarily pick the first one. 5947 return query.get(0); 5948 } 5949 } 5950 return null; 5951 } 5952 5953 @Override 5954 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 5955 String resolvedType, int flags, int userId) { 5956 return new ParceledListSlice<>( 5957 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 5958 } 5959 5960 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 5961 String resolvedType, int flags, int userId) { 5962 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5963 flags = updateFlagsForResolve(flags, userId, intent); 5964 ComponentName comp = intent.getComponent(); 5965 if (comp == null) { 5966 if (intent.getSelector() != null) { 5967 intent = intent.getSelector(); 5968 comp = intent.getComponent(); 5969 } 5970 } 5971 if (comp != null) { 5972 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5973 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5974 if (si != null) { 5975 final ResolveInfo ri = new ResolveInfo(); 5976 ri.serviceInfo = si; 5977 list.add(ri); 5978 } 5979 return list; 5980 } 5981 5982 // reader 5983 synchronized (mPackages) { 5984 String pkgName = intent.getPackage(); 5985 if (pkgName == null) { 5986 return mServices.queryIntent(intent, resolvedType, flags, userId); 5987 } 5988 final PackageParser.Package pkg = mPackages.get(pkgName); 5989 if (pkg != null) { 5990 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5991 userId); 5992 } 5993 return Collections.emptyList(); 5994 } 5995 } 5996 5997 @Override 5998 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 5999 String resolvedType, int flags, int userId) { 6000 return new ParceledListSlice<>( 6001 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 6002 } 6003 6004 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 6005 Intent intent, String resolvedType, int flags, int userId) { 6006 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6007 flags = updateFlagsForResolve(flags, userId, intent); 6008 ComponentName comp = intent.getComponent(); 6009 if (comp == null) { 6010 if (intent.getSelector() != null) { 6011 intent = intent.getSelector(); 6012 comp = intent.getComponent(); 6013 } 6014 } 6015 if (comp != null) { 6016 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6017 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 6018 if (pi != null) { 6019 final ResolveInfo ri = new ResolveInfo(); 6020 ri.providerInfo = pi; 6021 list.add(ri); 6022 } 6023 return list; 6024 } 6025 6026 // reader 6027 synchronized (mPackages) { 6028 String pkgName = intent.getPackage(); 6029 if (pkgName == null) { 6030 return mProviders.queryIntent(intent, resolvedType, flags, userId); 6031 } 6032 final PackageParser.Package pkg = mPackages.get(pkgName); 6033 if (pkg != null) { 6034 return mProviders.queryIntentForPackage( 6035 intent, resolvedType, flags, pkg.providers, userId); 6036 } 6037 return Collections.emptyList(); 6038 } 6039 } 6040 6041 @Override 6042 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 6043 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6044 flags = updateFlagsForPackage(flags, userId, null); 6045 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6046 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6047 true /* requireFullPermission */, false /* checkShell */, 6048 "get installed packages"); 6049 6050 // writer 6051 synchronized (mPackages) { 6052 ArrayList<PackageInfo> list; 6053 if (listUninstalled) { 6054 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 6055 for (PackageSetting ps : mSettings.mPackages.values()) { 6056 final PackageInfo pi; 6057 if (ps.pkg != null) { 6058 pi = generatePackageInfo(ps, flags, userId); 6059 } else { 6060 pi = generatePackageInfo(ps, flags, userId); 6061 } 6062 if (pi != null) { 6063 list.add(pi); 6064 } 6065 } 6066 } else { 6067 list = new ArrayList<PackageInfo>(mPackages.size()); 6068 for (PackageParser.Package p : mPackages.values()) { 6069 final PackageInfo pi = 6070 generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 6071 if (pi != null) { 6072 list.add(pi); 6073 } 6074 } 6075 } 6076 6077 return new ParceledListSlice<PackageInfo>(list); 6078 } 6079 } 6080 6081 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 6082 String[] permissions, boolean[] tmp, int flags, int userId) { 6083 int numMatch = 0; 6084 final PermissionsState permissionsState = ps.getPermissionsState(); 6085 for (int i=0; i<permissions.length; i++) { 6086 final String permission = permissions[i]; 6087 if (permissionsState.hasPermission(permission, userId)) { 6088 tmp[i] = true; 6089 numMatch++; 6090 } else { 6091 tmp[i] = false; 6092 } 6093 } 6094 if (numMatch == 0) { 6095 return; 6096 } 6097 final PackageInfo pi; 6098 if (ps.pkg != null) { 6099 pi = generatePackageInfo(ps, flags, userId); 6100 } else { 6101 pi = generatePackageInfo(ps, flags, userId); 6102 } 6103 // The above might return null in cases of uninstalled apps or install-state 6104 // skew across users/profiles. 6105 if (pi != null) { 6106 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 6107 if (numMatch == permissions.length) { 6108 pi.requestedPermissions = permissions; 6109 } else { 6110 pi.requestedPermissions = new String[numMatch]; 6111 numMatch = 0; 6112 for (int i=0; i<permissions.length; i++) { 6113 if (tmp[i]) { 6114 pi.requestedPermissions[numMatch] = permissions[i]; 6115 numMatch++; 6116 } 6117 } 6118 } 6119 } 6120 list.add(pi); 6121 } 6122 } 6123 6124 @Override 6125 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 6126 String[] permissions, int flags, int userId) { 6127 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6128 flags = updateFlagsForPackage(flags, userId, permissions); 6129 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6130 6131 // writer 6132 synchronized (mPackages) { 6133 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 6134 boolean[] tmpBools = new boolean[permissions.length]; 6135 if (listUninstalled) { 6136 for (PackageSetting ps : mSettings.mPackages.values()) { 6137 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 6138 } 6139 } else { 6140 for (PackageParser.Package pkg : mPackages.values()) { 6141 PackageSetting ps = (PackageSetting)pkg.mExtras; 6142 if (ps != null) { 6143 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6144 userId); 6145 } 6146 } 6147 } 6148 6149 return new ParceledListSlice<PackageInfo>(list); 6150 } 6151 } 6152 6153 @Override 6154 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 6155 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6156 flags = updateFlagsForApplication(flags, userId, null); 6157 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6158 6159 // writer 6160 synchronized (mPackages) { 6161 ArrayList<ApplicationInfo> list; 6162 if (listUninstalled) { 6163 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 6164 for (PackageSetting ps : mSettings.mPackages.values()) { 6165 ApplicationInfo ai; 6166 if (ps.pkg != null) { 6167 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 6168 ps.readUserState(userId), userId); 6169 } else { 6170 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 6171 } 6172 if (ai != null) { 6173 list.add(ai); 6174 } 6175 } 6176 } else { 6177 list = new ArrayList<ApplicationInfo>(mPackages.size()); 6178 for (PackageParser.Package p : mPackages.values()) { 6179 if (p.mExtras != null) { 6180 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6181 ((PackageSetting)p.mExtras).readUserState(userId), userId); 6182 if (ai != null) { 6183 list.add(ai); 6184 } 6185 } 6186 } 6187 } 6188 6189 return new ParceledListSlice<ApplicationInfo>(list); 6190 } 6191 } 6192 6193 @Override 6194 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 6195 if (DISABLE_EPHEMERAL_APPS) { 6196 return null; 6197 } 6198 6199 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6200 "getEphemeralApplications"); 6201 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6202 true /* requireFullPermission */, false /* checkShell */, 6203 "getEphemeralApplications"); 6204 synchronized (mPackages) { 6205 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 6206 .getEphemeralApplicationsLPw(userId); 6207 if (ephemeralApps != null) { 6208 return new ParceledListSlice<>(ephemeralApps); 6209 } 6210 } 6211 return null; 6212 } 6213 6214 @Override 6215 public boolean isEphemeralApplication(String packageName, int userId) { 6216 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6217 true /* requireFullPermission */, false /* checkShell */, 6218 "isEphemeral"); 6219 if (DISABLE_EPHEMERAL_APPS) { 6220 return false; 6221 } 6222 6223 if (!isCallerSameApp(packageName)) { 6224 return false; 6225 } 6226 synchronized (mPackages) { 6227 PackageParser.Package pkg = mPackages.get(packageName); 6228 if (pkg != null) { 6229 return pkg.applicationInfo.isEphemeralApp(); 6230 } 6231 } 6232 return false; 6233 } 6234 6235 @Override 6236 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6237 if (DISABLE_EPHEMERAL_APPS) { 6238 return null; 6239 } 6240 6241 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6242 true /* requireFullPermission */, false /* checkShell */, 6243 "getCookie"); 6244 if (!isCallerSameApp(packageName)) { 6245 return null; 6246 } 6247 synchronized (mPackages) { 6248 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6249 packageName, userId); 6250 } 6251 } 6252 6253 @Override 6254 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6255 if (DISABLE_EPHEMERAL_APPS) { 6256 return true; 6257 } 6258 6259 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6260 true /* requireFullPermission */, true /* checkShell */, 6261 "setCookie"); 6262 if (!isCallerSameApp(packageName)) { 6263 return false; 6264 } 6265 synchronized (mPackages) { 6266 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6267 packageName, cookie, userId); 6268 } 6269 } 6270 6271 @Override 6272 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6273 if (DISABLE_EPHEMERAL_APPS) { 6274 return null; 6275 } 6276 6277 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6278 "getEphemeralApplicationIcon"); 6279 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6280 true /* requireFullPermission */, false /* checkShell */, 6281 "getEphemeralApplicationIcon"); 6282 synchronized (mPackages) { 6283 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6284 packageName, userId); 6285 } 6286 } 6287 6288 private boolean isCallerSameApp(String packageName) { 6289 PackageParser.Package pkg = mPackages.get(packageName); 6290 return pkg != null 6291 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6292 } 6293 6294 @Override 6295 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 6296 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 6297 } 6298 6299 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 6300 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6301 6302 // reader 6303 synchronized (mPackages) { 6304 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6305 final int userId = UserHandle.getCallingUserId(); 6306 while (i.hasNext()) { 6307 final PackageParser.Package p = i.next(); 6308 if (p.applicationInfo == null) continue; 6309 6310 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 6311 && !p.applicationInfo.isDirectBootAware(); 6312 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 6313 && p.applicationInfo.isDirectBootAware(); 6314 6315 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6316 && (!mSafeMode || isSystemApp(p)) 6317 && (matchesUnaware || matchesAware)) { 6318 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6319 if (ps != null) { 6320 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6321 ps.readUserState(userId), userId); 6322 if (ai != null) { 6323 finalList.add(ai); 6324 } 6325 } 6326 } 6327 } 6328 } 6329 6330 return finalList; 6331 } 6332 6333 @Override 6334 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6335 if (!sUserManager.exists(userId)) return null; 6336 flags = updateFlagsForComponent(flags, userId, name); 6337 // reader 6338 synchronized (mPackages) { 6339 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6340 PackageSetting ps = provider != null 6341 ? mSettings.mPackages.get(provider.owner.packageName) 6342 : null; 6343 return ps != null 6344 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6345 ? PackageParser.generateProviderInfo(provider, flags, 6346 ps.readUserState(userId), userId) 6347 : null; 6348 } 6349 } 6350 6351 /** 6352 * @deprecated 6353 */ 6354 @Deprecated 6355 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6356 // reader 6357 synchronized (mPackages) { 6358 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6359 .entrySet().iterator(); 6360 final int userId = UserHandle.getCallingUserId(); 6361 while (i.hasNext()) { 6362 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6363 PackageParser.Provider p = entry.getValue(); 6364 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6365 6366 if (ps != null && p.syncable 6367 && (!mSafeMode || (p.info.applicationInfo.flags 6368 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6369 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6370 ps.readUserState(userId), userId); 6371 if (info != null) { 6372 outNames.add(entry.getKey()); 6373 outInfo.add(info); 6374 } 6375 } 6376 } 6377 } 6378 } 6379 6380 @Override 6381 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6382 int uid, int flags) { 6383 final int userId = processName != null ? UserHandle.getUserId(uid) 6384 : UserHandle.getCallingUserId(); 6385 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6386 flags = updateFlagsForComponent(flags, userId, processName); 6387 6388 ArrayList<ProviderInfo> finalList = null; 6389 // reader 6390 synchronized (mPackages) { 6391 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6392 while (i.hasNext()) { 6393 final PackageParser.Provider p = i.next(); 6394 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6395 if (ps != null && p.info.authority != null 6396 && (processName == null 6397 || (p.info.processName.equals(processName) 6398 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6399 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6400 if (finalList == null) { 6401 finalList = new ArrayList<ProviderInfo>(3); 6402 } 6403 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6404 ps.readUserState(userId), userId); 6405 if (info != null) { 6406 finalList.add(info); 6407 } 6408 } 6409 } 6410 } 6411 6412 if (finalList != null) { 6413 Collections.sort(finalList, mProviderInitOrderSorter); 6414 return new ParceledListSlice<ProviderInfo>(finalList); 6415 } 6416 6417 return ParceledListSlice.emptyList(); 6418 } 6419 6420 @Override 6421 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6422 // reader 6423 synchronized (mPackages) { 6424 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6425 return PackageParser.generateInstrumentationInfo(i, flags); 6426 } 6427 } 6428 6429 @Override 6430 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 6431 String targetPackage, int flags) { 6432 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 6433 } 6434 6435 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 6436 int flags) { 6437 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 6438 6439 // reader 6440 synchronized (mPackages) { 6441 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6442 while (i.hasNext()) { 6443 final PackageParser.Instrumentation p = i.next(); 6444 if (targetPackage == null 6445 || targetPackage.equals(p.info.targetPackage)) { 6446 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6447 flags); 6448 if (ii != null) { 6449 finalList.add(ii); 6450 } 6451 } 6452 } 6453 } 6454 6455 return finalList; 6456 } 6457 6458 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6459 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6460 if (overlays == null) { 6461 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6462 return; 6463 } 6464 for (PackageParser.Package opkg : overlays.values()) { 6465 // Not much to do if idmap fails: we already logged the error 6466 // and we certainly don't want to abort installation of pkg simply 6467 // because an overlay didn't fit properly. For these reasons, 6468 // ignore the return value of createIdmapForPackagePairLI. 6469 createIdmapForPackagePairLI(pkg, opkg); 6470 } 6471 } 6472 6473 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6474 PackageParser.Package opkg) { 6475 if (!opkg.mTrustedOverlay) { 6476 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6477 opkg.baseCodePath + ": overlay not trusted"); 6478 return false; 6479 } 6480 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6481 if (overlaySet == null) { 6482 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6483 opkg.baseCodePath + " but target package has no known overlays"); 6484 return false; 6485 } 6486 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6487 // TODO: generate idmap for split APKs 6488 try { 6489 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6490 } catch (InstallerException e) { 6491 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6492 + opkg.baseCodePath); 6493 return false; 6494 } 6495 PackageParser.Package[] overlayArray = 6496 overlaySet.values().toArray(new PackageParser.Package[0]); 6497 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6498 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6499 return p1.mOverlayPriority - p2.mOverlayPriority; 6500 } 6501 }; 6502 Arrays.sort(overlayArray, cmp); 6503 6504 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6505 int i = 0; 6506 for (PackageParser.Package p : overlayArray) { 6507 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6508 } 6509 return true; 6510 } 6511 6512 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6513 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6514 try { 6515 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6516 } finally { 6517 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6518 } 6519 } 6520 6521 private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6522 final File[] files = dir.listFiles(); 6523 if (ArrayUtils.isEmpty(files)) { 6524 Log.d(TAG, "No files in app dir " + dir); 6525 return; 6526 } 6527 6528 if (DEBUG_PACKAGE_SCANNING) { 6529 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6530 + " flags=0x" + Integer.toHexString(parseFlags)); 6531 } 6532 6533 for (File file : files) { 6534 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6535 && !PackageInstallerService.isStageName(file.getName()); 6536 if (!isPackage) { 6537 // Ignore entries which are not packages 6538 continue; 6539 } 6540 try { 6541 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6542 scanFlags, currentTime, null); 6543 } catch (PackageManagerException e) { 6544 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6545 6546 // Delete invalid userdata apps 6547 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6548 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6549 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6550 removeCodePathLI(file); 6551 } 6552 } 6553 } 6554 } 6555 6556 private static File getSettingsProblemFile() { 6557 File dataDir = Environment.getDataDirectory(); 6558 File systemDir = new File(dataDir, "system"); 6559 File fname = new File(systemDir, "uiderrors.txt"); 6560 return fname; 6561 } 6562 6563 static void reportSettingsProblem(int priority, String msg) { 6564 logCriticalInfo(priority, msg); 6565 } 6566 6567 static void logCriticalInfo(int priority, String msg) { 6568 Slog.println(priority, TAG, msg); 6569 EventLogTags.writePmCriticalInfo(msg); 6570 try { 6571 File fname = getSettingsProblemFile(); 6572 FileOutputStream out = new FileOutputStream(fname, true); 6573 PrintWriter pw = new FastPrintWriter(out); 6574 SimpleDateFormat formatter = new SimpleDateFormat(); 6575 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6576 pw.println(dateString + ": " + msg); 6577 pw.close(); 6578 FileUtils.setPermissions( 6579 fname.toString(), 6580 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6581 -1, -1); 6582 } catch (java.io.IOException e) { 6583 } 6584 } 6585 6586 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6587 final int policyFlags) throws PackageManagerException { 6588 if (ps != null 6589 && ps.codePath.equals(srcFile) 6590 && ps.timeStamp == srcFile.lastModified() 6591 && !isCompatSignatureUpdateNeeded(pkg) 6592 && !isRecoverSignatureUpdateNeeded(pkg)) { 6593 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6594 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6595 ArraySet<PublicKey> signingKs; 6596 synchronized (mPackages) { 6597 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6598 } 6599 if (ps.signatures.mSignatures != null 6600 && ps.signatures.mSignatures.length != 0 6601 && signingKs != null) { 6602 // Optimization: reuse the existing cached certificates 6603 // if the package appears to be unchanged. 6604 pkg.mSignatures = ps.signatures.mSignatures; 6605 pkg.mSigningKeys = signingKs; 6606 return; 6607 } 6608 6609 Slog.w(TAG, "PackageSetting for " + ps.name 6610 + " is missing signatures. Collecting certs again to recover them."); 6611 } else { 6612 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6613 } 6614 6615 try { 6616 PackageParser.collectCertificates(pkg, policyFlags); 6617 } catch (PackageParserException e) { 6618 throw PackageManagerException.from(e); 6619 } 6620 } 6621 6622 /** 6623 * Traces a package scan. 6624 * @see #scanPackageLI(File, int, int, long, UserHandle) 6625 */ 6626 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 6627 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6628 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6629 try { 6630 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6631 } finally { 6632 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6633 } 6634 } 6635 6636 /** 6637 * Scans a package and returns the newly parsed package. 6638 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6639 */ 6640 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6641 long currentTime, UserHandle user) throws PackageManagerException { 6642 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6643 PackageParser pp = new PackageParser(); 6644 pp.setSeparateProcesses(mSeparateProcesses); 6645 pp.setOnlyCoreApps(mOnlyCore); 6646 pp.setDisplayMetrics(mMetrics); 6647 6648 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6649 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6650 } 6651 6652 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 6653 final PackageParser.Package pkg; 6654 try { 6655 pkg = pp.parsePackage(scanFile, parseFlags); 6656 } catch (PackageParserException e) { 6657 throw PackageManagerException.from(e); 6658 } finally { 6659 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6660 } 6661 6662 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6663 } 6664 6665 /** 6666 * Scans a package and returns the newly parsed package. 6667 * @throws PackageManagerException on a parse error. 6668 */ 6669 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6670 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 6671 throws PackageManagerException { 6672 // If the package has children and this is the first dive in the function 6673 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6674 // packages (parent and children) would be successfully scanned before the 6675 // actual scan since scanning mutates internal state and we want to atomically 6676 // install the package and its children. 6677 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6678 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6679 scanFlags |= SCAN_CHECK_ONLY; 6680 } 6681 } else { 6682 scanFlags &= ~SCAN_CHECK_ONLY; 6683 } 6684 6685 // Scan the parent 6686 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 6687 scanFlags, currentTime, user); 6688 6689 // Scan the children 6690 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6691 for (int i = 0; i < childCount; i++) { 6692 PackageParser.Package childPackage = pkg.childPackages.get(i); 6693 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 6694 currentTime, user); 6695 } 6696 6697 6698 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6699 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 6700 } 6701 6702 return scannedPkg; 6703 } 6704 6705 /** 6706 * Scans a package and returns the newly parsed package. 6707 * @throws PackageManagerException on a parse error. 6708 */ 6709 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6710 int policyFlags, int scanFlags, long currentTime, UserHandle user) 6711 throws PackageManagerException { 6712 PackageSetting ps = null; 6713 PackageSetting updatedPkg; 6714 // reader 6715 synchronized (mPackages) { 6716 // Look to see if we already know about this package. 6717 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6718 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6719 // This package has been renamed to its original name. Let's 6720 // use that. 6721 ps = mSettings.peekPackageLPr(oldName); 6722 } 6723 // If there was no original package, see one for the real package name. 6724 if (ps == null) { 6725 ps = mSettings.peekPackageLPr(pkg.packageName); 6726 } 6727 // Check to see if this package could be hiding/updating a system 6728 // package. Must look for it either under the original or real 6729 // package name depending on our state. 6730 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6731 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6732 6733 // If this is a package we don't know about on the system partition, we 6734 // may need to remove disabled child packages on the system partition 6735 // or may need to not add child packages if the parent apk is updated 6736 // on the data partition and no longer defines this child package. 6737 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6738 // If this is a parent package for an updated system app and this system 6739 // app got an OTA update which no longer defines some of the child packages 6740 // we have to prune them from the disabled system packages. 6741 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6742 if (disabledPs != null) { 6743 final int scannedChildCount = (pkg.childPackages != null) 6744 ? pkg.childPackages.size() : 0; 6745 final int disabledChildCount = disabledPs.childPackageNames != null 6746 ? disabledPs.childPackageNames.size() : 0; 6747 for (int i = 0; i < disabledChildCount; i++) { 6748 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6749 boolean disabledPackageAvailable = false; 6750 for (int j = 0; j < scannedChildCount; j++) { 6751 PackageParser.Package childPkg = pkg.childPackages.get(j); 6752 if (childPkg.packageName.equals(disabledChildPackageName)) { 6753 disabledPackageAvailable = true; 6754 break; 6755 } 6756 } 6757 if (!disabledPackageAvailable) { 6758 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6759 } 6760 } 6761 } 6762 } 6763 } 6764 6765 boolean updatedPkgBetter = false; 6766 // First check if this is a system package that may involve an update 6767 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6768 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6769 // it needs to drop FLAG_PRIVILEGED. 6770 if (locationIsPrivileged(scanFile)) { 6771 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6772 } else { 6773 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6774 } 6775 6776 if (ps != null && !ps.codePath.equals(scanFile)) { 6777 // The path has changed from what was last scanned... check the 6778 // version of the new path against what we have stored to determine 6779 // what to do. 6780 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6781 if (pkg.mVersionCode <= ps.versionCode) { 6782 // The system package has been updated and the code path does not match 6783 // Ignore entry. Skip it. 6784 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6785 + " ignored: updated version " + ps.versionCode 6786 + " better than this " + pkg.mVersionCode); 6787 if (!updatedPkg.codePath.equals(scanFile)) { 6788 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6789 + ps.name + " changing from " + updatedPkg.codePathString 6790 + " to " + scanFile); 6791 updatedPkg.codePath = scanFile; 6792 updatedPkg.codePathString = scanFile.toString(); 6793 updatedPkg.resourcePath = scanFile; 6794 updatedPkg.resourcePathString = scanFile.toString(); 6795 } 6796 updatedPkg.pkg = pkg; 6797 updatedPkg.versionCode = pkg.mVersionCode; 6798 6799 // Update the disabled system child packages to point to the package too. 6800 final int childCount = updatedPkg.childPackageNames != null 6801 ? updatedPkg.childPackageNames.size() : 0; 6802 for (int i = 0; i < childCount; i++) { 6803 String childPackageName = updatedPkg.childPackageNames.get(i); 6804 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 6805 childPackageName); 6806 if (updatedChildPkg != null) { 6807 updatedChildPkg.pkg = pkg; 6808 updatedChildPkg.versionCode = pkg.mVersionCode; 6809 } 6810 } 6811 6812 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 6813 + scanFile + " ignored: updated version " + ps.versionCode 6814 + " better than this " + pkg.mVersionCode); 6815 } else { 6816 // The current app on the system partition is better than 6817 // what we have updated to on the data partition; switch 6818 // back to the system partition version. 6819 // At this point, its safely assumed that package installation for 6820 // apps in system partition will go through. If not there won't be a working 6821 // version of the app 6822 // writer 6823 synchronized (mPackages) { 6824 // Just remove the loaded entries from package lists. 6825 mPackages.remove(ps.name); 6826 } 6827 6828 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6829 + " reverting from " + ps.codePathString 6830 + ": new version " + pkg.mVersionCode 6831 + " better than installed " + ps.versionCode); 6832 6833 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6834 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6835 synchronized (mInstallLock) { 6836 args.cleanUpResourcesLI(); 6837 } 6838 synchronized (mPackages) { 6839 mSettings.enableSystemPackageLPw(ps.name); 6840 } 6841 updatedPkgBetter = true; 6842 } 6843 } 6844 } 6845 6846 if (updatedPkg != null) { 6847 // An updated system app will not have the PARSE_IS_SYSTEM flag set 6848 // initially 6849 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 6850 6851 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 6852 // flag set initially 6853 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 6854 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 6855 } 6856 } 6857 6858 // Verify certificates against what was last scanned 6859 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 6860 6861 /* 6862 * A new system app appeared, but we already had a non-system one of the 6863 * same name installed earlier. 6864 */ 6865 boolean shouldHideSystemApp = false; 6866 if (updatedPkg == null && ps != null 6867 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 6868 /* 6869 * Check to make sure the signatures match first. If they don't, 6870 * wipe the installed application and its data. 6871 */ 6872 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 6873 != PackageManager.SIGNATURE_MATCH) { 6874 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 6875 + " signatures don't match existing userdata copy; removing"); 6876 try (PackageFreezer freezer = freezePackage(pkg.packageName, 6877 "scanPackageInternalLI")) { 6878 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 6879 } 6880 ps = null; 6881 } else { 6882 /* 6883 * If the newly-added system app is an older version than the 6884 * already installed version, hide it. It will be scanned later 6885 * and re-added like an update. 6886 */ 6887 if (pkg.mVersionCode <= ps.versionCode) { 6888 shouldHideSystemApp = true; 6889 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 6890 + " but new version " + pkg.mVersionCode + " better than installed " 6891 + ps.versionCode + "; hiding system"); 6892 } else { 6893 /* 6894 * The newly found system app is a newer version that the 6895 * one previously installed. Simply remove the 6896 * already-installed application and replace it with our own 6897 * while keeping the application data. 6898 */ 6899 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6900 + " reverting from " + ps.codePathString + ": new version " 6901 + pkg.mVersionCode + " better than installed " + ps.versionCode); 6902 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6903 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6904 synchronized (mInstallLock) { 6905 args.cleanUpResourcesLI(); 6906 } 6907 } 6908 } 6909 } 6910 6911 // The apk is forward locked (not public) if its code and resources 6912 // are kept in different files. (except for app in either system or 6913 // vendor path). 6914 // TODO grab this value from PackageSettings 6915 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6916 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 6917 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 6918 } 6919 } 6920 6921 // TODO: extend to support forward-locked splits 6922 String resourcePath = null; 6923 String baseResourcePath = null; 6924 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 6925 if (ps != null && ps.resourcePathString != null) { 6926 resourcePath = ps.resourcePathString; 6927 baseResourcePath = ps.resourcePathString; 6928 } else { 6929 // Should not happen at all. Just log an error. 6930 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 6931 } 6932 } else { 6933 resourcePath = pkg.codePath; 6934 baseResourcePath = pkg.baseCodePath; 6935 } 6936 6937 // Set application objects path explicitly. 6938 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 6939 pkg.setApplicationInfoCodePath(pkg.codePath); 6940 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 6941 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 6942 pkg.setApplicationInfoResourcePath(resourcePath); 6943 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 6944 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 6945 6946 // Note that we invoke the following method only if we are about to unpack an application 6947 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 6948 | SCAN_UPDATE_SIGNATURE, currentTime, user); 6949 6950 /* 6951 * If the system app should be overridden by a previously installed 6952 * data, hide the system app now and let the /data/app scan pick it up 6953 * again. 6954 */ 6955 if (shouldHideSystemApp) { 6956 synchronized (mPackages) { 6957 mSettings.disableSystemPackageLPw(pkg.packageName, true); 6958 } 6959 } 6960 6961 return scannedPkg; 6962 } 6963 6964 private static String fixProcessName(String defProcessName, 6965 String processName, int uid) { 6966 if (processName == null) { 6967 return defProcessName; 6968 } 6969 return processName; 6970 } 6971 6972 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 6973 throws PackageManagerException { 6974 if (pkgSetting.signatures.mSignatures != null) { 6975 // Already existing package. Make sure signatures match 6976 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 6977 == PackageManager.SIGNATURE_MATCH; 6978 if (!match) { 6979 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 6980 == PackageManager.SIGNATURE_MATCH; 6981 } 6982 if (!match) { 6983 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 6984 == PackageManager.SIGNATURE_MATCH; 6985 } 6986 if (!match) { 6987 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 6988 + pkg.packageName + " signatures do not match the " 6989 + "previously installed version; ignoring!"); 6990 } 6991 } 6992 6993 // Check for shared user signatures 6994 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 6995 // Already existing package. Make sure signatures match 6996 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6997 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 6998 if (!match) { 6999 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 7000 == PackageManager.SIGNATURE_MATCH; 7001 } 7002 if (!match) { 7003 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 7004 == PackageManager.SIGNATURE_MATCH; 7005 } 7006 if (!match) { 7007 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 7008 "Package " + pkg.packageName 7009 + " has no signatures that match those in shared user " 7010 + pkgSetting.sharedUser.name + "; ignoring!"); 7011 } 7012 } 7013 } 7014 7015 /** 7016 * Enforces that only the system UID or root's UID can call a method exposed 7017 * via Binder. 7018 * 7019 * @param message used as message if SecurityException is thrown 7020 * @throws SecurityException if the caller is not system or root 7021 */ 7022 private static final void enforceSystemOrRoot(String message) { 7023 final int uid = Binder.getCallingUid(); 7024 if (uid != Process.SYSTEM_UID && uid != 0) { 7025 throw new SecurityException(message); 7026 } 7027 } 7028 7029 @Override 7030 public void performFstrimIfNeeded() { 7031 enforceSystemOrRoot("Only the system can request fstrim"); 7032 7033 // Before everything else, see whether we need to fstrim. 7034 try { 7035 IMountService ms = PackageHelper.getMountService(); 7036 if (ms != null) { 7037 final boolean isUpgrade = isUpgrade(); 7038 boolean doTrim = isUpgrade; 7039 if (doTrim) { 7040 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 7041 } else { 7042 final long interval = android.provider.Settings.Global.getLong( 7043 mContext.getContentResolver(), 7044 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 7045 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 7046 if (interval > 0) { 7047 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 7048 if (timeSinceLast > interval) { 7049 doTrim = true; 7050 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 7051 + "; running immediately"); 7052 } 7053 } 7054 } 7055 if (doTrim) { 7056 if (!isFirstBoot()) { 7057 try { 7058 ActivityManagerNative.getDefault().showBootMessage( 7059 mContext.getResources().getString( 7060 R.string.android_upgrading_fstrim), true); 7061 } catch (RemoteException e) { 7062 } 7063 } 7064 ms.runMaintenance(); 7065 } 7066 } else { 7067 Slog.e(TAG, "Mount service unavailable!"); 7068 } 7069 } catch (RemoteException e) { 7070 // Can't happen; MountService is local 7071 } 7072 } 7073 7074 @Override 7075 public void updatePackagesIfNeeded() { 7076 enforceSystemOrRoot("Only the system can request package update"); 7077 7078 // We need to re-extract after an OTA. 7079 boolean causeUpgrade = isUpgrade(); 7080 7081 // First boot or factory reset. 7082 // Note: we also handle devices that are upgrading to N right now as if it is their 7083 // first boot, as they do not have profile data. 7084 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 7085 7086 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 7087 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 7088 7089 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 7090 return; 7091 } 7092 7093 List<PackageParser.Package> pkgs; 7094 synchronized (mPackages) { 7095 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 7096 } 7097 7098 int curr = 0; 7099 int total = pkgs.size(); 7100 for (PackageParser.Package pkg : pkgs) { 7101 curr++; 7102 7103 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 7104 if (DEBUG_DEXOPT) { 7105 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 7106 } 7107 continue; 7108 } 7109 7110 if (DEBUG_DEXOPT) { 7111 Log.i(TAG, "Extracting app " + curr + " of " + total + ": " + pkg.packageName); 7112 } 7113 7114 if (!isFirstBoot()) { 7115 try { 7116 ActivityManagerNative.getDefault().showBootMessage( 7117 mContext.getResources().getString(R.string.android_upgrading_apk, 7118 curr, total), true); 7119 } catch (RemoteException e) { 7120 } 7121 } 7122 7123 performDexOpt(pkg.packageName, 7124 null /* instructionSet */, 7125 false /* checkProfiles */, 7126 causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT, 7127 false /* force */); 7128 } 7129 } 7130 7131 @Override 7132 public void notifyPackageUse(String packageName) { 7133 synchronized (mPackages) { 7134 PackageParser.Package p = mPackages.get(packageName); 7135 if (p == null) { 7136 return; 7137 } 7138 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 7139 } 7140 } 7141 7142 // TODO: this is not used nor needed. Delete it. 7143 @Override 7144 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 7145 return performDexOptTraced(packageName, instructionSet, false /* checkProfiles */, 7146 getFullCompilerFilter(), false /* force */); 7147 } 7148 7149 @Override 7150 public boolean performDexOpt(String packageName, String instructionSet, 7151 boolean checkProfiles, int compileReason, boolean force) { 7152 return performDexOptTraced(packageName, instructionSet, checkProfiles, 7153 getCompilerFilterForReason(compileReason), force); 7154 } 7155 7156 @Override 7157 public boolean performDexOptMode(String packageName, String instructionSet, 7158 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7159 return performDexOptTraced(packageName, instructionSet, checkProfiles, 7160 targetCompilerFilter, force); 7161 } 7162 7163 private boolean performDexOptTraced(String packageName, String instructionSet, 7164 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7165 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7166 try { 7167 return performDexOptInternal(packageName, instructionSet, checkProfiles, 7168 targetCompilerFilter, force); 7169 } finally { 7170 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7171 } 7172 } 7173 7174 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 7175 // if the package can now be considered up to date for the given filter. 7176 private boolean performDexOptInternal(String packageName, String instructionSet, 7177 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7178 PackageParser.Package p; 7179 final String targetInstructionSet; 7180 synchronized (mPackages) { 7181 p = mPackages.get(packageName); 7182 if (p == null) { 7183 return false; 7184 } 7185 mPackageUsage.write(false); 7186 7187 targetInstructionSet = instructionSet != null ? instructionSet : 7188 getPrimaryInstructionSet(p.applicationInfo); 7189 } 7190 long callingId = Binder.clearCallingIdentity(); 7191 try { 7192 synchronized (mInstallLock) { 7193 final String[] instructionSets = new String[] { targetInstructionSet }; 7194 int result = performDexOptInternalWithDependenciesLI(p, instructionSets, 7195 checkProfiles, targetCompilerFilter, force); 7196 return result != PackageDexOptimizer.DEX_OPT_FAILED; 7197 } 7198 } finally { 7199 Binder.restoreCallingIdentity(callingId); 7200 } 7201 } 7202 7203 public ArraySet<String> getOptimizablePackages() { 7204 ArraySet<String> pkgs = new ArraySet<String>(); 7205 synchronized (mPackages) { 7206 for (PackageParser.Package p : mPackages.values()) { 7207 if (PackageDexOptimizer.canOptimizePackage(p)) { 7208 pkgs.add(p.packageName); 7209 } 7210 } 7211 } 7212 return pkgs; 7213 } 7214 7215 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7216 String instructionSets[], boolean checkProfiles, String targetCompilerFilter, 7217 boolean force) { 7218 // Select the dex optimizer based on the force parameter. 7219 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7220 // allocate an object here. 7221 PackageDexOptimizer pdo = force 7222 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7223 : mPackageDexOptimizer; 7224 7225 // Optimize all dependencies first. Note: we ignore the return value and march on 7226 // on errors. 7227 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7228 if (!deps.isEmpty()) { 7229 for (PackageParser.Package depPackage : deps) { 7230 // TODO: Analyze and investigate if we (should) profile libraries. 7231 // Currently this will do a full compilation of the library by default. 7232 pdo.performDexOpt(depPackage, instructionSets, false /* checkProfiles */, 7233 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY)); 7234 } 7235 } 7236 7237 return pdo.performDexOpt(p, instructionSets, checkProfiles, targetCompilerFilter); 7238 } 7239 7240 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7241 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7242 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7243 Set<String> collectedNames = new HashSet<>(); 7244 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7245 7246 retValue.remove(p); 7247 7248 return retValue; 7249 } else { 7250 return Collections.emptyList(); 7251 } 7252 } 7253 7254 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7255 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7256 if (!collectedNames.contains(p.packageName)) { 7257 collectedNames.add(p.packageName); 7258 collected.add(p); 7259 7260 if (p.usesLibraries != null) { 7261 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7262 } 7263 if (p.usesOptionalLibraries != null) { 7264 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7265 collectedNames); 7266 } 7267 } 7268 } 7269 7270 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7271 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7272 for (String libName : libs) { 7273 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7274 if (libPkg != null) { 7275 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7276 } 7277 } 7278 } 7279 7280 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7281 synchronized (mPackages) { 7282 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7283 if (lib != null && lib.apk != null) { 7284 return mPackages.get(lib.apk); 7285 } 7286 } 7287 return null; 7288 } 7289 7290 public void shutdown() { 7291 mPackageUsage.write(true); 7292 } 7293 7294 @Override 7295 public void forceDexOpt(String packageName) { 7296 enforceSystemOrRoot("forceDexOpt"); 7297 7298 PackageParser.Package pkg; 7299 synchronized (mPackages) { 7300 pkg = mPackages.get(packageName); 7301 if (pkg == null) { 7302 throw new IllegalArgumentException("Unknown package: " + packageName); 7303 } 7304 } 7305 7306 synchronized (mInstallLock) { 7307 final String[] instructionSets = new String[] { 7308 getPrimaryInstructionSet(pkg.applicationInfo) }; 7309 7310 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7311 7312 // Whoever is calling forceDexOpt wants a fully compiled package. 7313 // Don't use profiles since that may cause compilation to be skipped. 7314 final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets, 7315 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7316 true /* force */); 7317 7318 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7319 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7320 throw new IllegalStateException("Failed to dexopt: " + res); 7321 } 7322 } 7323 } 7324 7325 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7326 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7327 Slog.w(TAG, "Unable to update from " + oldPkg.name 7328 + " to " + newPkg.packageName 7329 + ": old package not in system partition"); 7330 return false; 7331 } else if (mPackages.get(oldPkg.name) != null) { 7332 Slog.w(TAG, "Unable to update from " + oldPkg.name 7333 + " to " + newPkg.packageName 7334 + ": old package still exists"); 7335 return false; 7336 } 7337 return true; 7338 } 7339 7340 void removeCodePathLI(File codePath) { 7341 if (codePath.isDirectory()) { 7342 try { 7343 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7344 } catch (InstallerException e) { 7345 Slog.w(TAG, "Failed to remove code path", e); 7346 } 7347 } else { 7348 codePath.delete(); 7349 } 7350 } 7351 7352 private int[] resolveUserIds(int userId) { 7353 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 7354 } 7355 7356 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7357 if (pkg == null) { 7358 Slog.wtf(TAG, "Package was null!", new Throwable()); 7359 return; 7360 } 7361 clearAppDataLeafLIF(pkg, userId, flags); 7362 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7363 for (int i = 0; i < childCount; i++) { 7364 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7365 } 7366 } 7367 7368 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7369 final PackageSetting ps; 7370 synchronized (mPackages) { 7371 ps = mSettings.mPackages.get(pkg.packageName); 7372 } 7373 for (int realUserId : resolveUserIds(userId)) { 7374 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7375 try { 7376 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7377 ceDataInode); 7378 } catch (InstallerException e) { 7379 Slog.w(TAG, String.valueOf(e)); 7380 } 7381 } 7382 } 7383 7384 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7385 if (pkg == null) { 7386 Slog.wtf(TAG, "Package was null!", new Throwable()); 7387 return; 7388 } 7389 destroyAppDataLeafLIF(pkg, userId, flags); 7390 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7391 for (int i = 0; i < childCount; i++) { 7392 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7393 } 7394 } 7395 7396 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7397 final PackageSetting ps; 7398 synchronized (mPackages) { 7399 ps = mSettings.mPackages.get(pkg.packageName); 7400 } 7401 for (int realUserId : resolveUserIds(userId)) { 7402 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7403 try { 7404 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7405 ceDataInode); 7406 } catch (InstallerException e) { 7407 Slog.w(TAG, String.valueOf(e)); 7408 } 7409 } 7410 } 7411 7412 private void destroyAppProfilesLIF(PackageParser.Package pkg) { 7413 if (pkg == null) { 7414 Slog.wtf(TAG, "Package was null!", new Throwable()); 7415 return; 7416 } 7417 destroyAppProfilesLeafLIF(pkg); 7418 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7419 for (int i = 0; i < childCount; i++) { 7420 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 7421 } 7422 } 7423 7424 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 7425 try { 7426 mInstaller.destroyAppProfiles(pkg.packageName); 7427 } catch (InstallerException e) { 7428 Slog.w(TAG, String.valueOf(e)); 7429 } 7430 } 7431 7432 private void clearAppProfilesLIF(PackageParser.Package pkg) { 7433 if (pkg == null) { 7434 Slog.wtf(TAG, "Package was null!", new Throwable()); 7435 return; 7436 } 7437 clearAppProfilesLeafLIF(pkg); 7438 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7439 for (int i = 0; i < childCount; i++) { 7440 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 7441 } 7442 } 7443 7444 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 7445 try { 7446 mInstaller.clearAppProfiles(pkg.packageName); 7447 } catch (InstallerException e) { 7448 Slog.w(TAG, String.valueOf(e)); 7449 } 7450 } 7451 7452 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7453 long lastUpdateTime) { 7454 // Set parent install/update time 7455 PackageSetting ps = (PackageSetting) pkg.mExtras; 7456 if (ps != null) { 7457 ps.firstInstallTime = firstInstallTime; 7458 ps.lastUpdateTime = lastUpdateTime; 7459 } 7460 // Set children install/update time 7461 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7462 for (int i = 0; i < childCount; i++) { 7463 PackageParser.Package childPkg = pkg.childPackages.get(i); 7464 ps = (PackageSetting) childPkg.mExtras; 7465 if (ps != null) { 7466 ps.firstInstallTime = firstInstallTime; 7467 ps.lastUpdateTime = lastUpdateTime; 7468 } 7469 } 7470 } 7471 7472 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7473 PackageParser.Package changingLib) { 7474 if (file.path != null) { 7475 usesLibraryFiles.add(file.path); 7476 return; 7477 } 7478 PackageParser.Package p = mPackages.get(file.apk); 7479 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7480 // If we are doing this while in the middle of updating a library apk, 7481 // then we need to make sure to use that new apk for determining the 7482 // dependencies here. (We haven't yet finished committing the new apk 7483 // to the package manager state.) 7484 if (p == null || p.packageName.equals(changingLib.packageName)) { 7485 p = changingLib; 7486 } 7487 } 7488 if (p != null) { 7489 usesLibraryFiles.addAll(p.getAllCodePaths()); 7490 } 7491 } 7492 7493 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7494 PackageParser.Package changingLib) throws PackageManagerException { 7495 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7496 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7497 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7498 for (int i=0; i<N; i++) { 7499 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7500 if (file == null) { 7501 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7502 "Package " + pkg.packageName + " requires unavailable shared library " 7503 + pkg.usesLibraries.get(i) + "; failing!"); 7504 } 7505 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7506 } 7507 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7508 for (int i=0; i<N; i++) { 7509 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7510 if (file == null) { 7511 Slog.w(TAG, "Package " + pkg.packageName 7512 + " desires unavailable shared library " 7513 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7514 } else { 7515 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7516 } 7517 } 7518 N = usesLibraryFiles.size(); 7519 if (N > 0) { 7520 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7521 } else { 7522 pkg.usesLibraryFiles = null; 7523 } 7524 } 7525 } 7526 7527 private static boolean hasString(List<String> list, List<String> which) { 7528 if (list == null) { 7529 return false; 7530 } 7531 for (int i=list.size()-1; i>=0; i--) { 7532 for (int j=which.size()-1; j>=0; j--) { 7533 if (which.get(j).equals(list.get(i))) { 7534 return true; 7535 } 7536 } 7537 } 7538 return false; 7539 } 7540 7541 private void updateAllSharedLibrariesLPw() { 7542 for (PackageParser.Package pkg : mPackages.values()) { 7543 try { 7544 updateSharedLibrariesLPw(pkg, null); 7545 } catch (PackageManagerException e) { 7546 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7547 } 7548 } 7549 } 7550 7551 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7552 PackageParser.Package changingPkg) { 7553 ArrayList<PackageParser.Package> res = null; 7554 for (PackageParser.Package pkg : mPackages.values()) { 7555 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7556 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7557 if (res == null) { 7558 res = new ArrayList<PackageParser.Package>(); 7559 } 7560 res.add(pkg); 7561 try { 7562 updateSharedLibrariesLPw(pkg, changingPkg); 7563 } catch (PackageManagerException e) { 7564 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7565 } 7566 } 7567 } 7568 return res; 7569 } 7570 7571 /** 7572 * Derive the value of the {@code cpuAbiOverride} based on the provided 7573 * value and an optional stored value from the package settings. 7574 */ 7575 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7576 String cpuAbiOverride = null; 7577 7578 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7579 cpuAbiOverride = null; 7580 } else if (abiOverride != null) { 7581 cpuAbiOverride = abiOverride; 7582 } else if (settings != null) { 7583 cpuAbiOverride = settings.cpuAbiOverrideString; 7584 } 7585 7586 return cpuAbiOverride; 7587 } 7588 7589 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 7590 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 7591 throws PackageManagerException { 7592 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7593 // If the package has children and this is the first dive in the function 7594 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7595 // whether all packages (parent and children) would be successfully scanned 7596 // before the actual scan since scanning mutates internal state and we want 7597 // to atomically install the package and its children. 7598 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7599 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7600 scanFlags |= SCAN_CHECK_ONLY; 7601 } 7602 } else { 7603 scanFlags &= ~SCAN_CHECK_ONLY; 7604 } 7605 7606 final PackageParser.Package scannedPkg; 7607 try { 7608 // Scan the parent 7609 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 7610 // Scan the children 7611 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7612 for (int i = 0; i < childCount; i++) { 7613 PackageParser.Package childPkg = pkg.childPackages.get(i); 7614 scanPackageLI(childPkg, policyFlags, 7615 scanFlags, currentTime, user); 7616 } 7617 } finally { 7618 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7619 } 7620 7621 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7622 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 7623 } 7624 7625 return scannedPkg; 7626 } 7627 7628 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 7629 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7630 boolean success = false; 7631 try { 7632 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 7633 currentTime, user); 7634 success = true; 7635 return res; 7636 } finally { 7637 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 7638 // DELETE_DATA_ON_FAILURES is only used by frozen paths 7639 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 7640 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 7641 destroyAppProfilesLIF(pkg); 7642 } 7643 } 7644 } 7645 7646 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 7647 final int policyFlags, final int scanFlags, long currentTime, UserHandle user) 7648 throws PackageManagerException { 7649 final File scanFile = new File(pkg.codePath); 7650 if (pkg.applicationInfo.getCodePath() == null || 7651 pkg.applicationInfo.getResourcePath() == null) { 7652 // Bail out. The resource and code paths haven't been set. 7653 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7654 "Code and resource paths haven't been set correctly"); 7655 } 7656 7657 // Apply policy 7658 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 7659 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 7660 if (pkg.applicationInfo.isDirectBootAware()) { 7661 // we're direct boot aware; set for all components 7662 for (PackageParser.Service s : pkg.services) { 7663 s.info.encryptionAware = s.info.directBootAware = true; 7664 } 7665 for (PackageParser.Provider p : pkg.providers) { 7666 p.info.encryptionAware = p.info.directBootAware = true; 7667 } 7668 for (PackageParser.Activity a : pkg.activities) { 7669 a.info.encryptionAware = a.info.directBootAware = true; 7670 } 7671 for (PackageParser.Activity r : pkg.receivers) { 7672 r.info.encryptionAware = r.info.directBootAware = true; 7673 } 7674 } 7675 } else { 7676 // Only allow system apps to be flagged as core apps. 7677 pkg.coreApp = false; 7678 // clear flags not applicable to regular apps 7679 pkg.applicationInfo.privateFlags &= 7680 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 7681 pkg.applicationInfo.privateFlags &= 7682 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 7683 } 7684 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 7685 7686 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 7687 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7688 } 7689 7690 if (mCustomResolverComponentName != null && 7691 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 7692 setUpCustomResolverActivity(pkg); 7693 } 7694 7695 if (pkg.packageName.equals("android")) { 7696 synchronized (mPackages) { 7697 if (mAndroidApplication != null) { 7698 Slog.w(TAG, "*************************************************"); 7699 Slog.w(TAG, "Core android package being redefined. Skipping."); 7700 Slog.w(TAG, " file=" + scanFile); 7701 Slog.w(TAG, "*************************************************"); 7702 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7703 "Core android package being redefined. Skipping."); 7704 } 7705 7706 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7707 // Set up information for our fall-back user intent resolution activity. 7708 mPlatformPackage = pkg; 7709 pkg.mVersionCode = mSdkVersion; 7710 mAndroidApplication = pkg.applicationInfo; 7711 7712 if (!mResolverReplaced) { 7713 mResolveActivity.applicationInfo = mAndroidApplication; 7714 mResolveActivity.name = ResolverActivity.class.getName(); 7715 mResolveActivity.packageName = mAndroidApplication.packageName; 7716 mResolveActivity.processName = "system:ui"; 7717 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7718 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 7719 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 7720 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 7721 mResolveActivity.exported = true; 7722 mResolveActivity.enabled = true; 7723 mResolveInfo.activityInfo = mResolveActivity; 7724 mResolveInfo.priority = 0; 7725 mResolveInfo.preferredOrder = 0; 7726 mResolveInfo.match = 0; 7727 mResolveComponentName = new ComponentName( 7728 mAndroidApplication.packageName, mResolveActivity.name); 7729 } 7730 } 7731 } 7732 } 7733 7734 if (DEBUG_PACKAGE_SCANNING) { 7735 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 7736 Log.d(TAG, "Scanning package " + pkg.packageName); 7737 } 7738 7739 synchronized (mPackages) { 7740 if (mPackages.containsKey(pkg.packageName) 7741 || mSharedLibraries.containsKey(pkg.packageName)) { 7742 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7743 "Application package " + pkg.packageName 7744 + " already installed. Skipping duplicate."); 7745 } 7746 7747 // If we're only installing presumed-existing packages, require that the 7748 // scanned APK is both already known and at the path previously established 7749 // for it. Previously unknown packages we pick up normally, but if we have an 7750 // a priori expectation about this package's install presence, enforce it. 7751 // With a singular exception for new system packages. When an OTA contains 7752 // a new system package, we allow the codepath to change from a system location 7753 // to the user-installed location. If we don't allow this change, any newer, 7754 // user-installed version of the application will be ignored. 7755 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 7756 if (mExpectingBetter.containsKey(pkg.packageName)) { 7757 logCriticalInfo(Log.WARN, 7758 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 7759 } else { 7760 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 7761 if (known != null) { 7762 if (DEBUG_PACKAGE_SCANNING) { 7763 Log.d(TAG, "Examining " + pkg.codePath 7764 + " and requiring known paths " + known.codePathString 7765 + " & " + known.resourcePathString); 7766 } 7767 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 7768 || !pkg.applicationInfo.getResourcePath().equals( 7769 known.resourcePathString)) { 7770 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 7771 "Application package " + pkg.packageName 7772 + " found at " + pkg.applicationInfo.getCodePath() 7773 + " but expected at " + known.codePathString 7774 + "; ignoring."); 7775 } 7776 } 7777 } 7778 } 7779 } 7780 7781 // Initialize package source and resource directories 7782 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 7783 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 7784 7785 SharedUserSetting suid = null; 7786 PackageSetting pkgSetting = null; 7787 7788 if (!isSystemApp(pkg)) { 7789 // Only system apps can use these features. 7790 pkg.mOriginalPackages = null; 7791 pkg.mRealPackage = null; 7792 pkg.mAdoptPermissions = null; 7793 } 7794 7795 // Getting the package setting may have a side-effect, so if we 7796 // are only checking if scan would succeed, stash a copy of the 7797 // old setting to restore at the end. 7798 PackageSetting nonMutatedPs = null; 7799 7800 // writer 7801 synchronized (mPackages) { 7802 if (pkg.mSharedUserId != null) { 7803 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 7804 if (suid == null) { 7805 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7806 "Creating application package " + pkg.packageName 7807 + " for shared user failed"); 7808 } 7809 if (DEBUG_PACKAGE_SCANNING) { 7810 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 7811 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 7812 + "): packages=" + suid.packages); 7813 } 7814 } 7815 7816 // Check if we are renaming from an original package name. 7817 PackageSetting origPackage = null; 7818 String realName = null; 7819 if (pkg.mOriginalPackages != null) { 7820 // This package may need to be renamed to a previously 7821 // installed name. Let's check on that... 7822 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 7823 if (pkg.mOriginalPackages.contains(renamed)) { 7824 // This package had originally been installed as the 7825 // original name, and we have already taken care of 7826 // transitioning to the new one. Just update the new 7827 // one to continue using the old name. 7828 realName = pkg.mRealPackage; 7829 if (!pkg.packageName.equals(renamed)) { 7830 // Callers into this function may have already taken 7831 // care of renaming the package; only do it here if 7832 // it is not already done. 7833 pkg.setPackageName(renamed); 7834 } 7835 7836 } else { 7837 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 7838 if ((origPackage = mSettings.peekPackageLPr( 7839 pkg.mOriginalPackages.get(i))) != null) { 7840 // We do have the package already installed under its 7841 // original name... should we use it? 7842 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 7843 // New package is not compatible with original. 7844 origPackage = null; 7845 continue; 7846 } else if (origPackage.sharedUser != null) { 7847 // Make sure uid is compatible between packages. 7848 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 7849 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 7850 + " to " + pkg.packageName + ": old uid " 7851 + origPackage.sharedUser.name 7852 + " differs from " + pkg.mSharedUserId); 7853 origPackage = null; 7854 continue; 7855 } 7856 // TODO: Add case when shared user id is added [b/28144775] 7857 } else { 7858 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 7859 + pkg.packageName + " to old name " + origPackage.name); 7860 } 7861 break; 7862 } 7863 } 7864 } 7865 } 7866 7867 if (mTransferedPackages.contains(pkg.packageName)) { 7868 Slog.w(TAG, "Package " + pkg.packageName 7869 + " was transferred to another, but its .apk remains"); 7870 } 7871 7872 // See comments in nonMutatedPs declaration 7873 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7874 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 7875 if (foundPs != null) { 7876 nonMutatedPs = new PackageSetting(foundPs); 7877 } 7878 } 7879 7880 // Just create the setting, don't add it yet. For already existing packages 7881 // the PkgSetting exists already and doesn't have to be created. 7882 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 7883 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 7884 pkg.applicationInfo.primaryCpuAbi, 7885 pkg.applicationInfo.secondaryCpuAbi, 7886 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 7887 user, false); 7888 if (pkgSetting == null) { 7889 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7890 "Creating application package " + pkg.packageName + " failed"); 7891 } 7892 7893 if (pkgSetting.origPackage != null) { 7894 // If we are first transitioning from an original package, 7895 // fix up the new package's name now. We need to do this after 7896 // looking up the package under its new name, so getPackageLP 7897 // can take care of fiddling things correctly. 7898 pkg.setPackageName(origPackage.name); 7899 7900 // File a report about this. 7901 String msg = "New package " + pkgSetting.realName 7902 + " renamed to replace old package " + pkgSetting.name; 7903 reportSettingsProblem(Log.WARN, msg); 7904 7905 // Make a note of it. 7906 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7907 mTransferedPackages.add(origPackage.name); 7908 } 7909 7910 // No longer need to retain this. 7911 pkgSetting.origPackage = null; 7912 } 7913 7914 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 7915 // Make a note of it. 7916 mTransferedPackages.add(pkg.packageName); 7917 } 7918 7919 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 7920 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 7921 } 7922 7923 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7924 // Check all shared libraries and map to their actual file path. 7925 // We only do this here for apps not on a system dir, because those 7926 // are the only ones that can fail an install due to this. We 7927 // will take care of the system apps by updating all of their 7928 // library paths after the scan is done. 7929 updateSharedLibrariesLPw(pkg, null); 7930 } 7931 7932 if (mFoundPolicyFile) { 7933 SELinuxMMAC.assignSeinfoValue(pkg); 7934 } 7935 7936 pkg.applicationInfo.uid = pkgSetting.appId; 7937 pkg.mExtras = pkgSetting; 7938 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 7939 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 7940 // We just determined the app is signed correctly, so bring 7941 // over the latest parsed certs. 7942 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7943 } else { 7944 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7945 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7946 "Package " + pkg.packageName + " upgrade keys do not match the " 7947 + "previously installed version"); 7948 } else { 7949 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7950 String msg = "System package " + pkg.packageName 7951 + " signature changed; retaining data."; 7952 reportSettingsProblem(Log.WARN, msg); 7953 } 7954 } 7955 } else { 7956 try { 7957 verifySignaturesLP(pkgSetting, pkg); 7958 // We just determined the app is signed correctly, so bring 7959 // over the latest parsed certs. 7960 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7961 } catch (PackageManagerException e) { 7962 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7963 throw e; 7964 } 7965 // The signature has changed, but this package is in the system 7966 // image... let's recover! 7967 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7968 // However... if this package is part of a shared user, but it 7969 // doesn't match the signature of the shared user, let's fail. 7970 // What this means is that you can't change the signatures 7971 // associated with an overall shared user, which doesn't seem all 7972 // that unreasonable. 7973 if (pkgSetting.sharedUser != null) { 7974 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7975 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 7976 throw new PackageManagerException( 7977 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 7978 "Signature mismatch for shared user: " 7979 + pkgSetting.sharedUser); 7980 } 7981 } 7982 // File a report about this. 7983 String msg = "System package " + pkg.packageName 7984 + " signature changed; retaining data."; 7985 reportSettingsProblem(Log.WARN, msg); 7986 } 7987 } 7988 // Verify that this new package doesn't have any content providers 7989 // that conflict with existing packages. Only do this if the 7990 // package isn't already installed, since we don't want to break 7991 // things that are installed. 7992 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 7993 final int N = pkg.providers.size(); 7994 int i; 7995 for (i=0; i<N; i++) { 7996 PackageParser.Provider p = pkg.providers.get(i); 7997 if (p.info.authority != null) { 7998 String names[] = p.info.authority.split(";"); 7999 for (int j = 0; j < names.length; j++) { 8000 if (mProvidersByAuthority.containsKey(names[j])) { 8001 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8002 final String otherPackageName = 8003 ((other != null && other.getComponentName() != null) ? 8004 other.getComponentName().getPackageName() : "?"); 8005 throw new PackageManagerException( 8006 INSTALL_FAILED_CONFLICTING_PROVIDER, 8007 "Can't install because provider name " + names[j] 8008 + " (in package " + pkg.applicationInfo.packageName 8009 + ") is already used by " + otherPackageName); 8010 } 8011 } 8012 } 8013 } 8014 } 8015 8016 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 8017 // This package wants to adopt ownership of permissions from 8018 // another package. 8019 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 8020 final String origName = pkg.mAdoptPermissions.get(i); 8021 final PackageSetting orig = mSettings.peekPackageLPr(origName); 8022 if (orig != null) { 8023 if (verifyPackageUpdateLPr(orig, pkg)) { 8024 Slog.i(TAG, "Adopting permissions from " + origName + " to " 8025 + pkg.packageName); 8026 mSettings.transferPermissionsLPw(origName, pkg.packageName); 8027 } 8028 } 8029 } 8030 } 8031 } 8032 8033 final String pkgName = pkg.packageName; 8034 8035 final long scanFileTime = scanFile.lastModified(); 8036 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 8037 pkg.applicationInfo.processName = fixProcessName( 8038 pkg.applicationInfo.packageName, 8039 pkg.applicationInfo.processName, 8040 pkg.applicationInfo.uid); 8041 8042 if (pkg != mPlatformPackage) { 8043 // Get all of our default paths setup 8044 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 8045 } 8046 8047 final String path = scanFile.getPath(); 8048 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 8049 8050 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 8051 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 8052 8053 // Some system apps still use directory structure for native libraries 8054 // in which case we might end up not detecting abi solely based on apk 8055 // structure. Try to detect abi based on directory structure. 8056 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 8057 pkg.applicationInfo.primaryCpuAbi == null) { 8058 setBundledAppAbisAndRoots(pkg, pkgSetting); 8059 setNativeLibraryPaths(pkg); 8060 } 8061 8062 } else { 8063 if ((scanFlags & SCAN_MOVE) != 0) { 8064 // We haven't run dex-opt for this move (since we've moved the compiled output too) 8065 // but we already have this packages package info in the PackageSetting. We just 8066 // use that and derive the native library path based on the new codepath. 8067 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 8068 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 8069 } 8070 8071 // Set native library paths again. For moves, the path will be updated based on the 8072 // ABIs we've determined above. For non-moves, the path will be updated based on the 8073 // ABIs we determined during compilation, but the path will depend on the final 8074 // package path (after the rename away from the stage path). 8075 setNativeLibraryPaths(pkg); 8076 } 8077 8078 // This is a special case for the "system" package, where the ABI is 8079 // dictated by the zygote configuration (and init.rc). We should keep track 8080 // of this ABI so that we can deal with "normal" applications that run under 8081 // the same UID correctly. 8082 if (mPlatformPackage == pkg) { 8083 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 8084 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 8085 } 8086 8087 // If there's a mismatch between the abi-override in the package setting 8088 // and the abiOverride specified for the install. Warn about this because we 8089 // would've already compiled the app without taking the package setting into 8090 // account. 8091 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 8092 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 8093 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 8094 " for package " + pkg.packageName); 8095 } 8096 } 8097 8098 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8099 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8100 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 8101 8102 // Copy the derived override back to the parsed package, so that we can 8103 // update the package settings accordingly. 8104 pkg.cpuAbiOverride = cpuAbiOverride; 8105 8106 if (DEBUG_ABI_SELECTION) { 8107 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 8108 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 8109 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 8110 } 8111 8112 // Push the derived path down into PackageSettings so we know what to 8113 // clean up at uninstall time. 8114 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 8115 8116 if (DEBUG_ABI_SELECTION) { 8117 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 8118 " primary=" + pkg.applicationInfo.primaryCpuAbi + 8119 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 8120 } 8121 8122 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 8123 // We don't do this here during boot because we can do it all 8124 // at once after scanning all existing packages. 8125 // 8126 // We also do this *before* we perform dexopt on this package, so that 8127 // we can avoid redundant dexopts, and also to make sure we've got the 8128 // code and package path correct. 8129 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 8130 pkg, true /* boot complete */); 8131 } 8132 8133 if (mFactoryTest && pkg.requestedPermissions.contains( 8134 android.Manifest.permission.FACTORY_TEST)) { 8135 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 8136 } 8137 8138 ArrayList<PackageParser.Package> clientLibPkgs = null; 8139 8140 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8141 if (nonMutatedPs != null) { 8142 synchronized (mPackages) { 8143 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 8144 } 8145 } 8146 return pkg; 8147 } 8148 8149 // Only privileged apps and updated privileged apps can add child packages. 8150 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 8151 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 8152 throw new PackageManagerException("Only privileged apps and updated " 8153 + "privileged apps can add child packages. Ignoring package " 8154 + pkg.packageName); 8155 } 8156 final int childCount = pkg.childPackages.size(); 8157 for (int i = 0; i < childCount; i++) { 8158 PackageParser.Package childPkg = pkg.childPackages.get(i); 8159 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 8160 childPkg.packageName)) { 8161 throw new PackageManagerException("Cannot override a child package of " 8162 + "another disabled system app. Ignoring package " + pkg.packageName); 8163 } 8164 } 8165 } 8166 8167 // writer 8168 synchronized (mPackages) { 8169 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8170 // Only system apps can add new shared libraries. 8171 if (pkg.libraryNames != null) { 8172 for (int i=0; i<pkg.libraryNames.size(); i++) { 8173 String name = pkg.libraryNames.get(i); 8174 boolean allowed = false; 8175 if (pkg.isUpdatedSystemApp()) { 8176 // New library entries can only be added through the 8177 // system image. This is important to get rid of a lot 8178 // of nasty edge cases: for example if we allowed a non- 8179 // system update of the app to add a library, then uninstalling 8180 // the update would make the library go away, and assumptions 8181 // we made such as through app install filtering would now 8182 // have allowed apps on the device which aren't compatible 8183 // with it. Better to just have the restriction here, be 8184 // conservative, and create many fewer cases that can negatively 8185 // impact the user experience. 8186 final PackageSetting sysPs = mSettings 8187 .getDisabledSystemPkgLPr(pkg.packageName); 8188 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 8189 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 8190 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 8191 allowed = true; 8192 break; 8193 } 8194 } 8195 } 8196 } else { 8197 allowed = true; 8198 } 8199 if (allowed) { 8200 if (!mSharedLibraries.containsKey(name)) { 8201 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 8202 } else if (!name.equals(pkg.packageName)) { 8203 Slog.w(TAG, "Package " + pkg.packageName + " library " 8204 + name + " already exists; skipping"); 8205 } 8206 } else { 8207 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 8208 + name + " that is not declared on system image; skipping"); 8209 } 8210 } 8211 if ((scanFlags & SCAN_BOOTING) == 0) { 8212 // If we are not booting, we need to update any applications 8213 // that are clients of our shared library. If we are booting, 8214 // this will all be done once the scan is complete. 8215 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 8216 } 8217 } 8218 } 8219 } 8220 8221 if ((scanFlags & SCAN_BOOTING) != 0) { 8222 // No apps can run during boot scan, so they don't need to be frozen 8223 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 8224 // Caller asked to not kill app, so it's probably not frozen 8225 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 8226 // Caller asked us to ignore frozen check for some reason; they 8227 // probably didn't know the package name 8228 } else { 8229 // We're doing major surgery on this package, so it better be frozen 8230 // right now to keep it from launching 8231 checkPackageFrozen(pkgName); 8232 } 8233 8234 // Also need to kill any apps that are dependent on the library. 8235 if (clientLibPkgs != null) { 8236 for (int i=0; i<clientLibPkgs.size(); i++) { 8237 PackageParser.Package clientPkg = clientLibPkgs.get(i); 8238 killApplication(clientPkg.applicationInfo.packageName, 8239 clientPkg.applicationInfo.uid, "update lib"); 8240 } 8241 } 8242 8243 // Make sure we're not adding any bogus keyset info 8244 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8245 ksms.assertScannedPackageValid(pkg); 8246 8247 // writer 8248 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 8249 8250 boolean createIdmapFailed = false; 8251 synchronized (mPackages) { 8252 // We don't expect installation to fail beyond this point 8253 8254 // Add the new setting to mSettings 8255 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 8256 // Add the new setting to mPackages 8257 mPackages.put(pkg.applicationInfo.packageName, pkg); 8258 // Make sure we don't accidentally delete its data. 8259 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 8260 while (iter.hasNext()) { 8261 PackageCleanItem item = iter.next(); 8262 if (pkgName.equals(item.packageName)) { 8263 iter.remove(); 8264 } 8265 } 8266 8267 // Take care of first install / last update times. 8268 if (currentTime != 0) { 8269 if (pkgSetting.firstInstallTime == 0) { 8270 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8271 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 8272 pkgSetting.lastUpdateTime = currentTime; 8273 } 8274 } else if (pkgSetting.firstInstallTime == 0) { 8275 // We need *something*. Take time time stamp of the file. 8276 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8277 } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8278 if (scanFileTime != pkgSetting.timeStamp) { 8279 // A package on the system image has changed; consider this 8280 // to be an update. 8281 pkgSetting.lastUpdateTime = scanFileTime; 8282 } 8283 } 8284 8285 // Add the package's KeySets to the global KeySetManagerService 8286 ksms.addScannedPackageLPw(pkg); 8287 8288 int N = pkg.providers.size(); 8289 StringBuilder r = null; 8290 int i; 8291 for (i=0; i<N; i++) { 8292 PackageParser.Provider p = pkg.providers.get(i); 8293 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 8294 p.info.processName, pkg.applicationInfo.uid); 8295 mProviders.addProvider(p); 8296 p.syncable = p.info.isSyncable; 8297 if (p.info.authority != null) { 8298 String names[] = p.info.authority.split(";"); 8299 p.info.authority = null; 8300 for (int j = 0; j < names.length; j++) { 8301 if (j == 1 && p.syncable) { 8302 // We only want the first authority for a provider to possibly be 8303 // syncable, so if we already added this provider using a different 8304 // authority clear the syncable flag. We copy the provider before 8305 // changing it because the mProviders object contains a reference 8306 // to a provider that we don't want to change. 8307 // Only do this for the second authority since the resulting provider 8308 // object can be the same for all future authorities for this provider. 8309 p = new PackageParser.Provider(p); 8310 p.syncable = false; 8311 } 8312 if (!mProvidersByAuthority.containsKey(names[j])) { 8313 mProvidersByAuthority.put(names[j], p); 8314 if (p.info.authority == null) { 8315 p.info.authority = names[j]; 8316 } else { 8317 p.info.authority = p.info.authority + ";" + names[j]; 8318 } 8319 if (DEBUG_PACKAGE_SCANNING) { 8320 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8321 Log.d(TAG, "Registered content provider: " + names[j] 8322 + ", className = " + p.info.name + ", isSyncable = " 8323 + p.info.isSyncable); 8324 } 8325 } else { 8326 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8327 Slog.w(TAG, "Skipping provider name " + names[j] + 8328 " (in package " + pkg.applicationInfo.packageName + 8329 "): name already used by " 8330 + ((other != null && other.getComponentName() != null) 8331 ? other.getComponentName().getPackageName() : "?")); 8332 } 8333 } 8334 } 8335 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8336 if (r == null) { 8337 r = new StringBuilder(256); 8338 } else { 8339 r.append(' '); 8340 } 8341 r.append(p.info.name); 8342 } 8343 } 8344 if (r != null) { 8345 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8346 } 8347 8348 N = pkg.services.size(); 8349 r = null; 8350 for (i=0; i<N; i++) { 8351 PackageParser.Service s = pkg.services.get(i); 8352 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8353 s.info.processName, pkg.applicationInfo.uid); 8354 mServices.addService(s); 8355 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8356 if (r == null) { 8357 r = new StringBuilder(256); 8358 } else { 8359 r.append(' '); 8360 } 8361 r.append(s.info.name); 8362 } 8363 } 8364 if (r != null) { 8365 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8366 } 8367 8368 N = pkg.receivers.size(); 8369 r = null; 8370 for (i=0; i<N; i++) { 8371 PackageParser.Activity a = pkg.receivers.get(i); 8372 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8373 a.info.processName, pkg.applicationInfo.uid); 8374 mReceivers.addActivity(a, "receiver"); 8375 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8376 if (r == null) { 8377 r = new StringBuilder(256); 8378 } else { 8379 r.append(' '); 8380 } 8381 r.append(a.info.name); 8382 } 8383 } 8384 if (r != null) { 8385 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8386 } 8387 8388 N = pkg.activities.size(); 8389 r = null; 8390 for (i=0; i<N; i++) { 8391 PackageParser.Activity a = pkg.activities.get(i); 8392 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8393 a.info.processName, pkg.applicationInfo.uid); 8394 mActivities.addActivity(a, "activity"); 8395 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8396 if (r == null) { 8397 r = new StringBuilder(256); 8398 } else { 8399 r.append(' '); 8400 } 8401 r.append(a.info.name); 8402 } 8403 } 8404 if (r != null) { 8405 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8406 } 8407 8408 N = pkg.permissionGroups.size(); 8409 r = null; 8410 for (i=0; i<N; i++) { 8411 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8412 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8413 if (cur == null) { 8414 mPermissionGroups.put(pg.info.name, pg); 8415 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8416 if (r == null) { 8417 r = new StringBuilder(256); 8418 } else { 8419 r.append(' '); 8420 } 8421 r.append(pg.info.name); 8422 } 8423 } else { 8424 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8425 + pg.info.packageName + " ignored: original from " 8426 + cur.info.packageName); 8427 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8428 if (r == null) { 8429 r = new StringBuilder(256); 8430 } else { 8431 r.append(' '); 8432 } 8433 r.append("DUP:"); 8434 r.append(pg.info.name); 8435 } 8436 } 8437 } 8438 if (r != null) { 8439 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8440 } 8441 8442 N = pkg.permissions.size(); 8443 r = null; 8444 for (i=0; i<N; i++) { 8445 PackageParser.Permission p = pkg.permissions.get(i); 8446 8447 // Assume by default that we did not install this permission into the system. 8448 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8449 8450 // Now that permission groups have a special meaning, we ignore permission 8451 // groups for legacy apps to prevent unexpected behavior. In particular, 8452 // permissions for one app being granted to someone just becase they happen 8453 // to be in a group defined by another app (before this had no implications). 8454 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8455 p.group = mPermissionGroups.get(p.info.group); 8456 // Warn for a permission in an unknown group. 8457 if (p.info.group != null && p.group == null) { 8458 Slog.w(TAG, "Permission " + p.info.name + " from package " 8459 + p.info.packageName + " in an unknown group " + p.info.group); 8460 } 8461 } 8462 8463 ArrayMap<String, BasePermission> permissionMap = 8464 p.tree ? mSettings.mPermissionTrees 8465 : mSettings.mPermissions; 8466 BasePermission bp = permissionMap.get(p.info.name); 8467 8468 // Allow system apps to redefine non-system permissions 8469 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8470 final boolean currentOwnerIsSystem = (bp.perm != null 8471 && isSystemApp(bp.perm.owner)); 8472 if (isSystemApp(p.owner)) { 8473 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8474 // It's a built-in permission and no owner, take ownership now 8475 bp.packageSetting = pkgSetting; 8476 bp.perm = p; 8477 bp.uid = pkg.applicationInfo.uid; 8478 bp.sourcePackage = p.info.packageName; 8479 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8480 } else if (!currentOwnerIsSystem) { 8481 String msg = "New decl " + p.owner + " of permission " 8482 + p.info.name + " is system; overriding " + bp.sourcePackage; 8483 reportSettingsProblem(Log.WARN, msg); 8484 bp = null; 8485 } 8486 } 8487 } 8488 8489 if (bp == null) { 8490 bp = new BasePermission(p.info.name, p.info.packageName, 8491 BasePermission.TYPE_NORMAL); 8492 permissionMap.put(p.info.name, bp); 8493 } 8494 8495 if (bp.perm == null) { 8496 if (bp.sourcePackage == null 8497 || bp.sourcePackage.equals(p.info.packageName)) { 8498 BasePermission tree = findPermissionTreeLP(p.info.name); 8499 if (tree == null 8500 || tree.sourcePackage.equals(p.info.packageName)) { 8501 bp.packageSetting = pkgSetting; 8502 bp.perm = p; 8503 bp.uid = pkg.applicationInfo.uid; 8504 bp.sourcePackage = p.info.packageName; 8505 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8506 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8507 if (r == null) { 8508 r = new StringBuilder(256); 8509 } else { 8510 r.append(' '); 8511 } 8512 r.append(p.info.name); 8513 } 8514 } else { 8515 Slog.w(TAG, "Permission " + p.info.name + " from package " 8516 + p.info.packageName + " ignored: base tree " 8517 + tree.name + " is from package " 8518 + tree.sourcePackage); 8519 } 8520 } else { 8521 Slog.w(TAG, "Permission " + p.info.name + " from package " 8522 + p.info.packageName + " ignored: original from " 8523 + bp.sourcePackage); 8524 } 8525 } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8526 if (r == null) { 8527 r = new StringBuilder(256); 8528 } else { 8529 r.append(' '); 8530 } 8531 r.append("DUP:"); 8532 r.append(p.info.name); 8533 } 8534 if (bp.perm == p) { 8535 bp.protectionLevel = p.info.protectionLevel; 8536 } 8537 } 8538 8539 if (r != null) { 8540 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 8541 } 8542 8543 N = pkg.instrumentation.size(); 8544 r = null; 8545 for (i=0; i<N; i++) { 8546 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8547 a.info.packageName = pkg.applicationInfo.packageName; 8548 a.info.sourceDir = pkg.applicationInfo.sourceDir; 8549 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 8550 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 8551 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 8552 a.info.dataDir = pkg.applicationInfo.dataDir; 8553 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 8554 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 8555 8556 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 8557 // need other information about the application, like the ABI and what not ? 8558 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 8559 mInstrumentation.put(a.getComponentName(), a); 8560 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8561 if (r == null) { 8562 r = new StringBuilder(256); 8563 } else { 8564 r.append(' '); 8565 } 8566 r.append(a.info.name); 8567 } 8568 } 8569 if (r != null) { 8570 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 8571 } 8572 8573 if (pkg.protectedBroadcasts != null) { 8574 N = pkg.protectedBroadcasts.size(); 8575 for (i=0; i<N; i++) { 8576 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 8577 } 8578 } 8579 8580 pkgSetting.setTimeStamp(scanFileTime); 8581 8582 // Create idmap files for pairs of (packages, overlay packages). 8583 // Note: "android", ie framework-res.apk, is handled by native layers. 8584 if (pkg.mOverlayTarget != null) { 8585 // This is an overlay package. 8586 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 8587 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 8588 mOverlays.put(pkg.mOverlayTarget, 8589 new ArrayMap<String, PackageParser.Package>()); 8590 } 8591 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 8592 map.put(pkg.packageName, pkg); 8593 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 8594 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 8595 createIdmapFailed = true; 8596 } 8597 } 8598 } else if (mOverlays.containsKey(pkg.packageName) && 8599 !pkg.packageName.equals("android")) { 8600 // This is a regular package, with one or more known overlay packages. 8601 createIdmapsForPackageLI(pkg); 8602 } 8603 } 8604 8605 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8606 8607 if (createIdmapFailed) { 8608 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8609 "scanPackageLI failed to createIdmap"); 8610 } 8611 return pkg; 8612 } 8613 8614 /** 8615 * Derive the ABI of a non-system package located at {@code scanFile}. This information 8616 * is derived purely on the basis of the contents of {@code scanFile} and 8617 * {@code cpuAbiOverride}. 8618 * 8619 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 8620 */ 8621 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 8622 String cpuAbiOverride, boolean extractLibs) 8623 throws PackageManagerException { 8624 // TODO: We can probably be smarter about this stuff. For installed apps, 8625 // we can calculate this information at install time once and for all. For 8626 // system apps, we can probably assume that this information doesn't change 8627 // after the first boot scan. As things stand, we do lots of unnecessary work. 8628 8629 // Give ourselves some initial paths; we'll come back for another 8630 // pass once we've determined ABI below. 8631 setNativeLibraryPaths(pkg); 8632 8633 // We would never need to extract libs for forward-locked and external packages, 8634 // since the container service will do it for us. We shouldn't attempt to 8635 // extract libs from system app when it was not updated. 8636 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 8637 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 8638 extractLibs = false; 8639 } 8640 8641 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 8642 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 8643 8644 NativeLibraryHelper.Handle handle = null; 8645 try { 8646 handle = NativeLibraryHelper.Handle.create(pkg); 8647 // TODO(multiArch): This can be null for apps that didn't go through the 8648 // usual installation process. We can calculate it again, like we 8649 // do during install time. 8650 // 8651 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 8652 // unnecessary. 8653 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 8654 8655 // Null out the abis so that they can be recalculated. 8656 pkg.applicationInfo.primaryCpuAbi = null; 8657 pkg.applicationInfo.secondaryCpuAbi = null; 8658 if (isMultiArch(pkg.applicationInfo)) { 8659 // Warn if we've set an abiOverride for multi-lib packages.. 8660 // By definition, we need to copy both 32 and 64 bit libraries for 8661 // such packages. 8662 if (pkg.cpuAbiOverride != null 8663 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 8664 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 8665 } 8666 8667 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 8668 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 8669 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 8670 if (extractLibs) { 8671 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8672 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 8673 useIsaSpecificSubdirs); 8674 } else { 8675 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 8676 } 8677 } 8678 8679 maybeThrowExceptionForMultiArchCopy( 8680 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 8681 8682 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 8683 if (extractLibs) { 8684 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8685 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 8686 useIsaSpecificSubdirs); 8687 } else { 8688 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 8689 } 8690 } 8691 8692 maybeThrowExceptionForMultiArchCopy( 8693 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 8694 8695 if (abi64 >= 0) { 8696 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 8697 } 8698 8699 if (abi32 >= 0) { 8700 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 8701 if (abi64 >= 0) { 8702 if (pkg.use32bitAbi) { 8703 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 8704 pkg.applicationInfo.primaryCpuAbi = abi; 8705 } else { 8706 pkg.applicationInfo.secondaryCpuAbi = abi; 8707 } 8708 } else { 8709 pkg.applicationInfo.primaryCpuAbi = abi; 8710 } 8711 } 8712 8713 } else { 8714 String[] abiList = (cpuAbiOverride != null) ? 8715 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 8716 8717 // Enable gross and lame hacks for apps that are built with old 8718 // SDK tools. We must scan their APKs for renderscript bitcode and 8719 // not launch them if it's present. Don't bother checking on devices 8720 // that don't have 64 bit support. 8721 boolean needsRenderScriptOverride = false; 8722 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 8723 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 8724 abiList = Build.SUPPORTED_32_BIT_ABIS; 8725 needsRenderScriptOverride = true; 8726 } 8727 8728 final int copyRet; 8729 if (extractLibs) { 8730 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8731 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 8732 } else { 8733 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 8734 } 8735 8736 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 8737 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 8738 "Error unpackaging native libs for app, errorCode=" + copyRet); 8739 } 8740 8741 if (copyRet >= 0) { 8742 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 8743 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 8744 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 8745 } else if (needsRenderScriptOverride) { 8746 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 8747 } 8748 } 8749 } catch (IOException ioe) { 8750 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 8751 } finally { 8752 IoUtils.closeQuietly(handle); 8753 } 8754 8755 // Now that we've calculated the ABIs and determined if it's an internal app, 8756 // we will go ahead and populate the nativeLibraryPath. 8757 setNativeLibraryPaths(pkg); 8758 } 8759 8760 /** 8761 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 8762 * i.e, so that all packages can be run inside a single process if required. 8763 * 8764 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 8765 * this function will either try and make the ABI for all packages in {@code packagesForUser} 8766 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 8767 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 8768 * updating a package that belongs to a shared user. 8769 * 8770 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 8771 * adds unnecessary complexity. 8772 */ 8773 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 8774 PackageParser.Package scannedPackage, boolean bootComplete) { 8775 String requiredInstructionSet = null; 8776 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 8777 requiredInstructionSet = VMRuntime.getInstructionSet( 8778 scannedPackage.applicationInfo.primaryCpuAbi); 8779 } 8780 8781 PackageSetting requirer = null; 8782 for (PackageSetting ps : packagesForUser) { 8783 // If packagesForUser contains scannedPackage, we skip it. This will happen 8784 // when scannedPackage is an update of an existing package. Without this check, 8785 // we will never be able to change the ABI of any package belonging to a shared 8786 // user, even if it's compatible with other packages. 8787 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8788 if (ps.primaryCpuAbiString == null) { 8789 continue; 8790 } 8791 8792 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 8793 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 8794 // We have a mismatch between instruction sets (say arm vs arm64) warn about 8795 // this but there's not much we can do. 8796 String errorMessage = "Instruction set mismatch, " 8797 + ((requirer == null) ? "[caller]" : requirer) 8798 + " requires " + requiredInstructionSet + " whereas " + ps 8799 + " requires " + instructionSet; 8800 Slog.w(TAG, errorMessage); 8801 } 8802 8803 if (requiredInstructionSet == null) { 8804 requiredInstructionSet = instructionSet; 8805 requirer = ps; 8806 } 8807 } 8808 } 8809 8810 if (requiredInstructionSet != null) { 8811 String adjustedAbi; 8812 if (requirer != null) { 8813 // requirer != null implies that either scannedPackage was null or that scannedPackage 8814 // did not require an ABI, in which case we have to adjust scannedPackage to match 8815 // the ABI of the set (which is the same as requirer's ABI) 8816 adjustedAbi = requirer.primaryCpuAbiString; 8817 if (scannedPackage != null) { 8818 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 8819 } 8820 } else { 8821 // requirer == null implies that we're updating all ABIs in the set to 8822 // match scannedPackage. 8823 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 8824 } 8825 8826 for (PackageSetting ps : packagesForUser) { 8827 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8828 if (ps.primaryCpuAbiString != null) { 8829 continue; 8830 } 8831 8832 ps.primaryCpuAbiString = adjustedAbi; 8833 if (ps.pkg != null && ps.pkg.applicationInfo != null && 8834 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 8835 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 8836 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 8837 + " (requirer=" 8838 + (requirer == null ? "null" : requirer.pkg.packageName) 8839 + ", scannedPackage=" 8840 + (scannedPackage != null ? scannedPackage.packageName : "null") 8841 + ")"); 8842 try { 8843 mInstaller.rmdex(ps.codePathString, 8844 getDexCodeInstructionSet(getPreferredInstructionSet())); 8845 } catch (InstallerException ignored) { 8846 } 8847 } 8848 } 8849 } 8850 } 8851 } 8852 8853 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 8854 synchronized (mPackages) { 8855 mResolverReplaced = true; 8856 // Set up information for custom user intent resolution activity. 8857 mResolveActivity.applicationInfo = pkg.applicationInfo; 8858 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 8859 mResolveActivity.packageName = pkg.applicationInfo.packageName; 8860 mResolveActivity.processName = pkg.applicationInfo.packageName; 8861 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8862 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8863 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8864 mResolveActivity.theme = 0; 8865 mResolveActivity.exported = true; 8866 mResolveActivity.enabled = true; 8867 mResolveInfo.activityInfo = mResolveActivity; 8868 mResolveInfo.priority = 0; 8869 mResolveInfo.preferredOrder = 0; 8870 mResolveInfo.match = 0; 8871 mResolveComponentName = mCustomResolverComponentName; 8872 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 8873 mResolveComponentName); 8874 } 8875 } 8876 8877 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 8878 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 8879 8880 // Set up information for ephemeral installer activity 8881 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 8882 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 8883 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 8884 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 8885 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8886 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8887 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8888 mEphemeralInstallerActivity.theme = 0; 8889 mEphemeralInstallerActivity.exported = true; 8890 mEphemeralInstallerActivity.enabled = true; 8891 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 8892 mEphemeralInstallerInfo.priority = 0; 8893 mEphemeralInstallerInfo.preferredOrder = 0; 8894 mEphemeralInstallerInfo.match = 0; 8895 8896 if (DEBUG_EPHEMERAL) { 8897 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 8898 } 8899 } 8900 8901 private static String calculateBundledApkRoot(final String codePathString) { 8902 final File codePath = new File(codePathString); 8903 final File codeRoot; 8904 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 8905 codeRoot = Environment.getRootDirectory(); 8906 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 8907 codeRoot = Environment.getOemDirectory(); 8908 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 8909 codeRoot = Environment.getVendorDirectory(); 8910 } else { 8911 // Unrecognized code path; take its top real segment as the apk root: 8912 // e.g. /something/app/blah.apk => /something 8913 try { 8914 File f = codePath.getCanonicalFile(); 8915 File parent = f.getParentFile(); // non-null because codePath is a file 8916 File tmp; 8917 while ((tmp = parent.getParentFile()) != null) { 8918 f = parent; 8919 parent = tmp; 8920 } 8921 codeRoot = f; 8922 Slog.w(TAG, "Unrecognized code path " 8923 + codePath + " - using " + codeRoot); 8924 } catch (IOException e) { 8925 // Can't canonicalize the code path -- shenanigans? 8926 Slog.w(TAG, "Can't canonicalize code path " + codePath); 8927 return Environment.getRootDirectory().getPath(); 8928 } 8929 } 8930 return codeRoot.getPath(); 8931 } 8932 8933 /** 8934 * Derive and set the location of native libraries for the given package, 8935 * which varies depending on where and how the package was installed. 8936 */ 8937 private void setNativeLibraryPaths(PackageParser.Package pkg) { 8938 final ApplicationInfo info = pkg.applicationInfo; 8939 final String codePath = pkg.codePath; 8940 final File codeFile = new File(codePath); 8941 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 8942 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 8943 8944 info.nativeLibraryRootDir = null; 8945 info.nativeLibraryRootRequiresIsa = false; 8946 info.nativeLibraryDir = null; 8947 info.secondaryNativeLibraryDir = null; 8948 8949 if (isApkFile(codeFile)) { 8950 // Monolithic install 8951 if (bundledApp) { 8952 // If "/system/lib64/apkname" exists, assume that is the per-package 8953 // native library directory to use; otherwise use "/system/lib/apkname". 8954 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 8955 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 8956 getPrimaryInstructionSet(info)); 8957 8958 // This is a bundled system app so choose the path based on the ABI. 8959 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 8960 // is just the default path. 8961 final String apkName = deriveCodePathName(codePath); 8962 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 8963 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 8964 apkName).getAbsolutePath(); 8965 8966 if (info.secondaryCpuAbi != null) { 8967 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 8968 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 8969 secondaryLibDir, apkName).getAbsolutePath(); 8970 } 8971 } else if (asecApp) { 8972 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 8973 .getAbsolutePath(); 8974 } else { 8975 final String apkName = deriveCodePathName(codePath); 8976 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 8977 .getAbsolutePath(); 8978 } 8979 8980 info.nativeLibraryRootRequiresIsa = false; 8981 info.nativeLibraryDir = info.nativeLibraryRootDir; 8982 } else { 8983 // Cluster install 8984 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 8985 info.nativeLibraryRootRequiresIsa = true; 8986 8987 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 8988 getPrimaryInstructionSet(info)).getAbsolutePath(); 8989 8990 if (info.secondaryCpuAbi != null) { 8991 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 8992 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 8993 } 8994 } 8995 } 8996 8997 /** 8998 * Calculate the abis and roots for a bundled app. These can uniquely 8999 * be determined from the contents of the system partition, i.e whether 9000 * it contains 64 or 32 bit shared libraries etc. We do not validate any 9001 * of this information, and instead assume that the system was built 9002 * sensibly. 9003 */ 9004 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 9005 PackageSetting pkgSetting) { 9006 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 9007 9008 // If "/system/lib64/apkname" exists, assume that is the per-package 9009 // native library directory to use; otherwise use "/system/lib/apkname". 9010 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 9011 setBundledAppAbi(pkg, apkRoot, apkName); 9012 // pkgSetting might be null during rescan following uninstall of updates 9013 // to a bundled app, so accommodate that possibility. The settings in 9014 // that case will be established later from the parsed package. 9015 // 9016 // If the settings aren't null, sync them up with what we've just derived. 9017 // note that apkRoot isn't stored in the package settings. 9018 if (pkgSetting != null) { 9019 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9020 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9021 } 9022 } 9023 9024 /** 9025 * Deduces the ABI of a bundled app and sets the relevant fields on the 9026 * parsed pkg object. 9027 * 9028 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 9029 * under which system libraries are installed. 9030 * @param apkName the name of the installed package. 9031 */ 9032 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 9033 final File codeFile = new File(pkg.codePath); 9034 9035 final boolean has64BitLibs; 9036 final boolean has32BitLibs; 9037 if (isApkFile(codeFile)) { 9038 // Monolithic install 9039 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 9040 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 9041 } else { 9042 // Cluster install 9043 final File rootDir = new File(codeFile, LIB_DIR_NAME); 9044 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 9045 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 9046 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 9047 has64BitLibs = (new File(rootDir, isa)).exists(); 9048 } else { 9049 has64BitLibs = false; 9050 } 9051 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 9052 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 9053 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 9054 has32BitLibs = (new File(rootDir, isa)).exists(); 9055 } else { 9056 has32BitLibs = false; 9057 } 9058 } 9059 9060 if (has64BitLibs && !has32BitLibs) { 9061 // The package has 64 bit libs, but not 32 bit libs. Its primary 9062 // ABI should be 64 bit. We can safely assume here that the bundled 9063 // native libraries correspond to the most preferred ABI in the list. 9064 9065 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9066 pkg.applicationInfo.secondaryCpuAbi = null; 9067 } else if (has32BitLibs && !has64BitLibs) { 9068 // The package has 32 bit libs but not 64 bit libs. Its primary 9069 // ABI should be 32 bit. 9070 9071 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9072 pkg.applicationInfo.secondaryCpuAbi = null; 9073 } else if (has32BitLibs && has64BitLibs) { 9074 // The application has both 64 and 32 bit bundled libraries. We check 9075 // here that the app declares multiArch support, and warn if it doesn't. 9076 // 9077 // We will be lenient here and record both ABIs. The primary will be the 9078 // ABI that's higher on the list, i.e, a device that's configured to prefer 9079 // 64 bit apps will see a 64 bit primary ABI, 9080 9081 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 9082 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 9083 } 9084 9085 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 9086 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9087 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9088 } else { 9089 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9090 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9091 } 9092 } else { 9093 pkg.applicationInfo.primaryCpuAbi = null; 9094 pkg.applicationInfo.secondaryCpuAbi = null; 9095 } 9096 } 9097 9098 private void killApplication(String pkgName, int appId, String reason) { 9099 // Request the ActivityManager to kill the process(only for existing packages) 9100 // so that we do not end up in a confused state while the user is still using the older 9101 // version of the application while the new one gets installed. 9102 final long token = Binder.clearCallingIdentity(); 9103 try { 9104 IActivityManager am = ActivityManagerNative.getDefault(); 9105 if (am != null) { 9106 try { 9107 am.killApplicationWithAppId(pkgName, appId, reason); 9108 } catch (RemoteException e) { 9109 } 9110 } 9111 } finally { 9112 Binder.restoreCallingIdentity(token); 9113 } 9114 } 9115 9116 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 9117 // Remove the parent package setting 9118 PackageSetting ps = (PackageSetting) pkg.mExtras; 9119 if (ps != null) { 9120 removePackageLI(ps, chatty); 9121 } 9122 // Remove the child package setting 9123 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9124 for (int i = 0; i < childCount; i++) { 9125 PackageParser.Package childPkg = pkg.childPackages.get(i); 9126 ps = (PackageSetting) childPkg.mExtras; 9127 if (ps != null) { 9128 removePackageLI(ps, chatty); 9129 } 9130 } 9131 } 9132 9133 void removePackageLI(PackageSetting ps, boolean chatty) { 9134 if (DEBUG_INSTALL) { 9135 if (chatty) 9136 Log.d(TAG, "Removing package " + ps.name); 9137 } 9138 9139 // writer 9140 synchronized (mPackages) { 9141 mPackages.remove(ps.name); 9142 final PackageParser.Package pkg = ps.pkg; 9143 if (pkg != null) { 9144 cleanPackageDataStructuresLILPw(pkg, chatty); 9145 } 9146 } 9147 } 9148 9149 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 9150 if (DEBUG_INSTALL) { 9151 if (chatty) 9152 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 9153 } 9154 9155 // writer 9156 synchronized (mPackages) { 9157 // Remove the parent package 9158 mPackages.remove(pkg.applicationInfo.packageName); 9159 cleanPackageDataStructuresLILPw(pkg, chatty); 9160 9161 // Remove the child packages 9162 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9163 for (int i = 0; i < childCount; i++) { 9164 PackageParser.Package childPkg = pkg.childPackages.get(i); 9165 mPackages.remove(childPkg.applicationInfo.packageName); 9166 cleanPackageDataStructuresLILPw(childPkg, chatty); 9167 } 9168 } 9169 } 9170 9171 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 9172 int N = pkg.providers.size(); 9173 StringBuilder r = null; 9174 int i; 9175 for (i=0; i<N; i++) { 9176 PackageParser.Provider p = pkg.providers.get(i); 9177 mProviders.removeProvider(p); 9178 if (p.info.authority == null) { 9179 9180 /* There was another ContentProvider with this authority when 9181 * this app was installed so this authority is null, 9182 * Ignore it as we don't have to unregister the provider. 9183 */ 9184 continue; 9185 } 9186 String names[] = p.info.authority.split(";"); 9187 for (int j = 0; j < names.length; j++) { 9188 if (mProvidersByAuthority.get(names[j]) == p) { 9189 mProvidersByAuthority.remove(names[j]); 9190 if (DEBUG_REMOVE) { 9191 if (chatty) 9192 Log.d(TAG, "Unregistered content provider: " + names[j] 9193 + ", className = " + p.info.name + ", isSyncable = " 9194 + p.info.isSyncable); 9195 } 9196 } 9197 } 9198 if (DEBUG_REMOVE && chatty) { 9199 if (r == null) { 9200 r = new StringBuilder(256); 9201 } else { 9202 r.append(' '); 9203 } 9204 r.append(p.info.name); 9205 } 9206 } 9207 if (r != null) { 9208 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 9209 } 9210 9211 N = pkg.services.size(); 9212 r = null; 9213 for (i=0; i<N; i++) { 9214 PackageParser.Service s = pkg.services.get(i); 9215 mServices.removeService(s); 9216 if (chatty) { 9217 if (r == null) { 9218 r = new StringBuilder(256); 9219 } else { 9220 r.append(' '); 9221 } 9222 r.append(s.info.name); 9223 } 9224 } 9225 if (r != null) { 9226 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 9227 } 9228 9229 N = pkg.receivers.size(); 9230 r = null; 9231 for (i=0; i<N; i++) { 9232 PackageParser.Activity a = pkg.receivers.get(i); 9233 mReceivers.removeActivity(a, "receiver"); 9234 if (DEBUG_REMOVE && chatty) { 9235 if (r == null) { 9236 r = new StringBuilder(256); 9237 } else { 9238 r.append(' '); 9239 } 9240 r.append(a.info.name); 9241 } 9242 } 9243 if (r != null) { 9244 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 9245 } 9246 9247 N = pkg.activities.size(); 9248 r = null; 9249 for (i=0; i<N; i++) { 9250 PackageParser.Activity a = pkg.activities.get(i); 9251 mActivities.removeActivity(a, "activity"); 9252 if (DEBUG_REMOVE && chatty) { 9253 if (r == null) { 9254 r = new StringBuilder(256); 9255 } else { 9256 r.append(' '); 9257 } 9258 r.append(a.info.name); 9259 } 9260 } 9261 if (r != null) { 9262 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 9263 } 9264 9265 N = pkg.permissions.size(); 9266 r = null; 9267 for (i=0; i<N; i++) { 9268 PackageParser.Permission p = pkg.permissions.get(i); 9269 BasePermission bp = mSettings.mPermissions.get(p.info.name); 9270 if (bp == null) { 9271 bp = mSettings.mPermissionTrees.get(p.info.name); 9272 } 9273 if (bp != null && bp.perm == p) { 9274 bp.perm = null; 9275 if (DEBUG_REMOVE && chatty) { 9276 if (r == null) { 9277 r = new StringBuilder(256); 9278 } else { 9279 r.append(' '); 9280 } 9281 r.append(p.info.name); 9282 } 9283 } 9284 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9285 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 9286 if (appOpPkgs != null) { 9287 appOpPkgs.remove(pkg.packageName); 9288 } 9289 } 9290 } 9291 if (r != null) { 9292 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9293 } 9294 9295 N = pkg.requestedPermissions.size(); 9296 r = null; 9297 for (i=0; i<N; i++) { 9298 String perm = pkg.requestedPermissions.get(i); 9299 BasePermission bp = mSettings.mPermissions.get(perm); 9300 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9301 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 9302 if (appOpPkgs != null) { 9303 appOpPkgs.remove(pkg.packageName); 9304 if (appOpPkgs.isEmpty()) { 9305 mAppOpPermissionPackages.remove(perm); 9306 } 9307 } 9308 } 9309 } 9310 if (r != null) { 9311 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9312 } 9313 9314 N = pkg.instrumentation.size(); 9315 r = null; 9316 for (i=0; i<N; i++) { 9317 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9318 mInstrumentation.remove(a.getComponentName()); 9319 if (DEBUG_REMOVE && chatty) { 9320 if (r == null) { 9321 r = new StringBuilder(256); 9322 } else { 9323 r.append(' '); 9324 } 9325 r.append(a.info.name); 9326 } 9327 } 9328 if (r != null) { 9329 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9330 } 9331 9332 r = null; 9333 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9334 // Only system apps can hold shared libraries. 9335 if (pkg.libraryNames != null) { 9336 for (i=0; i<pkg.libraryNames.size(); i++) { 9337 String name = pkg.libraryNames.get(i); 9338 SharedLibraryEntry cur = mSharedLibraries.get(name); 9339 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9340 mSharedLibraries.remove(name); 9341 if (DEBUG_REMOVE && chatty) { 9342 if (r == null) { 9343 r = new StringBuilder(256); 9344 } else { 9345 r.append(' '); 9346 } 9347 r.append(name); 9348 } 9349 } 9350 } 9351 } 9352 } 9353 if (r != null) { 9354 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9355 } 9356 } 9357 9358 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9359 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9360 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9361 return true; 9362 } 9363 } 9364 return false; 9365 } 9366 9367 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9368 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9369 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9370 9371 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9372 // Update the parent permissions 9373 updatePermissionsLPw(pkg.packageName, pkg, flags); 9374 // Update the child permissions 9375 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9376 for (int i = 0; i < childCount; i++) { 9377 PackageParser.Package childPkg = pkg.childPackages.get(i); 9378 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9379 } 9380 } 9381 9382 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9383 int flags) { 9384 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9385 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9386 } 9387 9388 private void updatePermissionsLPw(String changingPkg, 9389 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9390 // Make sure there are no dangling permission trees. 9391 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9392 while (it.hasNext()) { 9393 final BasePermission bp = it.next(); 9394 if (bp.packageSetting == null) { 9395 // We may not yet have parsed the package, so just see if 9396 // we still know about its settings. 9397 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9398 } 9399 if (bp.packageSetting == null) { 9400 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9401 + " from package " + bp.sourcePackage); 9402 it.remove(); 9403 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9404 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9405 Slog.i(TAG, "Removing old permission tree: " + bp.name 9406 + " from package " + bp.sourcePackage); 9407 flags |= UPDATE_PERMISSIONS_ALL; 9408 it.remove(); 9409 } 9410 } 9411 } 9412 9413 // Make sure all dynamic permissions have been assigned to a package, 9414 // and make sure there are no dangling permissions. 9415 it = mSettings.mPermissions.values().iterator(); 9416 while (it.hasNext()) { 9417 final BasePermission bp = it.next(); 9418 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9419 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9420 + bp.name + " pkg=" + bp.sourcePackage 9421 + " info=" + bp.pendingInfo); 9422 if (bp.packageSetting == null && bp.pendingInfo != null) { 9423 final BasePermission tree = findPermissionTreeLP(bp.name); 9424 if (tree != null && tree.perm != null) { 9425 bp.packageSetting = tree.packageSetting; 9426 bp.perm = new PackageParser.Permission(tree.perm.owner, 9427 new PermissionInfo(bp.pendingInfo)); 9428 bp.perm.info.packageName = tree.perm.info.packageName; 9429 bp.perm.info.name = bp.name; 9430 bp.uid = tree.uid; 9431 } 9432 } 9433 } 9434 if (bp.packageSetting == null) { 9435 // We may not yet have parsed the package, so just see if 9436 // we still know about its settings. 9437 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9438 } 9439 if (bp.packageSetting == null) { 9440 Slog.w(TAG, "Removing dangling permission: " + bp.name 9441 + " from package " + bp.sourcePackage); 9442 it.remove(); 9443 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9444 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9445 Slog.i(TAG, "Removing old permission: " + bp.name 9446 + " from package " + bp.sourcePackage); 9447 flags |= UPDATE_PERMISSIONS_ALL; 9448 it.remove(); 9449 } 9450 } 9451 } 9452 9453 // Now update the permissions for all packages, in particular 9454 // replace the granted permissions of the system packages. 9455 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9456 for (PackageParser.Package pkg : mPackages.values()) { 9457 if (pkg != pkgInfo) { 9458 // Only replace for packages on requested volume 9459 final String volumeUuid = getVolumeUuidForPackage(pkg); 9460 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9461 && Objects.equals(replaceVolumeUuid, volumeUuid); 9462 grantPermissionsLPw(pkg, replace, changingPkg); 9463 } 9464 } 9465 } 9466 9467 if (pkgInfo != null) { 9468 // Only replace for packages on requested volume 9469 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9470 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9471 && Objects.equals(replaceVolumeUuid, volumeUuid); 9472 grantPermissionsLPw(pkgInfo, replace, changingPkg); 9473 } 9474 } 9475 9476 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 9477 String packageOfInterest) { 9478 // IMPORTANT: There are two types of permissions: install and runtime. 9479 // Install time permissions are granted when the app is installed to 9480 // all device users and users added in the future. Runtime permissions 9481 // are granted at runtime explicitly to specific users. Normal and signature 9482 // protected permissions are install time permissions. Dangerous permissions 9483 // are install permissions if the app's target SDK is Lollipop MR1 or older, 9484 // otherwise they are runtime permissions. This function does not manage 9485 // runtime permissions except for the case an app targeting Lollipop MR1 9486 // being upgraded to target a newer SDK, in which case dangerous permissions 9487 // are transformed from install time to runtime ones. 9488 9489 final PackageSetting ps = (PackageSetting) pkg.mExtras; 9490 if (ps == null) { 9491 return; 9492 } 9493 9494 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 9495 9496 PermissionsState permissionsState = ps.getPermissionsState(); 9497 PermissionsState origPermissions = permissionsState; 9498 9499 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 9500 9501 boolean runtimePermissionsRevoked = false; 9502 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 9503 9504 boolean changedInstallPermission = false; 9505 9506 if (replace) { 9507 ps.installPermissionsFixed = false; 9508 if (!ps.isSharedUser()) { 9509 origPermissions = new PermissionsState(permissionsState); 9510 permissionsState.reset(); 9511 } else { 9512 // We need to know only about runtime permission changes since the 9513 // calling code always writes the install permissions state but 9514 // the runtime ones are written only if changed. The only cases of 9515 // changed runtime permissions here are promotion of an install to 9516 // runtime and revocation of a runtime from a shared user. 9517 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 9518 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 9519 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 9520 runtimePermissionsRevoked = true; 9521 } 9522 } 9523 } 9524 9525 permissionsState.setGlobalGids(mGlobalGids); 9526 9527 final int N = pkg.requestedPermissions.size(); 9528 for (int i=0; i<N; i++) { 9529 final String name = pkg.requestedPermissions.get(i); 9530 final BasePermission bp = mSettings.mPermissions.get(name); 9531 9532 if (DEBUG_INSTALL) { 9533 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 9534 } 9535 9536 if (bp == null || bp.packageSetting == null) { 9537 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9538 Slog.w(TAG, "Unknown permission " + name 9539 + " in package " + pkg.packageName); 9540 } 9541 continue; 9542 } 9543 9544 final String perm = bp.name; 9545 boolean allowedSig = false; 9546 int grant = GRANT_DENIED; 9547 9548 // Keep track of app op permissions. 9549 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9550 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 9551 if (pkgs == null) { 9552 pkgs = new ArraySet<>(); 9553 mAppOpPermissionPackages.put(bp.name, pkgs); 9554 } 9555 pkgs.add(pkg.packageName); 9556 } 9557 9558 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 9559 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 9560 >= Build.VERSION_CODES.M; 9561 switch (level) { 9562 case PermissionInfo.PROTECTION_NORMAL: { 9563 // For all apps normal permissions are install time ones. 9564 grant = GRANT_INSTALL; 9565 } break; 9566 9567 case PermissionInfo.PROTECTION_DANGEROUS: { 9568 // If a permission review is required for legacy apps we represent 9569 // their permissions as always granted runtime ones since we need 9570 // to keep the review required permission flag per user while an 9571 // install permission's state is shared across all users. 9572 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 9573 // For legacy apps dangerous permissions are install time ones. 9574 grant = GRANT_INSTALL; 9575 } else if (origPermissions.hasInstallPermission(bp.name)) { 9576 // For legacy apps that became modern, install becomes runtime. 9577 grant = GRANT_UPGRADE; 9578 } else if (mPromoteSystemApps 9579 && isSystemApp(ps) 9580 && mExistingSystemPackages.contains(ps.name)) { 9581 // For legacy system apps, install becomes runtime. 9582 // We cannot check hasInstallPermission() for system apps since those 9583 // permissions were granted implicitly and not persisted pre-M. 9584 grant = GRANT_UPGRADE; 9585 } else { 9586 // For modern apps keep runtime permissions unchanged. 9587 grant = GRANT_RUNTIME; 9588 } 9589 } break; 9590 9591 case PermissionInfo.PROTECTION_SIGNATURE: { 9592 // For all apps signature permissions are install time ones. 9593 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 9594 if (allowedSig) { 9595 grant = GRANT_INSTALL; 9596 } 9597 } break; 9598 } 9599 9600 if (DEBUG_INSTALL) { 9601 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 9602 } 9603 9604 if (grant != GRANT_DENIED) { 9605 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 9606 // If this is an existing, non-system package, then 9607 // we can't add any new permissions to it. 9608 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 9609 // Except... if this is a permission that was added 9610 // to the platform (note: need to only do this when 9611 // updating the platform). 9612 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 9613 grant = GRANT_DENIED; 9614 } 9615 } 9616 } 9617 9618 switch (grant) { 9619 case GRANT_INSTALL: { 9620 // Revoke this as runtime permission to handle the case of 9621 // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps 9622 for (int userId : UserManagerService.getInstance().getUserIds()) { 9623 if (origPermissions.getRuntimePermissionState( 9624 bp.name, userId) != null) { 9625 // Revoke the runtime permission and clear the flags. 9626 origPermissions.revokeRuntimePermission(bp, userId); 9627 origPermissions.updatePermissionFlags(bp, userId, 9628 PackageManager.MASK_PERMISSION_FLAGS, 0); 9629 // If we revoked a permission permission, we have to write. 9630 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9631 changedRuntimePermissionUserIds, userId); 9632 } 9633 } 9634 // Grant an install permission. 9635 if (permissionsState.grantInstallPermission(bp) != 9636 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9637 changedInstallPermission = true; 9638 } 9639 } break; 9640 9641 case GRANT_RUNTIME: { 9642 // Grant previously granted runtime permissions. 9643 for (int userId : UserManagerService.getInstance().getUserIds()) { 9644 PermissionState permissionState = origPermissions 9645 .getRuntimePermissionState(bp.name, userId); 9646 int flags = permissionState != null 9647 ? permissionState.getFlags() : 0; 9648 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 9649 if (permissionsState.grantRuntimePermission(bp, userId) == 9650 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9651 // If we cannot put the permission as it was, we have to write. 9652 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9653 changedRuntimePermissionUserIds, userId); 9654 } 9655 // If the app supports runtime permissions no need for a review. 9656 if (Build.PERMISSIONS_REVIEW_REQUIRED 9657 && appSupportsRuntimePermissions 9658 && (flags & PackageManager 9659 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 9660 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 9661 // Since we changed the flags, we have to write. 9662 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9663 changedRuntimePermissionUserIds, userId); 9664 } 9665 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 9666 && !appSupportsRuntimePermissions) { 9667 // For legacy apps that need a permission review, every new 9668 // runtime permission is granted but it is pending a review. 9669 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 9670 permissionsState.grantRuntimePermission(bp, userId); 9671 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 9672 // We changed the permission and flags, hence have to write. 9673 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9674 changedRuntimePermissionUserIds, userId); 9675 } 9676 } 9677 // Propagate the permission flags. 9678 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 9679 } 9680 } break; 9681 9682 case GRANT_UPGRADE: { 9683 // Grant runtime permissions for a previously held install permission. 9684 PermissionState permissionState = origPermissions 9685 .getInstallPermissionState(bp.name); 9686 final int flags = permissionState != null ? permissionState.getFlags() : 0; 9687 9688 if (origPermissions.revokeInstallPermission(bp) 9689 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 9690 // We will be transferring the permission flags, so clear them. 9691 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 9692 PackageManager.MASK_PERMISSION_FLAGS, 0); 9693 changedInstallPermission = true; 9694 } 9695 9696 // If the permission is not to be promoted to runtime we ignore it and 9697 // also its other flags as they are not applicable to install permissions. 9698 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 9699 for (int userId : currentUserIds) { 9700 if (permissionsState.grantRuntimePermission(bp, userId) != 9701 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9702 // Transfer the permission flags. 9703 permissionsState.updatePermissionFlags(bp, userId, 9704 flags, flags); 9705 // If we granted the permission, we have to write. 9706 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9707 changedRuntimePermissionUserIds, userId); 9708 } 9709 } 9710 } 9711 } break; 9712 9713 default: { 9714 if (packageOfInterest == null 9715 || packageOfInterest.equals(pkg.packageName)) { 9716 Slog.w(TAG, "Not granting permission " + perm 9717 + " to package " + pkg.packageName 9718 + " because it was previously installed without"); 9719 } 9720 } break; 9721 } 9722 } else { 9723 if (permissionsState.revokeInstallPermission(bp) != 9724 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9725 // Also drop the permission flags. 9726 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 9727 PackageManager.MASK_PERMISSION_FLAGS, 0); 9728 changedInstallPermission = true; 9729 Slog.i(TAG, "Un-granting permission " + perm 9730 + " from package " + pkg.packageName 9731 + " (protectionLevel=" + bp.protectionLevel 9732 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9733 + ")"); 9734 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 9735 // Don't print warning for app op permissions, since it is fine for them 9736 // not to be granted, there is a UI for the user to decide. 9737 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9738 Slog.w(TAG, "Not granting permission " + perm 9739 + " to package " + pkg.packageName 9740 + " (protectionLevel=" + bp.protectionLevel 9741 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9742 + ")"); 9743 } 9744 } 9745 } 9746 } 9747 9748 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 9749 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 9750 // This is the first that we have heard about this package, so the 9751 // permissions we have now selected are fixed until explicitly 9752 // changed. 9753 ps.installPermissionsFixed = true; 9754 } 9755 9756 // Persist the runtime permissions state for users with changes. If permissions 9757 // were revoked because no app in the shared user declares them we have to 9758 // write synchronously to avoid losing runtime permissions state. 9759 for (int userId : changedRuntimePermissionUserIds) { 9760 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 9761 } 9762 9763 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9764 } 9765 9766 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 9767 boolean allowed = false; 9768 final int NP = PackageParser.NEW_PERMISSIONS.length; 9769 for (int ip=0; ip<NP; ip++) { 9770 final PackageParser.NewPermissionInfo npi 9771 = PackageParser.NEW_PERMISSIONS[ip]; 9772 if (npi.name.equals(perm) 9773 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 9774 allowed = true; 9775 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 9776 + pkg.packageName); 9777 break; 9778 } 9779 } 9780 return allowed; 9781 } 9782 9783 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 9784 BasePermission bp, PermissionsState origPermissions) { 9785 boolean allowed; 9786 allowed = (compareSignatures( 9787 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 9788 == PackageManager.SIGNATURE_MATCH) 9789 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 9790 == PackageManager.SIGNATURE_MATCH); 9791 if (!allowed && (bp.protectionLevel 9792 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 9793 if (isSystemApp(pkg)) { 9794 // For updated system applications, a system permission 9795 // is granted only if it had been defined by the original application. 9796 if (pkg.isUpdatedSystemApp()) { 9797 final PackageSetting sysPs = mSettings 9798 .getDisabledSystemPkgLPr(pkg.packageName); 9799 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 9800 // If the original was granted this permission, we take 9801 // that grant decision as read and propagate it to the 9802 // update. 9803 if (sysPs.isPrivileged()) { 9804 allowed = true; 9805 } 9806 } else { 9807 // The system apk may have been updated with an older 9808 // version of the one on the data partition, but which 9809 // granted a new system permission that it didn't have 9810 // before. In this case we do want to allow the app to 9811 // now get the new permission if the ancestral apk is 9812 // privileged to get it. 9813 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 9814 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 9815 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 9816 allowed = true; 9817 break; 9818 } 9819 } 9820 } 9821 // Also if a privileged parent package on the system image or any of 9822 // its children requested a privileged permission, the updated child 9823 // packages can also get the permission. 9824 if (pkg.parentPackage != null) { 9825 final PackageSetting disabledSysParentPs = mSettings 9826 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 9827 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 9828 && disabledSysParentPs.isPrivileged()) { 9829 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 9830 allowed = true; 9831 } else if (disabledSysParentPs.pkg.childPackages != null) { 9832 final int count = disabledSysParentPs.pkg.childPackages.size(); 9833 for (int i = 0; i < count; i++) { 9834 PackageParser.Package disabledSysChildPkg = 9835 disabledSysParentPs.pkg.childPackages.get(i); 9836 if (isPackageRequestingPermission(disabledSysChildPkg, 9837 perm)) { 9838 allowed = true; 9839 break; 9840 } 9841 } 9842 } 9843 } 9844 } 9845 } 9846 } else { 9847 allowed = isPrivilegedApp(pkg); 9848 } 9849 } 9850 } 9851 if (!allowed) { 9852 if (!allowed && (bp.protectionLevel 9853 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 9854 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 9855 // If this was a previously normal/dangerous permission that got moved 9856 // to a system permission as part of the runtime permission redesign, then 9857 // we still want to blindly grant it to old apps. 9858 allowed = true; 9859 } 9860 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 9861 && pkg.packageName.equals(mRequiredInstallerPackage)) { 9862 // If this permission is to be granted to the system installer and 9863 // this app is an installer, then it gets the permission. 9864 allowed = true; 9865 } 9866 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 9867 && pkg.packageName.equals(mRequiredVerifierPackage)) { 9868 // If this permission is to be granted to the system verifier and 9869 // this app is a verifier, then it gets the permission. 9870 allowed = true; 9871 } 9872 if (!allowed && (bp.protectionLevel 9873 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 9874 && isSystemApp(pkg)) { 9875 // Any pre-installed system app is allowed to get this permission. 9876 allowed = true; 9877 } 9878 if (!allowed && (bp.protectionLevel 9879 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 9880 // For development permissions, a development permission 9881 // is granted only if it was already granted. 9882 allowed = origPermissions.hasInstallPermission(perm); 9883 } 9884 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 9885 && pkg.packageName.equals(mSetupWizardPackage)) { 9886 // If this permission is to be granted to the system setup wizard and 9887 // this app is a setup wizard, then it gets the permission. 9888 allowed = true; 9889 } 9890 } 9891 return allowed; 9892 } 9893 9894 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 9895 final int permCount = pkg.requestedPermissions.size(); 9896 for (int j = 0; j < permCount; j++) { 9897 String requestedPermission = pkg.requestedPermissions.get(j); 9898 if (permission.equals(requestedPermission)) { 9899 return true; 9900 } 9901 } 9902 return false; 9903 } 9904 9905 final class ActivityIntentResolver 9906 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 9907 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9908 boolean defaultOnly, int userId) { 9909 if (!sUserManager.exists(userId)) return null; 9910 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9911 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9912 } 9913 9914 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9915 int userId) { 9916 if (!sUserManager.exists(userId)) return null; 9917 mFlags = flags; 9918 return super.queryIntent(intent, resolvedType, 9919 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9920 } 9921 9922 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9923 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 9924 if (!sUserManager.exists(userId)) return null; 9925 if (packageActivities == null) { 9926 return null; 9927 } 9928 mFlags = flags; 9929 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9930 final int N = packageActivities.size(); 9931 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 9932 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 9933 9934 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 9935 for (int i = 0; i < N; ++i) { 9936 intentFilters = packageActivities.get(i).intents; 9937 if (intentFilters != null && intentFilters.size() > 0) { 9938 PackageParser.ActivityIntentInfo[] array = 9939 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 9940 intentFilters.toArray(array); 9941 listCut.add(array); 9942 } 9943 } 9944 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9945 } 9946 9947 /** 9948 * Finds a privileged activity that matches the specified activity names. 9949 */ 9950 private PackageParser.Activity findMatchingActivity( 9951 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 9952 for (PackageParser.Activity sysActivity : activityList) { 9953 if (sysActivity.info.name.equals(activityInfo.name)) { 9954 return sysActivity; 9955 } 9956 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 9957 return sysActivity; 9958 } 9959 if (sysActivity.info.targetActivity != null) { 9960 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 9961 return sysActivity; 9962 } 9963 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 9964 return sysActivity; 9965 } 9966 } 9967 } 9968 return null; 9969 } 9970 9971 public class IterGenerator<E> { 9972 public Iterator<E> generate(ActivityIntentInfo info) { 9973 return null; 9974 } 9975 } 9976 9977 public class ActionIterGenerator extends IterGenerator<String> { 9978 @Override 9979 public Iterator<String> generate(ActivityIntentInfo info) { 9980 return info.actionsIterator(); 9981 } 9982 } 9983 9984 public class CategoriesIterGenerator extends IterGenerator<String> { 9985 @Override 9986 public Iterator<String> generate(ActivityIntentInfo info) { 9987 return info.categoriesIterator(); 9988 } 9989 } 9990 9991 public class SchemesIterGenerator extends IterGenerator<String> { 9992 @Override 9993 public Iterator<String> generate(ActivityIntentInfo info) { 9994 return info.schemesIterator(); 9995 } 9996 } 9997 9998 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 9999 @Override 10000 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 10001 return info.authoritiesIterator(); 10002 } 10003 } 10004 10005 /** 10006 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 10007 * MODIFIED. Do not pass in a list that should not be changed. 10008 */ 10009 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 10010 IterGenerator<T> generator, Iterator<T> searchIterator) { 10011 // loop through the set of actions; every one must be found in the intent filter 10012 while (searchIterator.hasNext()) { 10013 // we must have at least one filter in the list to consider a match 10014 if (intentList.size() == 0) { 10015 break; 10016 } 10017 10018 final T searchAction = searchIterator.next(); 10019 10020 // loop through the set of intent filters 10021 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 10022 while (intentIter.hasNext()) { 10023 final ActivityIntentInfo intentInfo = intentIter.next(); 10024 boolean selectionFound = false; 10025 10026 // loop through the intent filter's selection criteria; at least one 10027 // of them must match the searched criteria 10028 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 10029 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 10030 final T intentSelection = intentSelectionIter.next(); 10031 if (intentSelection != null && intentSelection.equals(searchAction)) { 10032 selectionFound = true; 10033 break; 10034 } 10035 } 10036 10037 // the selection criteria wasn't found in this filter's set; this filter 10038 // is not a potential match 10039 if (!selectionFound) { 10040 intentIter.remove(); 10041 } 10042 } 10043 } 10044 } 10045 10046 private boolean isProtectedAction(ActivityIntentInfo filter) { 10047 final Iterator<String> actionsIter = filter.actionsIterator(); 10048 while (actionsIter != null && actionsIter.hasNext()) { 10049 final String filterAction = actionsIter.next(); 10050 if (PROTECTED_ACTIONS.contains(filterAction)) { 10051 return true; 10052 } 10053 } 10054 return false; 10055 } 10056 10057 /** 10058 * Adjusts the priority of the given intent filter according to policy. 10059 * <p> 10060 * <ul> 10061 * <li>The priority for non privileged applications is capped to '0'</li> 10062 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 10063 * <li>The priority for unbundled updates to privileged applications is capped to the 10064 * priority defined on the system partition</li> 10065 * </ul> 10066 * <p> 10067 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 10068 * allowed to obtain any priority on any action. 10069 */ 10070 private void adjustPriority( 10071 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 10072 // nothing to do; priority is fine as-is 10073 if (intent.getPriority() <= 0) { 10074 return; 10075 } 10076 10077 final ActivityInfo activityInfo = intent.activity.info; 10078 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 10079 10080 final boolean privilegedApp = 10081 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 10082 if (!privilegedApp) { 10083 // non-privileged applications can never define a priority >0 10084 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 10085 + " package: " + applicationInfo.packageName 10086 + " activity: " + intent.activity.className 10087 + " origPrio: " + intent.getPriority()); 10088 intent.setPriority(0); 10089 return; 10090 } 10091 10092 if (systemActivities == null) { 10093 // the system package is not disabled; we're parsing the system partition 10094 if (isProtectedAction(intent)) { 10095 if (mDeferProtectedFilters) { 10096 // We can't deal with these just yet. No component should ever obtain a 10097 // >0 priority for a protected actions, with ONE exception -- the setup 10098 // wizard. The setup wizard, however, cannot be known until we're able to 10099 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 10100 // until all intent filters have been processed. Chicken, meet egg. 10101 // Let the filter temporarily have a high priority and rectify the 10102 // priorities after all system packages have been scanned. 10103 mProtectedFilters.add(intent); 10104 if (DEBUG_FILTERS) { 10105 Slog.i(TAG, "Protected action; save for later;" 10106 + " package: " + applicationInfo.packageName 10107 + " activity: " + intent.activity.className 10108 + " origPrio: " + intent.getPriority()); 10109 } 10110 return; 10111 } else { 10112 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 10113 Slog.i(TAG, "No setup wizard;" 10114 + " All protected intents capped to priority 0"); 10115 } 10116 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 10117 if (DEBUG_FILTERS) { 10118 Slog.i(TAG, "Found setup wizard;" 10119 + " allow priority " + intent.getPriority() + ";" 10120 + " package: " + intent.activity.info.packageName 10121 + " activity: " + intent.activity.className 10122 + " priority: " + intent.getPriority()); 10123 } 10124 // setup wizard gets whatever it wants 10125 return; 10126 } 10127 Slog.w(TAG, "Protected action; cap priority to 0;" 10128 + " package: " + intent.activity.info.packageName 10129 + " activity: " + intent.activity.className 10130 + " origPrio: " + intent.getPriority()); 10131 intent.setPriority(0); 10132 return; 10133 } 10134 } 10135 // privileged apps on the system image get whatever priority they request 10136 return; 10137 } 10138 10139 // privileged app unbundled update ... try to find the same activity 10140 final PackageParser.Activity foundActivity = 10141 findMatchingActivity(systemActivities, activityInfo); 10142 if (foundActivity == null) { 10143 // this is a new activity; it cannot obtain >0 priority 10144 if (DEBUG_FILTERS) { 10145 Slog.i(TAG, "New activity; cap priority to 0;" 10146 + " package: " + applicationInfo.packageName 10147 + " activity: " + intent.activity.className 10148 + " origPrio: " + intent.getPriority()); 10149 } 10150 intent.setPriority(0); 10151 return; 10152 } 10153 10154 // found activity, now check for filter equivalence 10155 10156 // a shallow copy is enough; we modify the list, not its contents 10157 final List<ActivityIntentInfo> intentListCopy = 10158 new ArrayList<>(foundActivity.intents); 10159 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 10160 10161 // find matching action subsets 10162 final Iterator<String> actionsIterator = intent.actionsIterator(); 10163 if (actionsIterator != null) { 10164 getIntentListSubset( 10165 intentListCopy, new ActionIterGenerator(), actionsIterator); 10166 if (intentListCopy.size() == 0) { 10167 // no more intents to match; we're not equivalent 10168 if (DEBUG_FILTERS) { 10169 Slog.i(TAG, "Mismatched action; cap priority to 0;" 10170 + " package: " + applicationInfo.packageName 10171 + " activity: " + intent.activity.className 10172 + " origPrio: " + intent.getPriority()); 10173 } 10174 intent.setPriority(0); 10175 return; 10176 } 10177 } 10178 10179 // find matching category subsets 10180 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 10181 if (categoriesIterator != null) { 10182 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 10183 categoriesIterator); 10184 if (intentListCopy.size() == 0) { 10185 // no more intents to match; we're not equivalent 10186 if (DEBUG_FILTERS) { 10187 Slog.i(TAG, "Mismatched category; cap priority to 0;" 10188 + " package: " + applicationInfo.packageName 10189 + " activity: " + intent.activity.className 10190 + " origPrio: " + intent.getPriority()); 10191 } 10192 intent.setPriority(0); 10193 return; 10194 } 10195 } 10196 10197 // find matching schemes subsets 10198 final Iterator<String> schemesIterator = intent.schemesIterator(); 10199 if (schemesIterator != null) { 10200 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 10201 schemesIterator); 10202 if (intentListCopy.size() == 0) { 10203 // no more intents to match; we're not equivalent 10204 if (DEBUG_FILTERS) { 10205 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 10206 + " package: " + applicationInfo.packageName 10207 + " activity: " + intent.activity.className 10208 + " origPrio: " + intent.getPriority()); 10209 } 10210 intent.setPriority(0); 10211 return; 10212 } 10213 } 10214 10215 // find matching authorities subsets 10216 final Iterator<IntentFilter.AuthorityEntry> 10217 authoritiesIterator = intent.authoritiesIterator(); 10218 if (authoritiesIterator != null) { 10219 getIntentListSubset(intentListCopy, 10220 new AuthoritiesIterGenerator(), 10221 authoritiesIterator); 10222 if (intentListCopy.size() == 0) { 10223 // no more intents to match; we're not equivalent 10224 if (DEBUG_FILTERS) { 10225 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 10226 + " package: " + applicationInfo.packageName 10227 + " activity: " + intent.activity.className 10228 + " origPrio: " + intent.getPriority()); 10229 } 10230 intent.setPriority(0); 10231 return; 10232 } 10233 } 10234 10235 // we found matching filter(s); app gets the max priority of all intents 10236 int cappedPriority = 0; 10237 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 10238 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 10239 } 10240 if (intent.getPriority() > cappedPriority) { 10241 if (DEBUG_FILTERS) { 10242 Slog.i(TAG, "Found matching filter(s);" 10243 + " cap priority to " + cappedPriority + ";" 10244 + " package: " + applicationInfo.packageName 10245 + " activity: " + intent.activity.className 10246 + " origPrio: " + intent.getPriority()); 10247 } 10248 intent.setPriority(cappedPriority); 10249 return; 10250 } 10251 // all this for nothing; the requested priority was <= what was on the system 10252 } 10253 10254 public final void addActivity(PackageParser.Activity a, String type) { 10255 mActivities.put(a.getComponentName(), a); 10256 if (DEBUG_SHOW_INFO) 10257 Log.v( 10258 TAG, " " + type + " " + 10259 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 10260 if (DEBUG_SHOW_INFO) 10261 Log.v(TAG, " Class=" + a.info.name); 10262 final int NI = a.intents.size(); 10263 for (int j=0; j<NI; j++) { 10264 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10265 if ("activity".equals(type)) { 10266 final PackageSetting ps = 10267 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 10268 final List<PackageParser.Activity> systemActivities = 10269 ps != null && ps.pkg != null ? ps.pkg.activities : null; 10270 adjustPriority(systemActivities, intent); 10271 } 10272 if (DEBUG_SHOW_INFO) { 10273 Log.v(TAG, " IntentFilter:"); 10274 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10275 } 10276 if (!intent.debugCheck()) { 10277 Log.w(TAG, "==> For Activity " + a.info.name); 10278 } 10279 addFilter(intent); 10280 } 10281 } 10282 10283 public final void removeActivity(PackageParser.Activity a, String type) { 10284 mActivities.remove(a.getComponentName()); 10285 if (DEBUG_SHOW_INFO) { 10286 Log.v(TAG, " " + type + " " 10287 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 10288 : a.info.name) + ":"); 10289 Log.v(TAG, " Class=" + a.info.name); 10290 } 10291 final int NI = a.intents.size(); 10292 for (int j=0; j<NI; j++) { 10293 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10294 if (DEBUG_SHOW_INFO) { 10295 Log.v(TAG, " IntentFilter:"); 10296 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10297 } 10298 removeFilter(intent); 10299 } 10300 } 10301 10302 @Override 10303 protected boolean allowFilterResult( 10304 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 10305 ActivityInfo filterAi = filter.activity.info; 10306 for (int i=dest.size()-1; i>=0; i--) { 10307 ActivityInfo destAi = dest.get(i).activityInfo; 10308 if (destAi.name == filterAi.name 10309 && destAi.packageName == filterAi.packageName) { 10310 return false; 10311 } 10312 } 10313 return true; 10314 } 10315 10316 @Override 10317 protected ActivityIntentInfo[] newArray(int size) { 10318 return new ActivityIntentInfo[size]; 10319 } 10320 10321 @Override 10322 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 10323 if (!sUserManager.exists(userId)) return true; 10324 PackageParser.Package p = filter.activity.owner; 10325 if (p != null) { 10326 PackageSetting ps = (PackageSetting)p.mExtras; 10327 if (ps != null) { 10328 // System apps are never considered stopped for purposes of 10329 // filtering, because there may be no way for the user to 10330 // actually re-launch them. 10331 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 10332 && ps.getStopped(userId); 10333 } 10334 } 10335 return false; 10336 } 10337 10338 @Override 10339 protected boolean isPackageForFilter(String packageName, 10340 PackageParser.ActivityIntentInfo info) { 10341 return packageName.equals(info.activity.owner.packageName); 10342 } 10343 10344 @Override 10345 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 10346 int match, int userId) { 10347 if (!sUserManager.exists(userId)) return null; 10348 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 10349 return null; 10350 } 10351 final PackageParser.Activity activity = info.activity; 10352 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 10353 if (ps == null) { 10354 return null; 10355 } 10356 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 10357 ps.readUserState(userId), userId); 10358 if (ai == null) { 10359 return null; 10360 } 10361 final ResolveInfo res = new ResolveInfo(); 10362 res.activityInfo = ai; 10363 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10364 res.filter = info; 10365 } 10366 if (info != null) { 10367 res.handleAllWebDataURI = info.handleAllWebDataURI(); 10368 } 10369 res.priority = info.getPriority(); 10370 res.preferredOrder = activity.owner.mPreferredOrder; 10371 //System.out.println("Result: " + res.activityInfo.className + 10372 // " = " + res.priority); 10373 res.match = match; 10374 res.isDefault = info.hasDefault; 10375 res.labelRes = info.labelRes; 10376 res.nonLocalizedLabel = info.nonLocalizedLabel; 10377 if (userNeedsBadging(userId)) { 10378 res.noResourceId = true; 10379 } else { 10380 res.icon = info.icon; 10381 } 10382 res.iconResourceId = info.icon; 10383 res.system = res.activityInfo.applicationInfo.isSystemApp(); 10384 return res; 10385 } 10386 10387 @Override 10388 protected void sortResults(List<ResolveInfo> results) { 10389 Collections.sort(results, mResolvePrioritySorter); 10390 } 10391 10392 @Override 10393 protected void dumpFilter(PrintWriter out, String prefix, 10394 PackageParser.ActivityIntentInfo filter) { 10395 out.print(prefix); out.print( 10396 Integer.toHexString(System.identityHashCode(filter.activity))); 10397 out.print(' '); 10398 filter.activity.printComponentShortName(out); 10399 out.print(" filter "); 10400 out.println(Integer.toHexString(System.identityHashCode(filter))); 10401 } 10402 10403 @Override 10404 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 10405 return filter.activity; 10406 } 10407 10408 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10409 PackageParser.Activity activity = (PackageParser.Activity)label; 10410 out.print(prefix); out.print( 10411 Integer.toHexString(System.identityHashCode(activity))); 10412 out.print(' '); 10413 activity.printComponentShortName(out); 10414 if (count > 1) { 10415 out.print(" ("); out.print(count); out.print(" filters)"); 10416 } 10417 out.println(); 10418 } 10419 10420 // Keys are String (activity class name), values are Activity. 10421 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 10422 = new ArrayMap<ComponentName, PackageParser.Activity>(); 10423 private int mFlags; 10424 } 10425 10426 private final class ServiceIntentResolver 10427 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 10428 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10429 boolean defaultOnly, int userId) { 10430 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10431 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10432 } 10433 10434 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10435 int userId) { 10436 if (!sUserManager.exists(userId)) return null; 10437 mFlags = flags; 10438 return super.queryIntent(intent, resolvedType, 10439 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10440 } 10441 10442 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10443 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 10444 if (!sUserManager.exists(userId)) return null; 10445 if (packageServices == null) { 10446 return null; 10447 } 10448 mFlags = flags; 10449 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10450 final int N = packageServices.size(); 10451 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 10452 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 10453 10454 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 10455 for (int i = 0; i < N; ++i) { 10456 intentFilters = packageServices.get(i).intents; 10457 if (intentFilters != null && intentFilters.size() > 0) { 10458 PackageParser.ServiceIntentInfo[] array = 10459 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 10460 intentFilters.toArray(array); 10461 listCut.add(array); 10462 } 10463 } 10464 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10465 } 10466 10467 public final void addService(PackageParser.Service s) { 10468 mServices.put(s.getComponentName(), s); 10469 if (DEBUG_SHOW_INFO) { 10470 Log.v(TAG, " " 10471 + (s.info.nonLocalizedLabel != null 10472 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10473 Log.v(TAG, " Class=" + s.info.name); 10474 } 10475 final int NI = s.intents.size(); 10476 int j; 10477 for (j=0; j<NI; j++) { 10478 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10479 if (DEBUG_SHOW_INFO) { 10480 Log.v(TAG, " IntentFilter:"); 10481 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10482 } 10483 if (!intent.debugCheck()) { 10484 Log.w(TAG, "==> For Service " + s.info.name); 10485 } 10486 addFilter(intent); 10487 } 10488 } 10489 10490 public final void removeService(PackageParser.Service s) { 10491 mServices.remove(s.getComponentName()); 10492 if (DEBUG_SHOW_INFO) { 10493 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 10494 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10495 Log.v(TAG, " Class=" + s.info.name); 10496 } 10497 final int NI = s.intents.size(); 10498 int j; 10499 for (j=0; j<NI; j++) { 10500 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10501 if (DEBUG_SHOW_INFO) { 10502 Log.v(TAG, " IntentFilter:"); 10503 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10504 } 10505 removeFilter(intent); 10506 } 10507 } 10508 10509 @Override 10510 protected boolean allowFilterResult( 10511 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 10512 ServiceInfo filterSi = filter.service.info; 10513 for (int i=dest.size()-1; i>=0; i--) { 10514 ServiceInfo destAi = dest.get(i).serviceInfo; 10515 if (destAi.name == filterSi.name 10516 && destAi.packageName == filterSi.packageName) { 10517 return false; 10518 } 10519 } 10520 return true; 10521 } 10522 10523 @Override 10524 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 10525 return new PackageParser.ServiceIntentInfo[size]; 10526 } 10527 10528 @Override 10529 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 10530 if (!sUserManager.exists(userId)) return true; 10531 PackageParser.Package p = filter.service.owner; 10532 if (p != null) { 10533 PackageSetting ps = (PackageSetting)p.mExtras; 10534 if (ps != null) { 10535 // System apps are never considered stopped for purposes of 10536 // filtering, because there may be no way for the user to 10537 // actually re-launch them. 10538 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10539 && ps.getStopped(userId); 10540 } 10541 } 10542 return false; 10543 } 10544 10545 @Override 10546 protected boolean isPackageForFilter(String packageName, 10547 PackageParser.ServiceIntentInfo info) { 10548 return packageName.equals(info.service.owner.packageName); 10549 } 10550 10551 @Override 10552 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 10553 int match, int userId) { 10554 if (!sUserManager.exists(userId)) return null; 10555 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 10556 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 10557 return null; 10558 } 10559 final PackageParser.Service service = info.service; 10560 PackageSetting ps = (PackageSetting) service.owner.mExtras; 10561 if (ps == null) { 10562 return null; 10563 } 10564 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 10565 ps.readUserState(userId), userId); 10566 if (si == null) { 10567 return null; 10568 } 10569 final ResolveInfo res = new ResolveInfo(); 10570 res.serviceInfo = si; 10571 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10572 res.filter = filter; 10573 } 10574 res.priority = info.getPriority(); 10575 res.preferredOrder = service.owner.mPreferredOrder; 10576 res.match = match; 10577 res.isDefault = info.hasDefault; 10578 res.labelRes = info.labelRes; 10579 res.nonLocalizedLabel = info.nonLocalizedLabel; 10580 res.icon = info.icon; 10581 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 10582 return res; 10583 } 10584 10585 @Override 10586 protected void sortResults(List<ResolveInfo> results) { 10587 Collections.sort(results, mResolvePrioritySorter); 10588 } 10589 10590 @Override 10591 protected void dumpFilter(PrintWriter out, String prefix, 10592 PackageParser.ServiceIntentInfo filter) { 10593 out.print(prefix); out.print( 10594 Integer.toHexString(System.identityHashCode(filter.service))); 10595 out.print(' '); 10596 filter.service.printComponentShortName(out); 10597 out.print(" filter "); 10598 out.println(Integer.toHexString(System.identityHashCode(filter))); 10599 } 10600 10601 @Override 10602 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 10603 return filter.service; 10604 } 10605 10606 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10607 PackageParser.Service service = (PackageParser.Service)label; 10608 out.print(prefix); out.print( 10609 Integer.toHexString(System.identityHashCode(service))); 10610 out.print(' '); 10611 service.printComponentShortName(out); 10612 if (count > 1) { 10613 out.print(" ("); out.print(count); out.print(" filters)"); 10614 } 10615 out.println(); 10616 } 10617 10618// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 10619// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 10620// final List<ResolveInfo> retList = Lists.newArrayList(); 10621// while (i.hasNext()) { 10622// final ResolveInfo resolveInfo = (ResolveInfo) i; 10623// if (isEnabledLP(resolveInfo.serviceInfo)) { 10624// retList.add(resolveInfo); 10625// } 10626// } 10627// return retList; 10628// } 10629 10630 // Keys are String (activity class name), values are Activity. 10631 private final ArrayMap<ComponentName, PackageParser.Service> mServices 10632 = new ArrayMap<ComponentName, PackageParser.Service>(); 10633 private int mFlags; 10634 }; 10635 10636 private final class ProviderIntentResolver 10637 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 10638 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10639 boolean defaultOnly, int userId) { 10640 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10641 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10642 } 10643 10644 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10645 int userId) { 10646 if (!sUserManager.exists(userId)) 10647 return null; 10648 mFlags = flags; 10649 return super.queryIntent(intent, resolvedType, 10650 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10651 } 10652 10653 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10654 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 10655 if (!sUserManager.exists(userId)) 10656 return null; 10657 if (packageProviders == null) { 10658 return null; 10659 } 10660 mFlags = flags; 10661 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 10662 final int N = packageProviders.size(); 10663 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 10664 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 10665 10666 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 10667 for (int i = 0; i < N; ++i) { 10668 intentFilters = packageProviders.get(i).intents; 10669 if (intentFilters != null && intentFilters.size() > 0) { 10670 PackageParser.ProviderIntentInfo[] array = 10671 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 10672 intentFilters.toArray(array); 10673 listCut.add(array); 10674 } 10675 } 10676 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10677 } 10678 10679 public final void addProvider(PackageParser.Provider p) { 10680 if (mProviders.containsKey(p.getComponentName())) { 10681 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 10682 return; 10683 } 10684 10685 mProviders.put(p.getComponentName(), p); 10686 if (DEBUG_SHOW_INFO) { 10687 Log.v(TAG, " " 10688 + (p.info.nonLocalizedLabel != null 10689 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10690 Log.v(TAG, " Class=" + p.info.name); 10691 } 10692 final int NI = p.intents.size(); 10693 int j; 10694 for (j = 0; j < NI; j++) { 10695 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10696 if (DEBUG_SHOW_INFO) { 10697 Log.v(TAG, " IntentFilter:"); 10698 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10699 } 10700 if (!intent.debugCheck()) { 10701 Log.w(TAG, "==> For Provider " + p.info.name); 10702 } 10703 addFilter(intent); 10704 } 10705 } 10706 10707 public final void removeProvider(PackageParser.Provider p) { 10708 mProviders.remove(p.getComponentName()); 10709 if (DEBUG_SHOW_INFO) { 10710 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 10711 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10712 Log.v(TAG, " Class=" + p.info.name); 10713 } 10714 final int NI = p.intents.size(); 10715 int j; 10716 for (j = 0; j < NI; j++) { 10717 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10718 if (DEBUG_SHOW_INFO) { 10719 Log.v(TAG, " IntentFilter:"); 10720 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10721 } 10722 removeFilter(intent); 10723 } 10724 } 10725 10726 @Override 10727 protected boolean allowFilterResult( 10728 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 10729 ProviderInfo filterPi = filter.provider.info; 10730 for (int i = dest.size() - 1; i >= 0; i--) { 10731 ProviderInfo destPi = dest.get(i).providerInfo; 10732 if (destPi.name == filterPi.name 10733 && destPi.packageName == filterPi.packageName) { 10734 return false; 10735 } 10736 } 10737 return true; 10738 } 10739 10740 @Override 10741 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 10742 return new PackageParser.ProviderIntentInfo[size]; 10743 } 10744 10745 @Override 10746 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 10747 if (!sUserManager.exists(userId)) 10748 return true; 10749 PackageParser.Package p = filter.provider.owner; 10750 if (p != null) { 10751 PackageSetting ps = (PackageSetting) p.mExtras; 10752 if (ps != null) { 10753 // System apps are never considered stopped for purposes of 10754 // filtering, because there may be no way for the user to 10755 // actually re-launch them. 10756 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10757 && ps.getStopped(userId); 10758 } 10759 } 10760 return false; 10761 } 10762 10763 @Override 10764 protected boolean isPackageForFilter(String packageName, 10765 PackageParser.ProviderIntentInfo info) { 10766 return packageName.equals(info.provider.owner.packageName); 10767 } 10768 10769 @Override 10770 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 10771 int match, int userId) { 10772 if (!sUserManager.exists(userId)) 10773 return null; 10774 final PackageParser.ProviderIntentInfo info = filter; 10775 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 10776 return null; 10777 } 10778 final PackageParser.Provider provider = info.provider; 10779 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 10780 if (ps == null) { 10781 return null; 10782 } 10783 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 10784 ps.readUserState(userId), userId); 10785 if (pi == null) { 10786 return null; 10787 } 10788 final ResolveInfo res = new ResolveInfo(); 10789 res.providerInfo = pi; 10790 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 10791 res.filter = filter; 10792 } 10793 res.priority = info.getPriority(); 10794 res.preferredOrder = provider.owner.mPreferredOrder; 10795 res.match = match; 10796 res.isDefault = info.hasDefault; 10797 res.labelRes = info.labelRes; 10798 res.nonLocalizedLabel = info.nonLocalizedLabel; 10799 res.icon = info.icon; 10800 res.system = res.providerInfo.applicationInfo.isSystemApp(); 10801 return res; 10802 } 10803 10804 @Override 10805 protected void sortResults(List<ResolveInfo> results) { 10806 Collections.sort(results, mResolvePrioritySorter); 10807 } 10808 10809 @Override 10810 protected void dumpFilter(PrintWriter out, String prefix, 10811 PackageParser.ProviderIntentInfo filter) { 10812 out.print(prefix); 10813 out.print( 10814 Integer.toHexString(System.identityHashCode(filter.provider))); 10815 out.print(' '); 10816 filter.provider.printComponentShortName(out); 10817 out.print(" filter "); 10818 out.println(Integer.toHexString(System.identityHashCode(filter))); 10819 } 10820 10821 @Override 10822 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 10823 return filter.provider; 10824 } 10825 10826 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10827 PackageParser.Provider provider = (PackageParser.Provider)label; 10828 out.print(prefix); out.print( 10829 Integer.toHexString(System.identityHashCode(provider))); 10830 out.print(' '); 10831 provider.printComponentShortName(out); 10832 if (count > 1) { 10833 out.print(" ("); out.print(count); out.print(" filters)"); 10834 } 10835 out.println(); 10836 } 10837 10838 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 10839 = new ArrayMap<ComponentName, PackageParser.Provider>(); 10840 private int mFlags; 10841 } 10842 10843 private static final class EphemeralIntentResolver 10844 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 10845 @Override 10846 protected EphemeralResolveIntentInfo[] newArray(int size) { 10847 return new EphemeralResolveIntentInfo[size]; 10848 } 10849 10850 @Override 10851 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 10852 return true; 10853 } 10854 10855 @Override 10856 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 10857 int userId) { 10858 if (!sUserManager.exists(userId)) { 10859 return null; 10860 } 10861 return info.getEphemeralResolveInfo(); 10862 } 10863 } 10864 10865 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 10866 new Comparator<ResolveInfo>() { 10867 public int compare(ResolveInfo r1, ResolveInfo r2) { 10868 int v1 = r1.priority; 10869 int v2 = r2.priority; 10870 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 10871 if (v1 != v2) { 10872 return (v1 > v2) ? -1 : 1; 10873 } 10874 v1 = r1.preferredOrder; 10875 v2 = r2.preferredOrder; 10876 if (v1 != v2) { 10877 return (v1 > v2) ? -1 : 1; 10878 } 10879 if (r1.isDefault != r2.isDefault) { 10880 return r1.isDefault ? -1 : 1; 10881 } 10882 v1 = r1.match; 10883 v2 = r2.match; 10884 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 10885 if (v1 != v2) { 10886 return (v1 > v2) ? -1 : 1; 10887 } 10888 if (r1.system != r2.system) { 10889 return r1.system ? -1 : 1; 10890 } 10891 if (r1.activityInfo != null) { 10892 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 10893 } 10894 if (r1.serviceInfo != null) { 10895 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 10896 } 10897 if (r1.providerInfo != null) { 10898 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 10899 } 10900 return 0; 10901 } 10902 }; 10903 10904 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 10905 new Comparator<ProviderInfo>() { 10906 public int compare(ProviderInfo p1, ProviderInfo p2) { 10907 final int v1 = p1.initOrder; 10908 final int v2 = p2.initOrder; 10909 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 10910 } 10911 }; 10912 10913 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 10914 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 10915 final int[] userIds) { 10916 mHandler.post(new Runnable() { 10917 @Override 10918 public void run() { 10919 try { 10920 final IActivityManager am = ActivityManagerNative.getDefault(); 10921 if (am == null) return; 10922 final int[] resolvedUserIds; 10923 if (userIds == null) { 10924 resolvedUserIds = am.getRunningUserIds(); 10925 } else { 10926 resolvedUserIds = userIds; 10927 } 10928 for (int id : resolvedUserIds) { 10929 final Intent intent = new Intent(action, 10930 pkg != null ? Uri.fromParts("package", pkg, null) : null); 10931 if (extras != null) { 10932 intent.putExtras(extras); 10933 } 10934 if (targetPkg != null) { 10935 intent.setPackage(targetPkg); 10936 } 10937 // Modify the UID when posting to other users 10938 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 10939 if (uid > 0 && UserHandle.getUserId(uid) != id) { 10940 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 10941 intent.putExtra(Intent.EXTRA_UID, uid); 10942 } 10943 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 10944 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 10945 if (DEBUG_BROADCASTS) { 10946 RuntimeException here = new RuntimeException("here"); 10947 here.fillInStackTrace(); 10948 Slog.d(TAG, "Sending to user " + id + ": " 10949 + intent.toShortString(false, true, false, false) 10950 + " " + intent.getExtras(), here); 10951 } 10952 am.broadcastIntent(null, intent, null, finishedReceiver, 10953 0, null, null, null, android.app.AppOpsManager.OP_NONE, 10954 null, finishedReceiver != null, false, id); 10955 } 10956 } catch (RemoteException ex) { 10957 } 10958 } 10959 }); 10960 } 10961 10962 /** 10963 * Check if the external storage media is available. This is true if there 10964 * is a mounted external storage medium or if the external storage is 10965 * emulated. 10966 */ 10967 private boolean isExternalMediaAvailable() { 10968 return mMediaMounted || Environment.isExternalStorageEmulated(); 10969 } 10970 10971 @Override 10972 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 10973 // writer 10974 synchronized (mPackages) { 10975 if (!isExternalMediaAvailable()) { 10976 // If the external storage is no longer mounted at this point, 10977 // the caller may not have been able to delete all of this 10978 // packages files and can not delete any more. Bail. 10979 return null; 10980 } 10981 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 10982 if (lastPackage != null) { 10983 pkgs.remove(lastPackage); 10984 } 10985 if (pkgs.size() > 0) { 10986 return pkgs.get(0); 10987 } 10988 } 10989 return null; 10990 } 10991 10992 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 10993 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 10994 userId, andCode ? 1 : 0, packageName); 10995 if (mSystemReady) { 10996 msg.sendToTarget(); 10997 } else { 10998 if (mPostSystemReadyMessages == null) { 10999 mPostSystemReadyMessages = new ArrayList<>(); 11000 } 11001 mPostSystemReadyMessages.add(msg); 11002 } 11003 } 11004 11005 void startCleaningPackages() { 11006 // reader 11007 if (!isExternalMediaAvailable()) { 11008 return; 11009 } 11010 synchronized (mPackages) { 11011 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 11012 return; 11013 } 11014 } 11015 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 11016 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 11017 IActivityManager am = ActivityManagerNative.getDefault(); 11018 if (am != null) { 11019 try { 11020 am.startService(null, intent, null, mContext.getOpPackageName(), 11021 UserHandle.USER_SYSTEM); 11022 } catch (RemoteException e) { 11023 } 11024 } 11025 } 11026 11027 @Override 11028 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 11029 int installFlags, String installerPackageName, int userId) { 11030 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 11031 11032 final int callingUid = Binder.getCallingUid(); 11033 enforceCrossUserPermission(callingUid, userId, 11034 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 11035 11036 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11037 try { 11038 if (observer != null) { 11039 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 11040 } 11041 } catch (RemoteException re) { 11042 } 11043 return; 11044 } 11045 11046 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 11047 installFlags |= PackageManager.INSTALL_FROM_ADB; 11048 11049 } else { 11050 // Caller holds INSTALL_PACKAGES permission, so we're less strict 11051 // about installerPackageName. 11052 11053 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 11054 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 11055 } 11056 11057 UserHandle user; 11058 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 11059 user = UserHandle.ALL; 11060 } else { 11061 user = new UserHandle(userId); 11062 } 11063 11064 // Only system components can circumvent runtime permissions when installing. 11065 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 11066 && mContext.checkCallingOrSelfPermission(Manifest.permission 11067 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 11068 throw new SecurityException("You need the " 11069 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 11070 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 11071 } 11072 11073 final File originFile = new File(originPath); 11074 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 11075 11076 final Message msg = mHandler.obtainMessage(INIT_COPY); 11077 final VerificationInfo verificationInfo = new VerificationInfo( 11078 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 11079 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 11080 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 11081 null /*packageAbiOverride*/, null /*grantedPermissions*/, 11082 null /*certificates*/); 11083 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 11084 msg.obj = params; 11085 11086 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 11087 System.identityHashCode(msg.obj)); 11088 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11089 System.identityHashCode(msg.obj)); 11090 11091 mHandler.sendMessage(msg); 11092 } 11093 11094 void installStage(String packageName, File stagedDir, String stagedCid, 11095 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 11096 String installerPackageName, int installerUid, UserHandle user, 11097 Certificate[][] certificates) { 11098 if (DEBUG_EPHEMERAL) { 11099 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11100 Slog.d(TAG, "Ephemeral install of " + packageName); 11101 } 11102 } 11103 final VerificationInfo verificationInfo = new VerificationInfo( 11104 sessionParams.originatingUri, sessionParams.referrerUri, 11105 sessionParams.originatingUid, installerUid); 11106 11107 final OriginInfo origin; 11108 if (stagedDir != null) { 11109 origin = OriginInfo.fromStagedFile(stagedDir); 11110 } else { 11111 origin = OriginInfo.fromStagedContainer(stagedCid); 11112 } 11113 11114 final Message msg = mHandler.obtainMessage(INIT_COPY); 11115 final InstallParams params = new InstallParams(origin, null, observer, 11116 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 11117 verificationInfo, user, sessionParams.abiOverride, 11118 sessionParams.grantedRuntimePermissions, certificates); 11119 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 11120 msg.obj = params; 11121 11122 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 11123 System.identityHashCode(msg.obj)); 11124 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11125 System.identityHashCode(msg.obj)); 11126 11127 mHandler.sendMessage(msg); 11128 } 11129 11130 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 11131 int userId) { 11132 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 11133 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId); 11134 } 11135 11136 private void sendPackageAddedForUser(String packageName, boolean isSystem, 11137 int appId, int userId) { 11138 Bundle extras = new Bundle(1); 11139 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId)); 11140 11141 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 11142 packageName, extras, 0, null, null, new int[] {userId}); 11143 try { 11144 IActivityManager am = ActivityManagerNative.getDefault(); 11145 if (isSystem && am.isUserRunning(userId, 0)) { 11146 // The just-installed/enabled app is bundled on the system, so presumed 11147 // to be able to run automatically without needing an explicit launch. 11148 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 11149 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 11150 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 11151 .setPackage(packageName); 11152 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 11153 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 11154 } 11155 } catch (RemoteException e) { 11156 // shouldn't happen 11157 Slog.w(TAG, "Unable to bootstrap installed package", e); 11158 } 11159 } 11160 11161 @Override 11162 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 11163 int userId) { 11164 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11165 PackageSetting pkgSetting; 11166 final int uid = Binder.getCallingUid(); 11167 enforceCrossUserPermission(uid, userId, 11168 true /* requireFullPermission */, true /* checkShell */, 11169 "setApplicationHiddenSetting for user " + userId); 11170 11171 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 11172 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 11173 return false; 11174 } 11175 11176 long callingId = Binder.clearCallingIdentity(); 11177 try { 11178 boolean sendAdded = false; 11179 boolean sendRemoved = false; 11180 // writer 11181 synchronized (mPackages) { 11182 pkgSetting = mSettings.mPackages.get(packageName); 11183 if (pkgSetting == null) { 11184 return false; 11185 } 11186 if (pkgSetting.getHidden(userId) != hidden) { 11187 pkgSetting.setHidden(hidden, userId); 11188 mSettings.writePackageRestrictionsLPr(userId); 11189 if (hidden) { 11190 sendRemoved = true; 11191 } else { 11192 sendAdded = true; 11193 } 11194 } 11195 } 11196 if (sendAdded) { 11197 sendPackageAddedForUser(packageName, pkgSetting, userId); 11198 return true; 11199 } 11200 if (sendRemoved) { 11201 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 11202 "hiding pkg"); 11203 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 11204 return true; 11205 } 11206 } finally { 11207 Binder.restoreCallingIdentity(callingId); 11208 } 11209 return false; 11210 } 11211 11212 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 11213 int userId) { 11214 final PackageRemovedInfo info = new PackageRemovedInfo(); 11215 info.removedPackage = packageName; 11216 info.removedUsers = new int[] {userId}; 11217 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 11218 info.sendPackageRemovedBroadcasts(true /*killApp*/); 11219 } 11220 11221 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 11222 if (pkgList.length > 0) { 11223 Bundle extras = new Bundle(1); 11224 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 11225 11226 sendPackageBroadcast( 11227 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 11228 : Intent.ACTION_PACKAGES_UNSUSPENDED, 11229 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 11230 new int[] {userId}); 11231 } 11232 } 11233 11234 /** 11235 * Returns true if application is not found or there was an error. Otherwise it returns 11236 * the hidden state of the package for the given user. 11237 */ 11238 @Override 11239 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 11240 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11241 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11242 true /* requireFullPermission */, false /* checkShell */, 11243 "getApplicationHidden for user " + userId); 11244 PackageSetting pkgSetting; 11245 long callingId = Binder.clearCallingIdentity(); 11246 try { 11247 // writer 11248 synchronized (mPackages) { 11249 pkgSetting = mSettings.mPackages.get(packageName); 11250 if (pkgSetting == null) { 11251 return true; 11252 } 11253 return pkgSetting.getHidden(userId); 11254 } 11255 } finally { 11256 Binder.restoreCallingIdentity(callingId); 11257 } 11258 } 11259 11260 /** 11261 * @hide 11262 */ 11263 @Override 11264 public int installExistingPackageAsUser(String packageName, int userId) { 11265 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 11266 null); 11267 PackageSetting pkgSetting; 11268 final int uid = Binder.getCallingUid(); 11269 enforceCrossUserPermission(uid, userId, 11270 true /* requireFullPermission */, true /* checkShell */, 11271 "installExistingPackage for user " + userId); 11272 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11273 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 11274 } 11275 11276 long callingId = Binder.clearCallingIdentity(); 11277 try { 11278 boolean installed = false; 11279 11280 // writer 11281 synchronized (mPackages) { 11282 pkgSetting = mSettings.mPackages.get(packageName); 11283 if (pkgSetting == null) { 11284 return PackageManager.INSTALL_FAILED_INVALID_URI; 11285 } 11286 if (!pkgSetting.getInstalled(userId)) { 11287 pkgSetting.setInstalled(true, userId); 11288 pkgSetting.setHidden(false, userId); 11289 mSettings.writePackageRestrictionsLPr(userId); 11290 installed = true; 11291 } 11292 } 11293 11294 if (installed) { 11295 if (pkgSetting.pkg != null) { 11296 synchronized (mInstallLock) { 11297 // We don't need to freeze for a brand new install 11298 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 11299 } 11300 } 11301 sendPackageAddedForUser(packageName, pkgSetting, userId); 11302 } 11303 } finally { 11304 Binder.restoreCallingIdentity(callingId); 11305 } 11306 11307 return PackageManager.INSTALL_SUCCEEDED; 11308 } 11309 11310 boolean isUserRestricted(int userId, String restrictionKey) { 11311 Bundle restrictions = sUserManager.getUserRestrictions(userId); 11312 if (restrictions.getBoolean(restrictionKey, false)) { 11313 Log.w(TAG, "User is restricted: " + restrictionKey); 11314 return true; 11315 } 11316 return false; 11317 } 11318 11319 @Override 11320 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 11321 int userId) { 11322 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11323 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11324 true /* requireFullPermission */, true /* checkShell */, 11325 "setPackagesSuspended for user " + userId); 11326 11327 if (ArrayUtils.isEmpty(packageNames)) { 11328 return packageNames; 11329 } 11330 11331 // List of package names for whom the suspended state has changed. 11332 List<String> changedPackages = new ArrayList<>(packageNames.length); 11333 // List of package names for whom the suspended state is not set as requested in this 11334 // method. 11335 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 11336 for (int i = 0; i < packageNames.length; i++) { 11337 String packageName = packageNames[i]; 11338 long callingId = Binder.clearCallingIdentity(); 11339 try { 11340 boolean changed = false; 11341 final int appId; 11342 synchronized (mPackages) { 11343 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11344 if (pkgSetting == null) { 11345 Slog.w(TAG, "Could not find package setting for package \"" + packageName 11346 + "\". Skipping suspending/un-suspending."); 11347 unactionedPackages.add(packageName); 11348 continue; 11349 } 11350 appId = pkgSetting.appId; 11351 if (pkgSetting.getSuspended(userId) != suspended) { 11352 if (!canSuspendPackageForUserLocked(packageName, userId)) { 11353 unactionedPackages.add(packageName); 11354 continue; 11355 } 11356 pkgSetting.setSuspended(suspended, userId); 11357 mSettings.writePackageRestrictionsLPr(userId); 11358 changed = true; 11359 changedPackages.add(packageName); 11360 } 11361 } 11362 11363 if (changed && suspended) { 11364 killApplication(packageName, UserHandle.getUid(userId, appId), 11365 "suspending package"); 11366 } 11367 } finally { 11368 Binder.restoreCallingIdentity(callingId); 11369 } 11370 } 11371 11372 if (!changedPackages.isEmpty()) { 11373 sendPackagesSuspendedForUser(changedPackages.toArray( 11374 new String[changedPackages.size()]), userId, suspended); 11375 } 11376 11377 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 11378 } 11379 11380 @Override 11381 public boolean isPackageSuspendedForUser(String packageName, int userId) { 11382 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11383 true /* requireFullPermission */, false /* checkShell */, 11384 "isPackageSuspendedForUser for user " + userId); 11385 synchronized (mPackages) { 11386 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11387 if (pkgSetting == null) { 11388 throw new IllegalArgumentException("Unknown target package: " + packageName); 11389 } 11390 return pkgSetting.getSuspended(userId); 11391 } 11392 } 11393 11394 /** 11395 * TODO: cache and disallow blocking the active dialer. 11396 * 11397 * @see also DefaultPermissionGrantPolicy#grantDefaultSystemHandlerPermissions 11398 */ 11399 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 11400 if (isPackageDeviceAdmin(packageName, userId)) { 11401 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11402 + "\": has an active device admin"); 11403 return false; 11404 } 11405 11406 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 11407 if (packageName.equals(activeLauncherPackageName)) { 11408 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11409 + "\": contains the active launcher"); 11410 return false; 11411 } 11412 11413 if (packageName.equals(mRequiredInstallerPackage)) { 11414 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11415 + "\": required for package installation"); 11416 return false; 11417 } 11418 11419 if (packageName.equals(mRequiredVerifierPackage)) { 11420 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11421 + "\": required for package verification"); 11422 return false; 11423 } 11424 11425 final PackageParser.Package pkg = mPackages.get(packageName); 11426 if (pkg != null && isPrivilegedApp(pkg)) { 11427 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11428 + "\": is a privileged app"); 11429 return false; 11430 } 11431 11432 return true; 11433 } 11434 11435 private String getActiveLauncherPackageName(int userId) { 11436 Intent intent = new Intent(Intent.ACTION_MAIN); 11437 intent.addCategory(Intent.CATEGORY_HOME); 11438 ResolveInfo resolveInfo = resolveIntent( 11439 intent, 11440 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 11441 PackageManager.MATCH_DEFAULT_ONLY, 11442 userId); 11443 11444 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 11445 } 11446 11447 @Override 11448 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 11449 mContext.enforceCallingOrSelfPermission( 11450 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11451 "Only package verification agents can verify applications"); 11452 11453 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11454 final PackageVerificationResponse response = new PackageVerificationResponse( 11455 verificationCode, Binder.getCallingUid()); 11456 msg.arg1 = id; 11457 msg.obj = response; 11458 mHandler.sendMessage(msg); 11459 } 11460 11461 @Override 11462 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 11463 long millisecondsToDelay) { 11464 mContext.enforceCallingOrSelfPermission( 11465 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11466 "Only package verification agents can extend verification timeouts"); 11467 11468 final PackageVerificationState state = mPendingVerification.get(id); 11469 final PackageVerificationResponse response = new PackageVerificationResponse( 11470 verificationCodeAtTimeout, Binder.getCallingUid()); 11471 11472 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 11473 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 11474 } 11475 if (millisecondsToDelay < 0) { 11476 millisecondsToDelay = 0; 11477 } 11478 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 11479 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 11480 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 11481 } 11482 11483 if ((state != null) && !state.timeoutExtended()) { 11484 state.extendTimeout(); 11485 11486 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11487 msg.arg1 = id; 11488 msg.obj = response; 11489 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 11490 } 11491 } 11492 11493 private void broadcastPackageVerified(int verificationId, Uri packageUri, 11494 int verificationCode, UserHandle user) { 11495 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 11496 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 11497 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11498 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11499 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 11500 11501 mContext.sendBroadcastAsUser(intent, user, 11502 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 11503 } 11504 11505 private ComponentName matchComponentForVerifier(String packageName, 11506 List<ResolveInfo> receivers) { 11507 ActivityInfo targetReceiver = null; 11508 11509 final int NR = receivers.size(); 11510 for (int i = 0; i < NR; i++) { 11511 final ResolveInfo info = receivers.get(i); 11512 if (info.activityInfo == null) { 11513 continue; 11514 } 11515 11516 if (packageName.equals(info.activityInfo.packageName)) { 11517 targetReceiver = info.activityInfo; 11518 break; 11519 } 11520 } 11521 11522 if (targetReceiver == null) { 11523 return null; 11524 } 11525 11526 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 11527 } 11528 11529 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 11530 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 11531 if (pkgInfo.verifiers.length == 0) { 11532 return null; 11533 } 11534 11535 final int N = pkgInfo.verifiers.length; 11536 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 11537 for (int i = 0; i < N; i++) { 11538 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 11539 11540 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 11541 receivers); 11542 if (comp == null) { 11543 continue; 11544 } 11545 11546 final int verifierUid = getUidForVerifier(verifierInfo); 11547 if (verifierUid == -1) { 11548 continue; 11549 } 11550 11551 if (DEBUG_VERIFY) { 11552 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 11553 + " with the correct signature"); 11554 } 11555 sufficientVerifiers.add(comp); 11556 verificationState.addSufficientVerifier(verifierUid); 11557 } 11558 11559 return sufficientVerifiers; 11560 } 11561 11562 private int getUidForVerifier(VerifierInfo verifierInfo) { 11563 synchronized (mPackages) { 11564 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 11565 if (pkg == null) { 11566 return -1; 11567 } else if (pkg.mSignatures.length != 1) { 11568 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11569 + " has more than one signature; ignoring"); 11570 return -1; 11571 } 11572 11573 /* 11574 * If the public key of the package's signature does not match 11575 * our expected public key, then this is a different package and 11576 * we should skip. 11577 */ 11578 11579 final byte[] expectedPublicKey; 11580 try { 11581 final Signature verifierSig = pkg.mSignatures[0]; 11582 final PublicKey publicKey = verifierSig.getPublicKey(); 11583 expectedPublicKey = publicKey.getEncoded(); 11584 } catch (CertificateException e) { 11585 return -1; 11586 } 11587 11588 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 11589 11590 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 11591 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11592 + " does not have the expected public key; ignoring"); 11593 return -1; 11594 } 11595 11596 return pkg.applicationInfo.uid; 11597 } 11598 } 11599 11600 @Override 11601 public void finishPackageInstall(int token) { 11602 enforceSystemOrRoot("Only the system is allowed to finish installs"); 11603 11604 if (DEBUG_INSTALL) { 11605 Slog.v(TAG, "BM finishing package install for " + token); 11606 } 11607 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 11608 11609 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 11610 mHandler.sendMessage(msg); 11611 } 11612 11613 /** 11614 * Get the verification agent timeout. 11615 * 11616 * @return verification timeout in milliseconds 11617 */ 11618 private long getVerificationTimeout() { 11619 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 11620 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 11621 DEFAULT_VERIFICATION_TIMEOUT); 11622 } 11623 11624 /** 11625 * Get the default verification agent response code. 11626 * 11627 * @return default verification response code 11628 */ 11629 private int getDefaultVerificationResponse() { 11630 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11631 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 11632 DEFAULT_VERIFICATION_RESPONSE); 11633 } 11634 11635 /** 11636 * Check whether or not package verification has been enabled. 11637 * 11638 * @return true if verification should be performed 11639 */ 11640 private boolean isVerificationEnabled(int userId, int installFlags) { 11641 if (!DEFAULT_VERIFY_ENABLE) { 11642 return false; 11643 } 11644 // Ephemeral apps don't get the full verification treatment 11645 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11646 if (DEBUG_EPHEMERAL) { 11647 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 11648 } 11649 return false; 11650 } 11651 11652 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 11653 11654 // Check if installing from ADB 11655 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 11656 // Do not run verification in a test harness environment 11657 if (ActivityManager.isRunningInTestHarness()) { 11658 return false; 11659 } 11660 if (ensureVerifyAppsEnabled) { 11661 return true; 11662 } 11663 // Check if the developer does not want package verification for ADB installs 11664 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11665 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 11666 return false; 11667 } 11668 } 11669 11670 if (ensureVerifyAppsEnabled) { 11671 return true; 11672 } 11673 11674 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11675 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 11676 } 11677 11678 @Override 11679 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 11680 throws RemoteException { 11681 mContext.enforceCallingOrSelfPermission( 11682 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 11683 "Only intentfilter verification agents can verify applications"); 11684 11685 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 11686 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 11687 Binder.getCallingUid(), verificationCode, failedDomains); 11688 msg.arg1 = id; 11689 msg.obj = response; 11690 mHandler.sendMessage(msg); 11691 } 11692 11693 @Override 11694 public int getIntentVerificationStatus(String packageName, int userId) { 11695 synchronized (mPackages) { 11696 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 11697 } 11698 } 11699 11700 @Override 11701 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 11702 mContext.enforceCallingOrSelfPermission( 11703 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11704 11705 boolean result = false; 11706 synchronized (mPackages) { 11707 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 11708 } 11709 if (result) { 11710 scheduleWritePackageRestrictionsLocked(userId); 11711 } 11712 return result; 11713 } 11714 11715 @Override 11716 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 11717 String packageName) { 11718 synchronized (mPackages) { 11719 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 11720 } 11721 } 11722 11723 @Override 11724 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 11725 if (TextUtils.isEmpty(packageName)) { 11726 return ParceledListSlice.emptyList(); 11727 } 11728 synchronized (mPackages) { 11729 PackageParser.Package pkg = mPackages.get(packageName); 11730 if (pkg == null || pkg.activities == null) { 11731 return ParceledListSlice.emptyList(); 11732 } 11733 final int count = pkg.activities.size(); 11734 ArrayList<IntentFilter> result = new ArrayList<>(); 11735 for (int n=0; n<count; n++) { 11736 PackageParser.Activity activity = pkg.activities.get(n); 11737 if (activity.intents != null && activity.intents.size() > 0) { 11738 result.addAll(activity.intents); 11739 } 11740 } 11741 return new ParceledListSlice<>(result); 11742 } 11743 } 11744 11745 @Override 11746 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 11747 mContext.enforceCallingOrSelfPermission( 11748 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11749 11750 synchronized (mPackages) { 11751 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 11752 if (packageName != null) { 11753 result |= updateIntentVerificationStatus(packageName, 11754 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 11755 userId); 11756 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 11757 packageName, userId); 11758 } 11759 return result; 11760 } 11761 } 11762 11763 @Override 11764 public String getDefaultBrowserPackageName(int userId) { 11765 synchronized (mPackages) { 11766 return mSettings.getDefaultBrowserPackageNameLPw(userId); 11767 } 11768 } 11769 11770 /** 11771 * Get the "allow unknown sources" setting. 11772 * 11773 * @return the current "allow unknown sources" setting 11774 */ 11775 private int getUnknownSourcesSettings() { 11776 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 11777 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 11778 -1); 11779 } 11780 11781 @Override 11782 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 11783 final int uid = Binder.getCallingUid(); 11784 // writer 11785 synchronized (mPackages) { 11786 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 11787 if (targetPackageSetting == null) { 11788 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 11789 } 11790 11791 PackageSetting installerPackageSetting; 11792 if (installerPackageName != null) { 11793 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 11794 if (installerPackageSetting == null) { 11795 throw new IllegalArgumentException("Unknown installer package: " 11796 + installerPackageName); 11797 } 11798 } else { 11799 installerPackageSetting = null; 11800 } 11801 11802 Signature[] callerSignature; 11803 Object obj = mSettings.getUserIdLPr(uid); 11804 if (obj != null) { 11805 if (obj instanceof SharedUserSetting) { 11806 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 11807 } else if (obj instanceof PackageSetting) { 11808 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 11809 } else { 11810 throw new SecurityException("Bad object " + obj + " for uid " + uid); 11811 } 11812 } else { 11813 throw new SecurityException("Unknown calling UID: " + uid); 11814 } 11815 11816 // Verify: can't set installerPackageName to a package that is 11817 // not signed with the same cert as the caller. 11818 if (installerPackageSetting != null) { 11819 if (compareSignatures(callerSignature, 11820 installerPackageSetting.signatures.mSignatures) 11821 != PackageManager.SIGNATURE_MATCH) { 11822 throw new SecurityException( 11823 "Caller does not have same cert as new installer package " 11824 + installerPackageName); 11825 } 11826 } 11827 11828 // Verify: if target already has an installer package, it must 11829 // be signed with the same cert as the caller. 11830 if (targetPackageSetting.installerPackageName != null) { 11831 PackageSetting setting = mSettings.mPackages.get( 11832 targetPackageSetting.installerPackageName); 11833 // If the currently set package isn't valid, then it's always 11834 // okay to change it. 11835 if (setting != null) { 11836 if (compareSignatures(callerSignature, 11837 setting.signatures.mSignatures) 11838 != PackageManager.SIGNATURE_MATCH) { 11839 throw new SecurityException( 11840 "Caller does not have same cert as old installer package " 11841 + targetPackageSetting.installerPackageName); 11842 } 11843 } 11844 } 11845 11846 // Okay! 11847 targetPackageSetting.installerPackageName = installerPackageName; 11848 if (installerPackageName != null) { 11849 mSettings.mInstallerPackages.add(installerPackageName); 11850 } 11851 scheduleWriteSettingsLocked(); 11852 } 11853 } 11854 11855 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 11856 // Queue up an async operation since the package installation may take a little while. 11857 mHandler.post(new Runnable() { 11858 public void run() { 11859 mHandler.removeCallbacks(this); 11860 // Result object to be returned 11861 PackageInstalledInfo res = new PackageInstalledInfo(); 11862 res.setReturnCode(currentStatus); 11863 res.uid = -1; 11864 res.pkg = null; 11865 res.removedInfo = null; 11866 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11867 args.doPreInstall(res.returnCode); 11868 synchronized (mInstallLock) { 11869 installPackageTracedLI(args, res); 11870 } 11871 args.doPostInstall(res.returnCode, res.uid); 11872 } 11873 11874 // A restore should be performed at this point if (a) the install 11875 // succeeded, (b) the operation is not an update, and (c) the new 11876 // package has not opted out of backup participation. 11877 final boolean update = res.removedInfo != null 11878 && res.removedInfo.removedPackage != null; 11879 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 11880 boolean doRestore = !update 11881 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 11882 11883 // Set up the post-install work request bookkeeping. This will be used 11884 // and cleaned up by the post-install event handling regardless of whether 11885 // there's a restore pass performed. Token values are >= 1. 11886 int token; 11887 if (mNextInstallToken < 0) mNextInstallToken = 1; 11888 token = mNextInstallToken++; 11889 11890 PostInstallData data = new PostInstallData(args, res); 11891 mRunningInstalls.put(token, data); 11892 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 11893 11894 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 11895 // Pass responsibility to the Backup Manager. It will perform a 11896 // restore if appropriate, then pass responsibility back to the 11897 // Package Manager to run the post-install observer callbacks 11898 // and broadcasts. 11899 IBackupManager bm = IBackupManager.Stub.asInterface( 11900 ServiceManager.getService(Context.BACKUP_SERVICE)); 11901 if (bm != null) { 11902 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 11903 + " to BM for possible restore"); 11904 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 11905 try { 11906 // TODO: http://b/22388012 11907 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 11908 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 11909 } else { 11910 doRestore = false; 11911 } 11912 } catch (RemoteException e) { 11913 // can't happen; the backup manager is local 11914 } catch (Exception e) { 11915 Slog.e(TAG, "Exception trying to enqueue restore", e); 11916 doRestore = false; 11917 } 11918 } else { 11919 Slog.e(TAG, "Backup Manager not found!"); 11920 doRestore = false; 11921 } 11922 } 11923 11924 if (!doRestore) { 11925 // No restore possible, or the Backup Manager was mysteriously not 11926 // available -- just fire the post-install work request directly. 11927 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 11928 11929 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 11930 11931 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 11932 mHandler.sendMessage(msg); 11933 } 11934 } 11935 }); 11936 } 11937 11938 private abstract class HandlerParams { 11939 private static final int MAX_RETRIES = 4; 11940 11941 /** 11942 * Number of times startCopy() has been attempted and had a non-fatal 11943 * error. 11944 */ 11945 private int mRetries = 0; 11946 11947 /** User handle for the user requesting the information or installation. */ 11948 private final UserHandle mUser; 11949 String traceMethod; 11950 int traceCookie; 11951 11952 HandlerParams(UserHandle user) { 11953 mUser = user; 11954 } 11955 11956 UserHandle getUser() { 11957 return mUser; 11958 } 11959 11960 HandlerParams setTraceMethod(String traceMethod) { 11961 this.traceMethod = traceMethod; 11962 return this; 11963 } 11964 11965 HandlerParams setTraceCookie(int traceCookie) { 11966 this.traceCookie = traceCookie; 11967 return this; 11968 } 11969 11970 final boolean startCopy() { 11971 boolean res; 11972 try { 11973 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 11974 11975 if (++mRetries > MAX_RETRIES) { 11976 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 11977 mHandler.sendEmptyMessage(MCS_GIVE_UP); 11978 handleServiceError(); 11979 return false; 11980 } else { 11981 handleStartCopy(); 11982 res = true; 11983 } 11984 } catch (RemoteException e) { 11985 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 11986 mHandler.sendEmptyMessage(MCS_RECONNECT); 11987 res = false; 11988 } 11989 handleReturnCode(); 11990 return res; 11991 } 11992 11993 final void serviceError() { 11994 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 11995 handleServiceError(); 11996 handleReturnCode(); 11997 } 11998 11999 abstract void handleStartCopy() throws RemoteException; 12000 abstract void handleServiceError(); 12001 abstract void handleReturnCode(); 12002 } 12003 12004 class MeasureParams extends HandlerParams { 12005 private final PackageStats mStats; 12006 private boolean mSuccess; 12007 12008 private final IPackageStatsObserver mObserver; 12009 12010 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 12011 super(new UserHandle(stats.userHandle)); 12012 mObserver = observer; 12013 mStats = stats; 12014 } 12015 12016 @Override 12017 public String toString() { 12018 return "MeasureParams{" 12019 + Integer.toHexString(System.identityHashCode(this)) 12020 + " " + mStats.packageName + "}"; 12021 } 12022 12023 @Override 12024 void handleStartCopy() throws RemoteException { 12025 synchronized (mInstallLock) { 12026 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 12027 } 12028 12029 if (mSuccess) { 12030 final boolean mounted; 12031 if (Environment.isExternalStorageEmulated()) { 12032 mounted = true; 12033 } else { 12034 final String status = Environment.getExternalStorageState(); 12035 mounted = (Environment.MEDIA_MOUNTED.equals(status) 12036 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 12037 } 12038 12039 if (mounted) { 12040 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 12041 12042 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 12043 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 12044 12045 mStats.externalDataSize = calculateDirectorySize(mContainerService, 12046 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 12047 12048 // Always subtract cache size, since it's a subdirectory 12049 mStats.externalDataSize -= mStats.externalCacheSize; 12050 12051 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 12052 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 12053 12054 mStats.externalObbSize = calculateDirectorySize(mContainerService, 12055 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 12056 } 12057 } 12058 } 12059 12060 @Override 12061 void handleReturnCode() { 12062 if (mObserver != null) { 12063 try { 12064 mObserver.onGetStatsCompleted(mStats, mSuccess); 12065 } catch (RemoteException e) { 12066 Slog.i(TAG, "Observer no longer exists."); 12067 } 12068 } 12069 } 12070 12071 @Override 12072 void handleServiceError() { 12073 Slog.e(TAG, "Could not measure application " + mStats.packageName 12074 + " external storage"); 12075 } 12076 } 12077 12078 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 12079 throws RemoteException { 12080 long result = 0; 12081 for (File path : paths) { 12082 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 12083 } 12084 return result; 12085 } 12086 12087 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 12088 for (File path : paths) { 12089 try { 12090 mcs.clearDirectory(path.getAbsolutePath()); 12091 } catch (RemoteException e) { 12092 } 12093 } 12094 } 12095 12096 static class OriginInfo { 12097 /** 12098 * Location where install is coming from, before it has been 12099 * copied/renamed into place. This could be a single monolithic APK 12100 * file, or a cluster directory. This location may be untrusted. 12101 */ 12102 final File file; 12103 final String cid; 12104 12105 /** 12106 * Flag indicating that {@link #file} or {@link #cid} has already been 12107 * staged, meaning downstream users don't need to defensively copy the 12108 * contents. 12109 */ 12110 final boolean staged; 12111 12112 /** 12113 * Flag indicating that {@link #file} or {@link #cid} is an already 12114 * installed app that is being moved. 12115 */ 12116 final boolean existing; 12117 12118 final String resolvedPath; 12119 final File resolvedFile; 12120 12121 static OriginInfo fromNothing() { 12122 return new OriginInfo(null, null, false, false); 12123 } 12124 12125 static OriginInfo fromUntrustedFile(File file) { 12126 return new OriginInfo(file, null, false, false); 12127 } 12128 12129 static OriginInfo fromExistingFile(File file) { 12130 return new OriginInfo(file, null, false, true); 12131 } 12132 12133 static OriginInfo fromStagedFile(File file) { 12134 return new OriginInfo(file, null, true, false); 12135 } 12136 12137 static OriginInfo fromStagedContainer(String cid) { 12138 return new OriginInfo(null, cid, true, false); 12139 } 12140 12141 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 12142 this.file = file; 12143 this.cid = cid; 12144 this.staged = staged; 12145 this.existing = existing; 12146 12147 if (cid != null) { 12148 resolvedPath = PackageHelper.getSdDir(cid); 12149 resolvedFile = new File(resolvedPath); 12150 } else if (file != null) { 12151 resolvedPath = file.getAbsolutePath(); 12152 resolvedFile = file; 12153 } else { 12154 resolvedPath = null; 12155 resolvedFile = null; 12156 } 12157 } 12158 } 12159 12160 static class MoveInfo { 12161 final int moveId; 12162 final String fromUuid; 12163 final String toUuid; 12164 final String packageName; 12165 final String dataAppName; 12166 final int appId; 12167 final String seinfo; 12168 final int targetSdkVersion; 12169 12170 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 12171 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 12172 this.moveId = moveId; 12173 this.fromUuid = fromUuid; 12174 this.toUuid = toUuid; 12175 this.packageName = packageName; 12176 this.dataAppName = dataAppName; 12177 this.appId = appId; 12178 this.seinfo = seinfo; 12179 this.targetSdkVersion = targetSdkVersion; 12180 } 12181 } 12182 12183 static class VerificationInfo { 12184 /** A constant used to indicate that a uid value is not present. */ 12185 public static final int NO_UID = -1; 12186 12187 /** URI referencing where the package was downloaded from. */ 12188 final Uri originatingUri; 12189 12190 /** HTTP referrer URI associated with the originatingURI. */ 12191 final Uri referrer; 12192 12193 /** UID of the application that the install request originated from. */ 12194 final int originatingUid; 12195 12196 /** UID of application requesting the install */ 12197 final int installerUid; 12198 12199 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 12200 this.originatingUri = originatingUri; 12201 this.referrer = referrer; 12202 this.originatingUid = originatingUid; 12203 this.installerUid = installerUid; 12204 } 12205 } 12206 12207 class InstallParams extends HandlerParams { 12208 final OriginInfo origin; 12209 final MoveInfo move; 12210 final IPackageInstallObserver2 observer; 12211 int installFlags; 12212 final String installerPackageName; 12213 final String volumeUuid; 12214 private InstallArgs mArgs; 12215 private int mRet; 12216 final String packageAbiOverride; 12217 final String[] grantedRuntimePermissions; 12218 final VerificationInfo verificationInfo; 12219 final Certificate[][] certificates; 12220 12221 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12222 int installFlags, String installerPackageName, String volumeUuid, 12223 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 12224 String[] grantedPermissions, Certificate[][] certificates) { 12225 super(user); 12226 this.origin = origin; 12227 this.move = move; 12228 this.observer = observer; 12229 this.installFlags = installFlags; 12230 this.installerPackageName = installerPackageName; 12231 this.volumeUuid = volumeUuid; 12232 this.verificationInfo = verificationInfo; 12233 this.packageAbiOverride = packageAbiOverride; 12234 this.grantedRuntimePermissions = grantedPermissions; 12235 this.certificates = certificates; 12236 } 12237 12238 @Override 12239 public String toString() { 12240 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 12241 + " file=" + origin.file + " cid=" + origin.cid + "}"; 12242 } 12243 12244 private int installLocationPolicy(PackageInfoLite pkgLite) { 12245 String packageName = pkgLite.packageName; 12246 int installLocation = pkgLite.installLocation; 12247 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12248 // reader 12249 synchronized (mPackages) { 12250 // Currently installed package which the new package is attempting to replace or 12251 // null if no such package is installed. 12252 PackageParser.Package installedPkg = mPackages.get(packageName); 12253 // Package which currently owns the data which the new package will own if installed. 12254 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 12255 // will be null whereas dataOwnerPkg will contain information about the package 12256 // which was uninstalled while keeping its data. 12257 PackageParser.Package dataOwnerPkg = installedPkg; 12258 if (dataOwnerPkg == null) { 12259 PackageSetting ps = mSettings.mPackages.get(packageName); 12260 if (ps != null) { 12261 dataOwnerPkg = ps.pkg; 12262 } 12263 } 12264 12265 if (dataOwnerPkg != null) { 12266 // If installed, the package will get access to data left on the device by its 12267 // predecessor. As a security measure, this is permited only if this is not a 12268 // version downgrade or if the predecessor package is marked as debuggable and 12269 // a downgrade is explicitly requested. 12270 // 12271 // On debuggable platform builds, downgrades are permitted even for 12272 // non-debuggable packages to make testing easier. Debuggable platform builds do 12273 // not offer security guarantees and thus it's OK to disable some security 12274 // mechanisms to make debugging/testing easier on those builds. However, even on 12275 // debuggable builds downgrades of packages are permitted only if requested via 12276 // installFlags. This is because we aim to keep the behavior of debuggable 12277 // platform builds as close as possible to the behavior of non-debuggable 12278 // platform builds. 12279 final boolean downgradeRequested = 12280 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 12281 final boolean packageDebuggable = 12282 (dataOwnerPkg.applicationInfo.flags 12283 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 12284 final boolean downgradePermitted = 12285 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 12286 if (!downgradePermitted) { 12287 try { 12288 checkDowngrade(dataOwnerPkg, pkgLite); 12289 } catch (PackageManagerException e) { 12290 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 12291 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 12292 } 12293 } 12294 } 12295 12296 if (installedPkg != null) { 12297 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12298 // Check for updated system application. 12299 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 12300 if (onSd) { 12301 Slog.w(TAG, "Cannot install update to system app on sdcard"); 12302 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 12303 } 12304 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12305 } else { 12306 if (onSd) { 12307 // Install flag overrides everything. 12308 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12309 } 12310 // If current upgrade specifies particular preference 12311 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 12312 // Application explicitly specified internal. 12313 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12314 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 12315 // App explictly prefers external. Let policy decide 12316 } else { 12317 // Prefer previous location 12318 if (isExternal(installedPkg)) { 12319 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12320 } 12321 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12322 } 12323 } 12324 } else { 12325 // Invalid install. Return error code 12326 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 12327 } 12328 } 12329 } 12330 // All the special cases have been taken care of. 12331 // Return result based on recommended install location. 12332 if (onSd) { 12333 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12334 } 12335 return pkgLite.recommendedInstallLocation; 12336 } 12337 12338 /* 12339 * Invoke remote method to get package information and install 12340 * location values. Override install location based on default 12341 * policy if needed and then create install arguments based 12342 * on the install location. 12343 */ 12344 public void handleStartCopy() throws RemoteException { 12345 int ret = PackageManager.INSTALL_SUCCEEDED; 12346 12347 // If we're already staged, we've firmly committed to an install location 12348 if (origin.staged) { 12349 if (origin.file != null) { 12350 installFlags |= PackageManager.INSTALL_INTERNAL; 12351 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12352 } else if (origin.cid != null) { 12353 installFlags |= PackageManager.INSTALL_EXTERNAL; 12354 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12355 } else { 12356 throw new IllegalStateException("Invalid stage location"); 12357 } 12358 } 12359 12360 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12361 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 12362 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12363 PackageInfoLite pkgLite = null; 12364 12365 if (onInt && onSd) { 12366 // Check if both bits are set. 12367 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 12368 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12369 } else if (onSd && ephemeral) { 12370 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 12371 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12372 } else { 12373 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 12374 packageAbiOverride); 12375 12376 if (DEBUG_EPHEMERAL && ephemeral) { 12377 Slog.v(TAG, "pkgLite for install: " + pkgLite); 12378 } 12379 12380 /* 12381 * If we have too little free space, try to free cache 12382 * before giving up. 12383 */ 12384 if (!origin.staged && pkgLite.recommendedInstallLocation 12385 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12386 // TODO: focus freeing disk space on the target device 12387 final StorageManager storage = StorageManager.from(mContext); 12388 final long lowThreshold = storage.getStorageLowBytes( 12389 Environment.getDataDirectory()); 12390 12391 final long sizeBytes = mContainerService.calculateInstalledSize( 12392 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 12393 12394 try { 12395 mInstaller.freeCache(null, sizeBytes + lowThreshold); 12396 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 12397 installFlags, packageAbiOverride); 12398 } catch (InstallerException e) { 12399 Slog.w(TAG, "Failed to free cache", e); 12400 } 12401 12402 /* 12403 * The cache free must have deleted the file we 12404 * downloaded to install. 12405 * 12406 * TODO: fix the "freeCache" call to not delete 12407 * the file we care about. 12408 */ 12409 if (pkgLite.recommendedInstallLocation 12410 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12411 pkgLite.recommendedInstallLocation 12412 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 12413 } 12414 } 12415 } 12416 12417 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12418 int loc = pkgLite.recommendedInstallLocation; 12419 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 12420 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12421 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 12422 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 12423 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12424 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12425 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 12426 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 12427 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12428 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 12429 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 12430 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 12431 } else { 12432 // Override with defaults if needed. 12433 loc = installLocationPolicy(pkgLite); 12434 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 12435 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 12436 } else if (!onSd && !onInt) { 12437 // Override install location with flags 12438 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 12439 // Set the flag to install on external media. 12440 installFlags |= PackageManager.INSTALL_EXTERNAL; 12441 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12442 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 12443 if (DEBUG_EPHEMERAL) { 12444 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 12445 } 12446 installFlags |= PackageManager.INSTALL_EPHEMERAL; 12447 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 12448 |PackageManager.INSTALL_INTERNAL); 12449 } else { 12450 // Make sure the flag for installing on external 12451 // media is unset 12452 installFlags |= PackageManager.INSTALL_INTERNAL; 12453 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12454 } 12455 } 12456 } 12457 } 12458 12459 final InstallArgs args = createInstallArgs(this); 12460 mArgs = args; 12461 12462 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12463 // TODO: http://b/22976637 12464 // Apps installed for "all" users use the device owner to verify the app 12465 UserHandle verifierUser = getUser(); 12466 if (verifierUser == UserHandle.ALL) { 12467 verifierUser = UserHandle.SYSTEM; 12468 } 12469 12470 /* 12471 * Determine if we have any installed package verifiers. If we 12472 * do, then we'll defer to them to verify the packages. 12473 */ 12474 final int requiredUid = mRequiredVerifierPackage == null ? -1 12475 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 12476 verifierUser.getIdentifier()); 12477 if (!origin.existing && requiredUid != -1 12478 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 12479 final Intent verification = new Intent( 12480 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 12481 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 12482 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 12483 PACKAGE_MIME_TYPE); 12484 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 12485 12486 // Query all live verifiers based on current user state 12487 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 12488 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 12489 12490 if (DEBUG_VERIFY) { 12491 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 12492 + verification.toString() + " with " + pkgLite.verifiers.length 12493 + " optional verifiers"); 12494 } 12495 12496 final int verificationId = mPendingVerificationToken++; 12497 12498 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 12499 12500 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 12501 installerPackageName); 12502 12503 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 12504 installFlags); 12505 12506 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 12507 pkgLite.packageName); 12508 12509 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 12510 pkgLite.versionCode); 12511 12512 if (verificationInfo != null) { 12513 if (verificationInfo.originatingUri != null) { 12514 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 12515 verificationInfo.originatingUri); 12516 } 12517 if (verificationInfo.referrer != null) { 12518 verification.putExtra(Intent.EXTRA_REFERRER, 12519 verificationInfo.referrer); 12520 } 12521 if (verificationInfo.originatingUid >= 0) { 12522 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 12523 verificationInfo.originatingUid); 12524 } 12525 if (verificationInfo.installerUid >= 0) { 12526 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 12527 verificationInfo.installerUid); 12528 } 12529 } 12530 12531 final PackageVerificationState verificationState = new PackageVerificationState( 12532 requiredUid, args); 12533 12534 mPendingVerification.append(verificationId, verificationState); 12535 12536 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 12537 receivers, verificationState); 12538 12539 /* 12540 * If any sufficient verifiers were listed in the package 12541 * manifest, attempt to ask them. 12542 */ 12543 if (sufficientVerifiers != null) { 12544 final int N = sufficientVerifiers.size(); 12545 if (N == 0) { 12546 Slog.i(TAG, "Additional verifiers required, but none installed."); 12547 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 12548 } else { 12549 for (int i = 0; i < N; i++) { 12550 final ComponentName verifierComponent = sufficientVerifiers.get(i); 12551 12552 final Intent sufficientIntent = new Intent(verification); 12553 sufficientIntent.setComponent(verifierComponent); 12554 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 12555 } 12556 } 12557 } 12558 12559 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 12560 mRequiredVerifierPackage, receivers); 12561 if (ret == PackageManager.INSTALL_SUCCEEDED 12562 && mRequiredVerifierPackage != null) { 12563 Trace.asyncTraceBegin( 12564 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 12565 /* 12566 * Send the intent to the required verification agent, 12567 * but only start the verification timeout after the 12568 * target BroadcastReceivers have run. 12569 */ 12570 verification.setComponent(requiredVerifierComponent); 12571 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 12572 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12573 new BroadcastReceiver() { 12574 @Override 12575 public void onReceive(Context context, Intent intent) { 12576 final Message msg = mHandler 12577 .obtainMessage(CHECK_PENDING_VERIFICATION); 12578 msg.arg1 = verificationId; 12579 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 12580 } 12581 }, null, 0, null, null); 12582 12583 /* 12584 * We don't want the copy to proceed until verification 12585 * succeeds, so null out this field. 12586 */ 12587 mArgs = null; 12588 } 12589 } else { 12590 /* 12591 * No package verification is enabled, so immediately start 12592 * the remote call to initiate copy using temporary file. 12593 */ 12594 ret = args.copyApk(mContainerService, true); 12595 } 12596 } 12597 12598 mRet = ret; 12599 } 12600 12601 @Override 12602 void handleReturnCode() { 12603 // If mArgs is null, then MCS couldn't be reached. When it 12604 // reconnects, it will try again to install. At that point, this 12605 // will succeed. 12606 if (mArgs != null) { 12607 processPendingInstall(mArgs, mRet); 12608 } 12609 } 12610 12611 @Override 12612 void handleServiceError() { 12613 mArgs = createInstallArgs(this); 12614 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12615 } 12616 12617 public boolean isForwardLocked() { 12618 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12619 } 12620 } 12621 12622 /** 12623 * Used during creation of InstallArgs 12624 * 12625 * @param installFlags package installation flags 12626 * @return true if should be installed on external storage 12627 */ 12628 private static boolean installOnExternalAsec(int installFlags) { 12629 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 12630 return false; 12631 } 12632 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 12633 return true; 12634 } 12635 return false; 12636 } 12637 12638 /** 12639 * Used during creation of InstallArgs 12640 * 12641 * @param installFlags package installation flags 12642 * @return true if should be installed as forward locked 12643 */ 12644 private static boolean installForwardLocked(int installFlags) { 12645 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12646 } 12647 12648 private InstallArgs createInstallArgs(InstallParams params) { 12649 if (params.move != null) { 12650 return new MoveInstallArgs(params); 12651 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 12652 return new AsecInstallArgs(params); 12653 } else { 12654 return new FileInstallArgs(params); 12655 } 12656 } 12657 12658 /** 12659 * Create args that describe an existing installed package. Typically used 12660 * when cleaning up old installs, or used as a move source. 12661 */ 12662 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 12663 String resourcePath, String[] instructionSets) { 12664 final boolean isInAsec; 12665 if (installOnExternalAsec(installFlags)) { 12666 /* Apps on SD card are always in ASEC containers. */ 12667 isInAsec = true; 12668 } else if (installForwardLocked(installFlags) 12669 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 12670 /* 12671 * Forward-locked apps are only in ASEC containers if they're the 12672 * new style 12673 */ 12674 isInAsec = true; 12675 } else { 12676 isInAsec = false; 12677 } 12678 12679 if (isInAsec) { 12680 return new AsecInstallArgs(codePath, instructionSets, 12681 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 12682 } else { 12683 return new FileInstallArgs(codePath, resourcePath, instructionSets); 12684 } 12685 } 12686 12687 static abstract class InstallArgs { 12688 /** @see InstallParams#origin */ 12689 final OriginInfo origin; 12690 /** @see InstallParams#move */ 12691 final MoveInfo move; 12692 12693 final IPackageInstallObserver2 observer; 12694 // Always refers to PackageManager flags only 12695 final int installFlags; 12696 final String installerPackageName; 12697 final String volumeUuid; 12698 final UserHandle user; 12699 final String abiOverride; 12700 final String[] installGrantPermissions; 12701 /** If non-null, drop an async trace when the install completes */ 12702 final String traceMethod; 12703 final int traceCookie; 12704 final Certificate[][] certificates; 12705 12706 // The list of instruction sets supported by this app. This is currently 12707 // only used during the rmdex() phase to clean up resources. We can get rid of this 12708 // if we move dex files under the common app path. 12709 /* nullable */ String[] instructionSets; 12710 12711 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12712 int installFlags, String installerPackageName, String volumeUuid, 12713 UserHandle user, String[] instructionSets, 12714 String abiOverride, String[] installGrantPermissions, 12715 String traceMethod, int traceCookie, Certificate[][] certificates) { 12716 this.origin = origin; 12717 this.move = move; 12718 this.installFlags = installFlags; 12719 this.observer = observer; 12720 this.installerPackageName = installerPackageName; 12721 this.volumeUuid = volumeUuid; 12722 this.user = user; 12723 this.instructionSets = instructionSets; 12724 this.abiOverride = abiOverride; 12725 this.installGrantPermissions = installGrantPermissions; 12726 this.traceMethod = traceMethod; 12727 this.traceCookie = traceCookie; 12728 this.certificates = certificates; 12729 } 12730 12731 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 12732 abstract int doPreInstall(int status); 12733 12734 /** 12735 * Rename package into final resting place. All paths on the given 12736 * scanned package should be updated to reflect the rename. 12737 */ 12738 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 12739 abstract int doPostInstall(int status, int uid); 12740 12741 /** @see PackageSettingBase#codePathString */ 12742 abstract String getCodePath(); 12743 /** @see PackageSettingBase#resourcePathString */ 12744 abstract String getResourcePath(); 12745 12746 // Need installer lock especially for dex file removal. 12747 abstract void cleanUpResourcesLI(); 12748 abstract boolean doPostDeleteLI(boolean delete); 12749 12750 /** 12751 * Called before the source arguments are copied. This is used mostly 12752 * for MoveParams when it needs to read the source file to put it in the 12753 * destination. 12754 */ 12755 int doPreCopy() { 12756 return PackageManager.INSTALL_SUCCEEDED; 12757 } 12758 12759 /** 12760 * Called after the source arguments are copied. This is used mostly for 12761 * MoveParams when it needs to read the source file to put it in the 12762 * destination. 12763 */ 12764 int doPostCopy(int uid) { 12765 return PackageManager.INSTALL_SUCCEEDED; 12766 } 12767 12768 protected boolean isFwdLocked() { 12769 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12770 } 12771 12772 protected boolean isExternalAsec() { 12773 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12774 } 12775 12776 protected boolean isEphemeral() { 12777 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12778 } 12779 12780 UserHandle getUser() { 12781 return user; 12782 } 12783 } 12784 12785 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 12786 if (!allCodePaths.isEmpty()) { 12787 if (instructionSets == null) { 12788 throw new IllegalStateException("instructionSet == null"); 12789 } 12790 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 12791 for (String codePath : allCodePaths) { 12792 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 12793 try { 12794 mInstaller.rmdex(codePath, dexCodeInstructionSet); 12795 } catch (InstallerException ignored) { 12796 } 12797 } 12798 } 12799 } 12800 } 12801 12802 /** 12803 * Logic to handle installation of non-ASEC applications, including copying 12804 * and renaming logic. 12805 */ 12806 class FileInstallArgs extends InstallArgs { 12807 private File codeFile; 12808 private File resourceFile; 12809 12810 // Example topology: 12811 // /data/app/com.example/base.apk 12812 // /data/app/com.example/split_foo.apk 12813 // /data/app/com.example/lib/arm/libfoo.so 12814 // /data/app/com.example/lib/arm64/libfoo.so 12815 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 12816 12817 /** New install */ 12818 FileInstallArgs(InstallParams params) { 12819 super(params.origin, params.move, params.observer, params.installFlags, 12820 params.installerPackageName, params.volumeUuid, 12821 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 12822 params.grantedRuntimePermissions, 12823 params.traceMethod, params.traceCookie, params.certificates); 12824 if (isFwdLocked()) { 12825 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 12826 } 12827 } 12828 12829 /** Existing install */ 12830 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 12831 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 12832 null, null, null, 0, null /*certificates*/); 12833 this.codeFile = (codePath != null) ? new File(codePath) : null; 12834 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 12835 } 12836 12837 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12838 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 12839 try { 12840 return doCopyApk(imcs, temp); 12841 } finally { 12842 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12843 } 12844 } 12845 12846 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12847 if (origin.staged) { 12848 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 12849 codeFile = origin.file; 12850 resourceFile = origin.file; 12851 return PackageManager.INSTALL_SUCCEEDED; 12852 } 12853 12854 try { 12855 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12856 final File tempDir = 12857 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 12858 codeFile = tempDir; 12859 resourceFile = tempDir; 12860 } catch (IOException e) { 12861 Slog.w(TAG, "Failed to create copy file: " + e); 12862 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12863 } 12864 12865 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 12866 @Override 12867 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 12868 if (!FileUtils.isValidExtFilename(name)) { 12869 throw new IllegalArgumentException("Invalid filename: " + name); 12870 } 12871 try { 12872 final File file = new File(codeFile, name); 12873 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 12874 O_RDWR | O_CREAT, 0644); 12875 Os.chmod(file.getAbsolutePath(), 0644); 12876 return new ParcelFileDescriptor(fd); 12877 } catch (ErrnoException e) { 12878 throw new RemoteException("Failed to open: " + e.getMessage()); 12879 } 12880 } 12881 }; 12882 12883 int ret = PackageManager.INSTALL_SUCCEEDED; 12884 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 12885 if (ret != PackageManager.INSTALL_SUCCEEDED) { 12886 Slog.e(TAG, "Failed to copy package"); 12887 return ret; 12888 } 12889 12890 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 12891 NativeLibraryHelper.Handle handle = null; 12892 try { 12893 handle = NativeLibraryHelper.Handle.create(codeFile); 12894 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 12895 abiOverride); 12896 } catch (IOException e) { 12897 Slog.e(TAG, "Copying native libraries failed", e); 12898 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12899 } finally { 12900 IoUtils.closeQuietly(handle); 12901 } 12902 12903 return ret; 12904 } 12905 12906 int doPreInstall(int status) { 12907 if (status != PackageManager.INSTALL_SUCCEEDED) { 12908 cleanUp(); 12909 } 12910 return status; 12911 } 12912 12913 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 12914 if (status != PackageManager.INSTALL_SUCCEEDED) { 12915 cleanUp(); 12916 return false; 12917 } 12918 12919 final File targetDir = codeFile.getParentFile(); 12920 final File beforeCodeFile = codeFile; 12921 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 12922 12923 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 12924 try { 12925 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 12926 } catch (ErrnoException e) { 12927 Slog.w(TAG, "Failed to rename", e); 12928 return false; 12929 } 12930 12931 if (!SELinux.restoreconRecursive(afterCodeFile)) { 12932 Slog.w(TAG, "Failed to restorecon"); 12933 return false; 12934 } 12935 12936 // Reflect the rename internally 12937 codeFile = afterCodeFile; 12938 resourceFile = afterCodeFile; 12939 12940 // Reflect the rename in scanned details 12941 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 12942 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 12943 afterCodeFile, pkg.baseCodePath)); 12944 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 12945 afterCodeFile, pkg.splitCodePaths)); 12946 12947 // Reflect the rename in app info 12948 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 12949 pkg.setApplicationInfoCodePath(pkg.codePath); 12950 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 12951 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 12952 pkg.setApplicationInfoResourcePath(pkg.codePath); 12953 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 12954 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 12955 12956 return true; 12957 } 12958 12959 int doPostInstall(int status, int uid) { 12960 if (status != PackageManager.INSTALL_SUCCEEDED) { 12961 cleanUp(); 12962 } 12963 return status; 12964 } 12965 12966 @Override 12967 String getCodePath() { 12968 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 12969 } 12970 12971 @Override 12972 String getResourcePath() { 12973 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 12974 } 12975 12976 private boolean cleanUp() { 12977 if (codeFile == null || !codeFile.exists()) { 12978 return false; 12979 } 12980 12981 removeCodePathLI(codeFile); 12982 12983 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 12984 resourceFile.delete(); 12985 } 12986 12987 return true; 12988 } 12989 12990 void cleanUpResourcesLI() { 12991 // Try enumerating all code paths before deleting 12992 List<String> allCodePaths = Collections.EMPTY_LIST; 12993 if (codeFile != null && codeFile.exists()) { 12994 try { 12995 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 12996 allCodePaths = pkg.getAllCodePaths(); 12997 } catch (PackageParserException e) { 12998 // Ignored; we tried our best 12999 } 13000 } 13001 13002 cleanUp(); 13003 removeDexFiles(allCodePaths, instructionSets); 13004 } 13005 13006 boolean doPostDeleteLI(boolean delete) { 13007 // XXX err, shouldn't we respect the delete flag? 13008 cleanUpResourcesLI(); 13009 return true; 13010 } 13011 } 13012 13013 private boolean isAsecExternal(String cid) { 13014 final String asecPath = PackageHelper.getSdFilesystem(cid); 13015 return !asecPath.startsWith(mAsecInternalPath); 13016 } 13017 13018 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 13019 PackageManagerException { 13020 if (copyRet < 0) { 13021 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 13022 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 13023 throw new PackageManagerException(copyRet, message); 13024 } 13025 } 13026 } 13027 13028 /** 13029 * Extract the MountService "container ID" from the full code path of an 13030 * .apk. 13031 */ 13032 static String cidFromCodePath(String fullCodePath) { 13033 int eidx = fullCodePath.lastIndexOf("/"); 13034 String subStr1 = fullCodePath.substring(0, eidx); 13035 int sidx = subStr1.lastIndexOf("/"); 13036 return subStr1.substring(sidx+1, eidx); 13037 } 13038 13039 /** 13040 * Logic to handle installation of ASEC applications, including copying and 13041 * renaming logic. 13042 */ 13043 class AsecInstallArgs extends InstallArgs { 13044 static final String RES_FILE_NAME = "pkg.apk"; 13045 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 13046 13047 String cid; 13048 String packagePath; 13049 String resourcePath; 13050 13051 /** New install */ 13052 AsecInstallArgs(InstallParams params) { 13053 super(params.origin, params.move, params.observer, params.installFlags, 13054 params.installerPackageName, params.volumeUuid, 13055 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13056 params.grantedRuntimePermissions, 13057 params.traceMethod, params.traceCookie, params.certificates); 13058 } 13059 13060 /** Existing install */ 13061 AsecInstallArgs(String fullCodePath, String[] instructionSets, 13062 boolean isExternal, boolean isForwardLocked) { 13063 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 13064 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13065 instructionSets, null, null, null, 0, null /*certificates*/); 13066 // Hackily pretend we're still looking at a full code path 13067 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 13068 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 13069 } 13070 13071 // Extract cid from fullCodePath 13072 int eidx = fullCodePath.lastIndexOf("/"); 13073 String subStr1 = fullCodePath.substring(0, eidx); 13074 int sidx = subStr1.lastIndexOf("/"); 13075 cid = subStr1.substring(sidx+1, eidx); 13076 setMountPath(subStr1); 13077 } 13078 13079 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 13080 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 13081 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13082 instructionSets, null, null, null, 0, null /*certificates*/); 13083 this.cid = cid; 13084 setMountPath(PackageHelper.getSdDir(cid)); 13085 } 13086 13087 void createCopyFile() { 13088 cid = mInstallerService.allocateExternalStageCidLegacy(); 13089 } 13090 13091 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13092 if (origin.staged && origin.cid != null) { 13093 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 13094 cid = origin.cid; 13095 setMountPath(PackageHelper.getSdDir(cid)); 13096 return PackageManager.INSTALL_SUCCEEDED; 13097 } 13098 13099 if (temp) { 13100 createCopyFile(); 13101 } else { 13102 /* 13103 * Pre-emptively destroy the container since it's destroyed if 13104 * copying fails due to it existing anyway. 13105 */ 13106 PackageHelper.destroySdDir(cid); 13107 } 13108 13109 final String newMountPath = imcs.copyPackageToContainer( 13110 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 13111 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 13112 13113 if (newMountPath != null) { 13114 setMountPath(newMountPath); 13115 return PackageManager.INSTALL_SUCCEEDED; 13116 } else { 13117 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13118 } 13119 } 13120 13121 @Override 13122 String getCodePath() { 13123 return packagePath; 13124 } 13125 13126 @Override 13127 String getResourcePath() { 13128 return resourcePath; 13129 } 13130 13131 int doPreInstall(int status) { 13132 if (status != PackageManager.INSTALL_SUCCEEDED) { 13133 // Destroy container 13134 PackageHelper.destroySdDir(cid); 13135 } else { 13136 boolean mounted = PackageHelper.isContainerMounted(cid); 13137 if (!mounted) { 13138 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 13139 Process.SYSTEM_UID); 13140 if (newMountPath != null) { 13141 setMountPath(newMountPath); 13142 } else { 13143 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13144 } 13145 } 13146 } 13147 return status; 13148 } 13149 13150 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13151 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 13152 String newMountPath = null; 13153 if (PackageHelper.isContainerMounted(cid)) { 13154 // Unmount the container 13155 if (!PackageHelper.unMountSdDir(cid)) { 13156 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 13157 return false; 13158 } 13159 } 13160 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13161 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 13162 " which might be stale. Will try to clean up."); 13163 // Clean up the stale container and proceed to recreate. 13164 if (!PackageHelper.destroySdDir(newCacheId)) { 13165 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 13166 return false; 13167 } 13168 // Successfully cleaned up stale container. Try to rename again. 13169 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13170 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 13171 + " inspite of cleaning it up."); 13172 return false; 13173 } 13174 } 13175 if (!PackageHelper.isContainerMounted(newCacheId)) { 13176 Slog.w(TAG, "Mounting container " + newCacheId); 13177 newMountPath = PackageHelper.mountSdDir(newCacheId, 13178 getEncryptKey(), Process.SYSTEM_UID); 13179 } else { 13180 newMountPath = PackageHelper.getSdDir(newCacheId); 13181 } 13182 if (newMountPath == null) { 13183 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 13184 return false; 13185 } 13186 Log.i(TAG, "Succesfully renamed " + cid + 13187 " to " + newCacheId + 13188 " at new path: " + newMountPath); 13189 cid = newCacheId; 13190 13191 final File beforeCodeFile = new File(packagePath); 13192 setMountPath(newMountPath); 13193 final File afterCodeFile = new File(packagePath); 13194 13195 // Reflect the rename in scanned details 13196 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13197 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13198 afterCodeFile, pkg.baseCodePath)); 13199 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13200 afterCodeFile, pkg.splitCodePaths)); 13201 13202 // Reflect the rename in app info 13203 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13204 pkg.setApplicationInfoCodePath(pkg.codePath); 13205 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13206 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13207 pkg.setApplicationInfoResourcePath(pkg.codePath); 13208 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13209 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13210 13211 return true; 13212 } 13213 13214 private void setMountPath(String mountPath) { 13215 final File mountFile = new File(mountPath); 13216 13217 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 13218 if (monolithicFile.exists()) { 13219 packagePath = monolithicFile.getAbsolutePath(); 13220 if (isFwdLocked()) { 13221 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 13222 } else { 13223 resourcePath = packagePath; 13224 } 13225 } else { 13226 packagePath = mountFile.getAbsolutePath(); 13227 resourcePath = packagePath; 13228 } 13229 } 13230 13231 int doPostInstall(int status, int uid) { 13232 if (status != PackageManager.INSTALL_SUCCEEDED) { 13233 cleanUp(); 13234 } else { 13235 final int groupOwner; 13236 final String protectedFile; 13237 if (isFwdLocked()) { 13238 groupOwner = UserHandle.getSharedAppGid(uid); 13239 protectedFile = RES_FILE_NAME; 13240 } else { 13241 groupOwner = -1; 13242 protectedFile = null; 13243 } 13244 13245 if (uid < Process.FIRST_APPLICATION_UID 13246 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 13247 Slog.e(TAG, "Failed to finalize " + cid); 13248 PackageHelper.destroySdDir(cid); 13249 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13250 } 13251 13252 boolean mounted = PackageHelper.isContainerMounted(cid); 13253 if (!mounted) { 13254 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 13255 } 13256 } 13257 return status; 13258 } 13259 13260 private void cleanUp() { 13261 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 13262 13263 // Destroy secure container 13264 PackageHelper.destroySdDir(cid); 13265 } 13266 13267 private List<String> getAllCodePaths() { 13268 final File codeFile = new File(getCodePath()); 13269 if (codeFile != null && codeFile.exists()) { 13270 try { 13271 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13272 return pkg.getAllCodePaths(); 13273 } catch (PackageParserException e) { 13274 // Ignored; we tried our best 13275 } 13276 } 13277 return Collections.EMPTY_LIST; 13278 } 13279 13280 void cleanUpResourcesLI() { 13281 // Enumerate all code paths before deleting 13282 cleanUpResourcesLI(getAllCodePaths()); 13283 } 13284 13285 private void cleanUpResourcesLI(List<String> allCodePaths) { 13286 cleanUp(); 13287 removeDexFiles(allCodePaths, instructionSets); 13288 } 13289 13290 String getPackageName() { 13291 return getAsecPackageName(cid); 13292 } 13293 13294 boolean doPostDeleteLI(boolean delete) { 13295 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 13296 final List<String> allCodePaths = getAllCodePaths(); 13297 boolean mounted = PackageHelper.isContainerMounted(cid); 13298 if (mounted) { 13299 // Unmount first 13300 if (PackageHelper.unMountSdDir(cid)) { 13301 mounted = false; 13302 } 13303 } 13304 if (!mounted && delete) { 13305 cleanUpResourcesLI(allCodePaths); 13306 } 13307 return !mounted; 13308 } 13309 13310 @Override 13311 int doPreCopy() { 13312 if (isFwdLocked()) { 13313 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 13314 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 13315 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13316 } 13317 } 13318 13319 return PackageManager.INSTALL_SUCCEEDED; 13320 } 13321 13322 @Override 13323 int doPostCopy(int uid) { 13324 if (isFwdLocked()) { 13325 if (uid < Process.FIRST_APPLICATION_UID 13326 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 13327 RES_FILE_NAME)) { 13328 Slog.e(TAG, "Failed to finalize " + cid); 13329 PackageHelper.destroySdDir(cid); 13330 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13331 } 13332 } 13333 13334 return PackageManager.INSTALL_SUCCEEDED; 13335 } 13336 } 13337 13338 /** 13339 * Logic to handle movement of existing installed applications. 13340 */ 13341 class MoveInstallArgs extends InstallArgs { 13342 private File codeFile; 13343 private File resourceFile; 13344 13345 /** New install */ 13346 MoveInstallArgs(InstallParams params) { 13347 super(params.origin, params.move, params.observer, params.installFlags, 13348 params.installerPackageName, params.volumeUuid, 13349 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13350 params.grantedRuntimePermissions, 13351 params.traceMethod, params.traceCookie, params.certificates); 13352 } 13353 13354 int copyApk(IMediaContainerService imcs, boolean temp) { 13355 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 13356 + move.fromUuid + " to " + move.toUuid); 13357 synchronized (mInstaller) { 13358 try { 13359 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 13360 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 13361 } catch (InstallerException e) { 13362 Slog.w(TAG, "Failed to move app", e); 13363 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13364 } 13365 } 13366 13367 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 13368 resourceFile = codeFile; 13369 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 13370 13371 return PackageManager.INSTALL_SUCCEEDED; 13372 } 13373 13374 int doPreInstall(int status) { 13375 if (status != PackageManager.INSTALL_SUCCEEDED) { 13376 cleanUp(move.toUuid); 13377 } 13378 return status; 13379 } 13380 13381 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13382 if (status != PackageManager.INSTALL_SUCCEEDED) { 13383 cleanUp(move.toUuid); 13384 return false; 13385 } 13386 13387 // Reflect the move in app info 13388 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13389 pkg.setApplicationInfoCodePath(pkg.codePath); 13390 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13391 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13392 pkg.setApplicationInfoResourcePath(pkg.codePath); 13393 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13394 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13395 13396 return true; 13397 } 13398 13399 int doPostInstall(int status, int uid) { 13400 if (status == PackageManager.INSTALL_SUCCEEDED) { 13401 cleanUp(move.fromUuid); 13402 } else { 13403 cleanUp(move.toUuid); 13404 } 13405 return status; 13406 } 13407 13408 @Override 13409 String getCodePath() { 13410 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13411 } 13412 13413 @Override 13414 String getResourcePath() { 13415 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13416 } 13417 13418 private boolean cleanUp(String volumeUuid) { 13419 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 13420 move.dataAppName); 13421 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 13422 synchronized (mInstallLock) { 13423 // Clean up both app data and code 13424 // All package moves are frozen until finished 13425 try { 13426 mInstaller.destroyAppData(volumeUuid, move.packageName, UserHandle.USER_ALL, 13427 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 13428 } catch (InstallerException e) { 13429 Slog.w(TAG, String.valueOf(e)); 13430 } 13431 removeCodePathLI(codeFile); 13432 } 13433 return true; 13434 } 13435 13436 void cleanUpResourcesLI() { 13437 throw new UnsupportedOperationException(); 13438 } 13439 13440 boolean doPostDeleteLI(boolean delete) { 13441 throw new UnsupportedOperationException(); 13442 } 13443 } 13444 13445 static String getAsecPackageName(String packageCid) { 13446 int idx = packageCid.lastIndexOf("-"); 13447 if (idx == -1) { 13448 return packageCid; 13449 } 13450 return packageCid.substring(0, idx); 13451 } 13452 13453 // Utility method used to create code paths based on package name and available index. 13454 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 13455 String idxStr = ""; 13456 int idx = 1; 13457 // Fall back to default value of idx=1 if prefix is not 13458 // part of oldCodePath 13459 if (oldCodePath != null) { 13460 String subStr = oldCodePath; 13461 // Drop the suffix right away 13462 if (suffix != null && subStr.endsWith(suffix)) { 13463 subStr = subStr.substring(0, subStr.length() - suffix.length()); 13464 } 13465 // If oldCodePath already contains prefix find out the 13466 // ending index to either increment or decrement. 13467 int sidx = subStr.lastIndexOf(prefix); 13468 if (sidx != -1) { 13469 subStr = subStr.substring(sidx + prefix.length()); 13470 if (subStr != null) { 13471 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 13472 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 13473 } 13474 try { 13475 idx = Integer.parseInt(subStr); 13476 if (idx <= 1) { 13477 idx++; 13478 } else { 13479 idx--; 13480 } 13481 } catch(NumberFormatException e) { 13482 } 13483 } 13484 } 13485 } 13486 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 13487 return prefix + idxStr; 13488 } 13489 13490 private File getNextCodePath(File targetDir, String packageName) { 13491 int suffix = 1; 13492 File result; 13493 do { 13494 result = new File(targetDir, packageName + "-" + suffix); 13495 suffix++; 13496 } while (result.exists()); 13497 return result; 13498 } 13499 13500 // Utility method that returns the relative package path with respect 13501 // to the installation directory. Like say for /data/data/com.test-1.apk 13502 // string com.test-1 is returned. 13503 static String deriveCodePathName(String codePath) { 13504 if (codePath == null) { 13505 return null; 13506 } 13507 final File codeFile = new File(codePath); 13508 final String name = codeFile.getName(); 13509 if (codeFile.isDirectory()) { 13510 return name; 13511 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 13512 final int lastDot = name.lastIndexOf('.'); 13513 return name.substring(0, lastDot); 13514 } else { 13515 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 13516 return null; 13517 } 13518 } 13519 13520 static class PackageInstalledInfo { 13521 String name; 13522 int uid; 13523 // The set of users that originally had this package installed. 13524 int[] origUsers; 13525 // The set of users that now have this package installed. 13526 int[] newUsers; 13527 PackageParser.Package pkg; 13528 int returnCode; 13529 String returnMsg; 13530 PackageRemovedInfo removedInfo; 13531 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 13532 13533 public void setError(int code, String msg) { 13534 setReturnCode(code); 13535 setReturnMessage(msg); 13536 Slog.w(TAG, msg); 13537 } 13538 13539 public void setError(String msg, PackageParserException e) { 13540 setReturnCode(e.error); 13541 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13542 Slog.w(TAG, msg, e); 13543 } 13544 13545 public void setError(String msg, PackageManagerException e) { 13546 returnCode = e.error; 13547 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13548 Slog.w(TAG, msg, e); 13549 } 13550 13551 public void setReturnCode(int returnCode) { 13552 this.returnCode = returnCode; 13553 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13554 for (int i = 0; i < childCount; i++) { 13555 addedChildPackages.valueAt(i).returnCode = returnCode; 13556 } 13557 } 13558 13559 private void setReturnMessage(String returnMsg) { 13560 this.returnMsg = returnMsg; 13561 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13562 for (int i = 0; i < childCount; i++) { 13563 addedChildPackages.valueAt(i).returnMsg = returnMsg; 13564 } 13565 } 13566 13567 // In some error cases we want to convey more info back to the observer 13568 String origPackage; 13569 String origPermission; 13570 } 13571 13572 /* 13573 * Install a non-existing package. 13574 */ 13575 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 13576 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 13577 PackageInstalledInfo res) { 13578 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 13579 13580 // Remember this for later, in case we need to rollback this install 13581 String pkgName = pkg.packageName; 13582 13583 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 13584 13585 synchronized(mPackages) { 13586 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 13587 // A package with the same name is already installed, though 13588 // it has been renamed to an older name. The package we 13589 // are trying to install should be installed as an update to 13590 // the existing one, but that has not been requested, so bail. 13591 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13592 + " without first uninstalling package running as " 13593 + mSettings.mRenamedPackages.get(pkgName)); 13594 return; 13595 } 13596 if (mPackages.containsKey(pkgName)) { 13597 // Don't allow installation over an existing package with the same name. 13598 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13599 + " without first uninstalling."); 13600 return; 13601 } 13602 } 13603 13604 try { 13605 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 13606 System.currentTimeMillis(), user); 13607 13608 updateSettingsLI(newPackage, installerPackageName, null, res, user); 13609 13610 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13611 prepareAppDataAfterInstallLIF(newPackage); 13612 13613 } else { 13614 // Remove package from internal structures, but keep around any 13615 // data that might have already existed 13616 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 13617 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 13618 } 13619 } catch (PackageManagerException e) { 13620 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13621 } 13622 13623 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13624 } 13625 13626 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 13627 // Can't rotate keys during boot or if sharedUser. 13628 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 13629 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 13630 return false; 13631 } 13632 // app is using upgradeKeySets; make sure all are valid 13633 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13634 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 13635 for (int i = 0; i < upgradeKeySets.length; i++) { 13636 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 13637 Slog.wtf(TAG, "Package " 13638 + (oldPs.name != null ? oldPs.name : "<null>") 13639 + " contains upgrade-key-set reference to unknown key-set: " 13640 + upgradeKeySets[i] 13641 + " reverting to signatures check."); 13642 return false; 13643 } 13644 } 13645 return true; 13646 } 13647 13648 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 13649 // Upgrade keysets are being used. Determine if new package has a superset of the 13650 // required keys. 13651 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 13652 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13653 for (int i = 0; i < upgradeKeySets.length; i++) { 13654 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 13655 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 13656 return true; 13657 } 13658 } 13659 return false; 13660 } 13661 13662 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 13663 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 13664 final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 13665 13666 final PackageParser.Package oldPackage; 13667 final String pkgName = pkg.packageName; 13668 final int[] allUsers; 13669 13670 // First find the old package info and check signatures 13671 synchronized(mPackages) { 13672 oldPackage = mPackages.get(pkgName); 13673 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 13674 if (isEphemeral && !oldIsEphemeral) { 13675 // can't downgrade from full to ephemeral 13676 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 13677 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 13678 return; 13679 } 13680 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 13681 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13682 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 13683 if (!checkUpgradeKeySetLP(ps, pkg)) { 13684 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13685 "New package not signed by keys specified by upgrade-keysets: " 13686 + pkgName); 13687 return; 13688 } 13689 } else { 13690 // default to original signature matching 13691 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 13692 != PackageManager.SIGNATURE_MATCH) { 13693 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13694 "New package has a different signature: " + pkgName); 13695 return; 13696 } 13697 } 13698 13699 // Check for shared user id changes 13700 String invalidPackageName = 13701 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 13702 if (invalidPackageName != null) { 13703 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 13704 "Package " + invalidPackageName + " tried to change user " 13705 + oldPackage.mSharedUserId); 13706 return; 13707 } 13708 13709 // In case of rollback, remember per-user/profile install state 13710 allUsers = sUserManager.getUserIds(); 13711 } 13712 13713 // Update what is removed 13714 res.removedInfo = new PackageRemovedInfo(); 13715 res.removedInfo.uid = oldPackage.applicationInfo.uid; 13716 res.removedInfo.removedPackage = oldPackage.packageName; 13717 res.removedInfo.isUpdate = true; 13718 final int childCount = (oldPackage.childPackages != null) 13719 ? oldPackage.childPackages.size() : 0; 13720 for (int i = 0; i < childCount; i++) { 13721 boolean childPackageUpdated = false; 13722 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 13723 if (res.addedChildPackages != null) { 13724 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 13725 if (childRes != null) { 13726 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 13727 childRes.removedInfo.removedPackage = childPkg.packageName; 13728 childRes.removedInfo.isUpdate = true; 13729 childPackageUpdated = true; 13730 } 13731 } 13732 if (!childPackageUpdated) { 13733 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 13734 childRemovedRes.removedPackage = childPkg.packageName; 13735 childRemovedRes.isUpdate = false; 13736 childRemovedRes.dataRemoved = true; 13737 synchronized (mPackages) { 13738 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 13739 if (childPs != null) { 13740 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 13741 } 13742 } 13743 if (res.removedInfo.removedChildPackages == null) { 13744 res.removedInfo.removedChildPackages = new ArrayMap<>(); 13745 } 13746 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 13747 } 13748 } 13749 13750 boolean sysPkg = (isSystemApp(oldPackage)); 13751 if (sysPkg) { 13752 // Set the system/privileged flags as needed 13753 final boolean privileged = 13754 (oldPackage.applicationInfo.privateFlags 13755 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 13756 final int systemPolicyFlags = policyFlags 13757 | PackageParser.PARSE_IS_SYSTEM 13758 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 13759 13760 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 13761 user, allUsers, installerPackageName, res); 13762 } else { 13763 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 13764 user, allUsers, installerPackageName, res); 13765 } 13766 } 13767 13768 public List<String> getPreviousCodePaths(String packageName) { 13769 final PackageSetting ps = mSettings.mPackages.get(packageName); 13770 final List<String> result = new ArrayList<String>(); 13771 if (ps != null && ps.oldCodePaths != null) { 13772 result.addAll(ps.oldCodePaths); 13773 } 13774 return result; 13775 } 13776 13777 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 13778 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 13779 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 13780 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 13781 + deletedPackage); 13782 13783 String pkgName = deletedPackage.packageName; 13784 boolean deletedPkg = true; 13785 boolean addedPkg = false; 13786 boolean updatedSettings = false; 13787 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 13788 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 13789 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 13790 13791 final long origUpdateTime = (pkg.mExtras != null) 13792 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 13793 13794 // First delete the existing package while retaining the data directory 13795 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 13796 res.removedInfo, true, pkg)) { 13797 // If the existing package wasn't successfully deleted 13798 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 13799 deletedPkg = false; 13800 } else { 13801 // Successfully deleted the old package; proceed with replace. 13802 13803 // If deleted package lived in a container, give users a chance to 13804 // relinquish resources before killing. 13805 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 13806 if (DEBUG_INSTALL) { 13807 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 13808 } 13809 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 13810 final ArrayList<String> pkgList = new ArrayList<String>(1); 13811 pkgList.add(deletedPackage.applicationInfo.packageName); 13812 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 13813 } 13814 13815 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 13816 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 13817 clearAppProfilesLIF(pkg); 13818 13819 try { 13820 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 13821 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 13822 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 13823 13824 // Update the in-memory copy of the previous code paths. 13825 PackageSetting ps = mSettings.mPackages.get(pkgName); 13826 if (!killApp) { 13827 if (ps.oldCodePaths == null) { 13828 ps.oldCodePaths = new ArraySet<>(); 13829 } 13830 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 13831 if (deletedPackage.splitCodePaths != null) { 13832 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 13833 } 13834 } else { 13835 ps.oldCodePaths = null; 13836 } 13837 if (ps.childPackageNames != null) { 13838 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 13839 final String childPkgName = ps.childPackageNames.get(i); 13840 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 13841 childPs.oldCodePaths = ps.oldCodePaths; 13842 } 13843 } 13844 prepareAppDataAfterInstallLIF(newPackage); 13845 addedPkg = true; 13846 } catch (PackageManagerException e) { 13847 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13848 } 13849 } 13850 13851 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 13852 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 13853 13854 // Revert all internal state mutations and added folders for the failed install 13855 if (addedPkg) { 13856 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 13857 res.removedInfo, true, null); 13858 } 13859 13860 // Restore the old package 13861 if (deletedPkg) { 13862 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 13863 File restoreFile = new File(deletedPackage.codePath); 13864 // Parse old package 13865 boolean oldExternal = isExternal(deletedPackage); 13866 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 13867 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 13868 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 13869 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 13870 try { 13871 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 13872 null); 13873 } catch (PackageManagerException e) { 13874 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 13875 + e.getMessage()); 13876 return; 13877 } 13878 13879 synchronized (mPackages) { 13880 // Ensure the installer package name up to date 13881 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 13882 13883 // Update permissions for restored package 13884 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 13885 13886 mSettings.writeLPr(); 13887 } 13888 13889 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 13890 } 13891 } else { 13892 synchronized (mPackages) { 13893 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 13894 if (ps != null) { 13895 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 13896 if (res.removedInfo.removedChildPackages != null) { 13897 final int childCount = res.removedInfo.removedChildPackages.size(); 13898 // Iterate in reverse as we may modify the collection 13899 for (int i = childCount - 1; i >= 0; i--) { 13900 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 13901 if (res.addedChildPackages.containsKey(childPackageName)) { 13902 res.removedInfo.removedChildPackages.removeAt(i); 13903 } else { 13904 PackageRemovedInfo childInfo = res.removedInfo 13905 .removedChildPackages.valueAt(i); 13906 childInfo.removedForAllUsers = mPackages.get( 13907 childInfo.removedPackage) == null; 13908 } 13909 } 13910 } 13911 } 13912 } 13913 } 13914 } 13915 13916 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 13917 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 13918 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 13919 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 13920 + ", old=" + deletedPackage); 13921 13922 final boolean disabledSystem; 13923 13924 // Remove existing system package 13925 removePackageLI(deletedPackage, true); 13926 13927 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 13928 if (!disabledSystem) { 13929 // We didn't need to disable the .apk as a current system package, 13930 // which means we are replacing another update that is already 13931 // installed. We need to make sure to delete the older one's .apk. 13932 res.removedInfo.args = createInstallArgsForExisting(0, 13933 deletedPackage.applicationInfo.getCodePath(), 13934 deletedPackage.applicationInfo.getResourcePath(), 13935 getAppDexInstructionSets(deletedPackage.applicationInfo)); 13936 } else { 13937 res.removedInfo.args = null; 13938 } 13939 13940 // Successfully disabled the old package. Now proceed with re-installation 13941 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 13942 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 13943 clearAppProfilesLIF(pkg); 13944 13945 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 13946 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 13947 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 13948 13949 PackageParser.Package newPackage = null; 13950 try { 13951 // Add the package to the internal data structures 13952 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 13953 13954 // Set the update and install times 13955 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 13956 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 13957 System.currentTimeMillis()); 13958 13959 // Update the package dynamic state if succeeded 13960 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13961 // Now that the install succeeded make sure we remove data 13962 // directories for any child package the update removed. 13963 final int deletedChildCount = (deletedPackage.childPackages != null) 13964 ? deletedPackage.childPackages.size() : 0; 13965 final int newChildCount = (newPackage.childPackages != null) 13966 ? newPackage.childPackages.size() : 0; 13967 for (int i = 0; i < deletedChildCount; i++) { 13968 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 13969 boolean childPackageDeleted = true; 13970 for (int j = 0; j < newChildCount; j++) { 13971 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 13972 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 13973 childPackageDeleted = false; 13974 break; 13975 } 13976 } 13977 if (childPackageDeleted) { 13978 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 13979 deletedChildPkg.packageName); 13980 if (ps != null && res.removedInfo.removedChildPackages != null) { 13981 PackageRemovedInfo removedChildRes = res.removedInfo 13982 .removedChildPackages.get(deletedChildPkg.packageName); 13983 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 13984 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 13985 } 13986 } 13987 } 13988 13989 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 13990 prepareAppDataAfterInstallLIF(newPackage); 13991 } 13992 } catch (PackageManagerException e) { 13993 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 13994 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13995 } 13996 13997 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 13998 // Re installation failed. Restore old information 13999 // Remove new pkg information 14000 if (newPackage != null) { 14001 removeInstalledPackageLI(newPackage, true); 14002 } 14003 // Add back the old system package 14004 try { 14005 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 14006 } catch (PackageManagerException e) { 14007 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 14008 } 14009 14010 synchronized (mPackages) { 14011 if (disabledSystem) { 14012 enableSystemPackageLPw(deletedPackage); 14013 } 14014 14015 // Ensure the installer package name up to date 14016 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14017 14018 // Update permissions for restored package 14019 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14020 14021 mSettings.writeLPr(); 14022 } 14023 14024 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 14025 + " after failed upgrade"); 14026 } 14027 } 14028 14029 /** 14030 * Checks whether the parent or any of the child packages have a change shared 14031 * user. For a package to be a valid update the shred users of the parent and 14032 * the children should match. We may later support changing child shared users. 14033 * @param oldPkg The updated package. 14034 * @param newPkg The update package. 14035 * @return The shared user that change between the versions. 14036 */ 14037 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 14038 PackageParser.Package newPkg) { 14039 // Check parent shared user 14040 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 14041 return newPkg.packageName; 14042 } 14043 // Check child shared users 14044 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14045 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 14046 for (int i = 0; i < newChildCount; i++) { 14047 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 14048 // If this child was present, did it have the same shared user? 14049 for (int j = 0; j < oldChildCount; j++) { 14050 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 14051 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 14052 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 14053 return newChildPkg.packageName; 14054 } 14055 } 14056 } 14057 return null; 14058 } 14059 14060 private void removeNativeBinariesLI(PackageSetting ps) { 14061 // Remove the lib path for the parent package 14062 if (ps != null) { 14063 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 14064 // Remove the lib path for the child packages 14065 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 14066 for (int i = 0; i < childCount; i++) { 14067 PackageSetting childPs = null; 14068 synchronized (mPackages) { 14069 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 14070 } 14071 if (childPs != null) { 14072 NativeLibraryHelper.removeNativeBinariesLI(childPs 14073 .legacyNativeLibraryPathString); 14074 } 14075 } 14076 } 14077 } 14078 14079 private void enableSystemPackageLPw(PackageParser.Package pkg) { 14080 // Enable the parent package 14081 mSettings.enableSystemPackageLPw(pkg.packageName); 14082 // Enable the child packages 14083 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14084 for (int i = 0; i < childCount; i++) { 14085 PackageParser.Package childPkg = pkg.childPackages.get(i); 14086 mSettings.enableSystemPackageLPw(childPkg.packageName); 14087 } 14088 } 14089 14090 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 14091 PackageParser.Package newPkg) { 14092 // Disable the parent package (parent always replaced) 14093 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 14094 // Disable the child packages 14095 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14096 for (int i = 0; i < childCount; i++) { 14097 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 14098 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 14099 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 14100 } 14101 return disabled; 14102 } 14103 14104 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 14105 String installerPackageName) { 14106 // Enable the parent package 14107 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 14108 // Enable the child packages 14109 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14110 for (int i = 0; i < childCount; i++) { 14111 PackageParser.Package childPkg = pkg.childPackages.get(i); 14112 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 14113 } 14114 } 14115 14116 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 14117 // Collect all used permissions in the UID 14118 ArraySet<String> usedPermissions = new ArraySet<>(); 14119 final int packageCount = su.packages.size(); 14120 for (int i = 0; i < packageCount; i++) { 14121 PackageSetting ps = su.packages.valueAt(i); 14122 if (ps.pkg == null) { 14123 continue; 14124 } 14125 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 14126 for (int j = 0; j < requestedPermCount; j++) { 14127 String permission = ps.pkg.requestedPermissions.get(j); 14128 BasePermission bp = mSettings.mPermissions.get(permission); 14129 if (bp != null) { 14130 usedPermissions.add(permission); 14131 } 14132 } 14133 } 14134 14135 PermissionsState permissionsState = su.getPermissionsState(); 14136 // Prune install permissions 14137 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 14138 final int installPermCount = installPermStates.size(); 14139 for (int i = installPermCount - 1; i >= 0; i--) { 14140 PermissionState permissionState = installPermStates.get(i); 14141 if (!usedPermissions.contains(permissionState.getName())) { 14142 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14143 if (bp != null) { 14144 permissionsState.revokeInstallPermission(bp); 14145 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 14146 PackageManager.MASK_PERMISSION_FLAGS, 0); 14147 } 14148 } 14149 } 14150 14151 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 14152 14153 // Prune runtime permissions 14154 for (int userId : allUserIds) { 14155 List<PermissionState> runtimePermStates = permissionsState 14156 .getRuntimePermissionStates(userId); 14157 final int runtimePermCount = runtimePermStates.size(); 14158 for (int i = runtimePermCount - 1; i >= 0; i--) { 14159 PermissionState permissionState = runtimePermStates.get(i); 14160 if (!usedPermissions.contains(permissionState.getName())) { 14161 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14162 if (bp != null) { 14163 permissionsState.revokeRuntimePermission(bp, userId); 14164 permissionsState.updatePermissionFlags(bp, userId, 14165 PackageManager.MASK_PERMISSION_FLAGS, 0); 14166 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 14167 runtimePermissionChangedUserIds, userId); 14168 } 14169 } 14170 } 14171 } 14172 14173 return runtimePermissionChangedUserIds; 14174 } 14175 14176 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 14177 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 14178 // Update the parent package setting 14179 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 14180 res, user); 14181 // Update the child packages setting 14182 final int childCount = (newPackage.childPackages != null) 14183 ? newPackage.childPackages.size() : 0; 14184 for (int i = 0; i < childCount; i++) { 14185 PackageParser.Package childPackage = newPackage.childPackages.get(i); 14186 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 14187 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 14188 childRes.origUsers, childRes, user); 14189 } 14190 } 14191 14192 private void updateSettingsInternalLI(PackageParser.Package newPackage, 14193 String installerPackageName, int[] allUsers, int[] installedForUsers, 14194 PackageInstalledInfo res, UserHandle user) { 14195 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 14196 14197 String pkgName = newPackage.packageName; 14198 synchronized (mPackages) { 14199 //write settings. the installStatus will be incomplete at this stage. 14200 //note that the new package setting would have already been 14201 //added to mPackages. It hasn't been persisted yet. 14202 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 14203 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14204 mSettings.writeLPr(); 14205 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14206 } 14207 14208 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 14209 synchronized (mPackages) { 14210 updatePermissionsLPw(newPackage.packageName, newPackage, 14211 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 14212 ? UPDATE_PERMISSIONS_ALL : 0)); 14213 // For system-bundled packages, we assume that installing an upgraded version 14214 // of the package implies that the user actually wants to run that new code, 14215 // so we enable the package. 14216 PackageSetting ps = mSettings.mPackages.get(pkgName); 14217 final int userId = user.getIdentifier(); 14218 if (ps != null) { 14219 if (isSystemApp(newPackage)) { 14220 if (DEBUG_INSTALL) { 14221 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 14222 } 14223 // Enable system package for requested users 14224 if (res.origUsers != null) { 14225 for (int origUserId : res.origUsers) { 14226 if (userId == UserHandle.USER_ALL || userId == origUserId) { 14227 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 14228 origUserId, installerPackageName); 14229 } 14230 } 14231 } 14232 // Also convey the prior install/uninstall state 14233 if (allUsers != null && installedForUsers != null) { 14234 for (int currentUserId : allUsers) { 14235 final boolean installed = ArrayUtils.contains( 14236 installedForUsers, currentUserId); 14237 if (DEBUG_INSTALL) { 14238 Slog.d(TAG, " user " + currentUserId + " => " + installed); 14239 } 14240 ps.setInstalled(installed, currentUserId); 14241 } 14242 // these install state changes will be persisted in the 14243 // upcoming call to mSettings.writeLPr(). 14244 } 14245 } 14246 // It's implied that when a user requests installation, they want the app to be 14247 // installed and enabled. 14248 if (userId != UserHandle.USER_ALL) { 14249 ps.setInstalled(true, userId); 14250 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 14251 } 14252 } 14253 res.name = pkgName; 14254 res.uid = newPackage.applicationInfo.uid; 14255 res.pkg = newPackage; 14256 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 14257 mSettings.setInstallerPackageName(pkgName, installerPackageName); 14258 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14259 //to update install status 14260 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14261 mSettings.writeLPr(); 14262 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14263 } 14264 14265 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14266 } 14267 14268 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 14269 try { 14270 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 14271 installPackageLI(args, res); 14272 } finally { 14273 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14274 } 14275 } 14276 14277 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 14278 final int installFlags = args.installFlags; 14279 final String installerPackageName = args.installerPackageName; 14280 final String volumeUuid = args.volumeUuid; 14281 final File tmpPackageFile = new File(args.getCodePath()); 14282 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 14283 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 14284 || (args.volumeUuid != null)); 14285 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 14286 boolean replace = false; 14287 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 14288 if (args.move != null) { 14289 // moving a complete application; perform an initial scan on the new install location 14290 scanFlags |= SCAN_INITIAL; 14291 } 14292 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 14293 scanFlags |= SCAN_DONT_KILL_APP; 14294 } 14295 14296 // Result object to be returned 14297 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14298 14299 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 14300 14301 // Sanity check 14302 if (ephemeral && (forwardLocked || onExternal)) { 14303 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 14304 + " external=" + onExternal); 14305 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14306 return; 14307 } 14308 14309 // Retrieve PackageSettings and parse package 14310 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 14311 | PackageParser.PARSE_ENFORCE_CODE 14312 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 14313 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 14314 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0); 14315 PackageParser pp = new PackageParser(); 14316 pp.setSeparateProcesses(mSeparateProcesses); 14317 pp.setDisplayMetrics(mMetrics); 14318 14319 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 14320 final PackageParser.Package pkg; 14321 try { 14322 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 14323 } catch (PackageParserException e) { 14324 res.setError("Failed parse during installPackageLI", e); 14325 return; 14326 } finally { 14327 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14328 } 14329 14330 // If we are installing a clustered package add results for the children 14331 if (pkg.childPackages != null) { 14332 synchronized (mPackages) { 14333 final int childCount = pkg.childPackages.size(); 14334 for (int i = 0; i < childCount; i++) { 14335 PackageParser.Package childPkg = pkg.childPackages.get(i); 14336 PackageInstalledInfo childRes = new PackageInstalledInfo(); 14337 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14338 childRes.pkg = childPkg; 14339 childRes.name = childPkg.packageName; 14340 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14341 if (childPs != null) { 14342 childRes.origUsers = childPs.queryInstalledUsers( 14343 sUserManager.getUserIds(), true); 14344 } 14345 if ((mPackages.containsKey(childPkg.packageName))) { 14346 childRes.removedInfo = new PackageRemovedInfo(); 14347 childRes.removedInfo.removedPackage = childPkg.packageName; 14348 } 14349 if (res.addedChildPackages == null) { 14350 res.addedChildPackages = new ArrayMap<>(); 14351 } 14352 res.addedChildPackages.put(childPkg.packageName, childRes); 14353 } 14354 } 14355 } 14356 14357 // If package doesn't declare API override, mark that we have an install 14358 // time CPU ABI override. 14359 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 14360 pkg.cpuAbiOverride = args.abiOverride; 14361 } 14362 14363 String pkgName = res.name = pkg.packageName; 14364 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 14365 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 14366 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 14367 return; 14368 } 14369 } 14370 14371 try { 14372 // either use what we've been given or parse directly from the APK 14373 if (args.certificates != null) { 14374 try { 14375 PackageParser.populateCertificates(pkg, args.certificates); 14376 } catch (PackageParserException e) { 14377 // there was something wrong with the certificates we were given; 14378 // try to pull them from the APK 14379 PackageParser.collectCertificates(pkg, parseFlags); 14380 } 14381 } else { 14382 PackageParser.collectCertificates(pkg, parseFlags); 14383 } 14384 } catch (PackageParserException e) { 14385 res.setError("Failed collect during installPackageLI", e); 14386 return; 14387 } 14388 14389 // Get rid of all references to package scan path via parser. 14390 pp = null; 14391 String oldCodePath = null; 14392 boolean systemApp = false; 14393 synchronized (mPackages) { 14394 // Check if installing already existing package 14395 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14396 String oldName = mSettings.mRenamedPackages.get(pkgName); 14397 if (pkg.mOriginalPackages != null 14398 && pkg.mOriginalPackages.contains(oldName) 14399 && mPackages.containsKey(oldName)) { 14400 // This package is derived from an original package, 14401 // and this device has been updating from that original 14402 // name. We must continue using the original name, so 14403 // rename the new package here. 14404 pkg.setPackageName(oldName); 14405 pkgName = pkg.packageName; 14406 replace = true; 14407 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 14408 + oldName + " pkgName=" + pkgName); 14409 } else if (mPackages.containsKey(pkgName)) { 14410 // This package, under its official name, already exists 14411 // on the device; we should replace it. 14412 replace = true; 14413 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 14414 } 14415 14416 // Child packages are installed through the parent package 14417 if (pkg.parentPackage != null) { 14418 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14419 "Package " + pkg.packageName + " is child of package " 14420 + pkg.parentPackage.parentPackage + ". Child packages " 14421 + "can be updated only through the parent package."); 14422 return; 14423 } 14424 14425 if (replace) { 14426 // Prevent apps opting out from runtime permissions 14427 PackageParser.Package oldPackage = mPackages.get(pkgName); 14428 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 14429 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 14430 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 14431 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 14432 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 14433 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 14434 + " doesn't support runtime permissions but the old" 14435 + " target SDK " + oldTargetSdk + " does."); 14436 return; 14437 } 14438 14439 // Prevent installing of child packages 14440 if (oldPackage.parentPackage != null) { 14441 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14442 "Package " + pkg.packageName + " is child of package " 14443 + oldPackage.parentPackage + ". Child packages " 14444 + "can be updated only through the parent package."); 14445 return; 14446 } 14447 } 14448 } 14449 14450 PackageSetting ps = mSettings.mPackages.get(pkgName); 14451 if (ps != null) { 14452 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 14453 14454 // Quick sanity check that we're signed correctly if updating; 14455 // we'll check this again later when scanning, but we want to 14456 // bail early here before tripping over redefined permissions. 14457 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14458 if (!checkUpgradeKeySetLP(ps, pkg)) { 14459 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 14460 + pkg.packageName + " upgrade keys do not match the " 14461 + "previously installed version"); 14462 return; 14463 } 14464 } else { 14465 try { 14466 verifySignaturesLP(ps, pkg); 14467 } catch (PackageManagerException e) { 14468 res.setError(e.error, e.getMessage()); 14469 return; 14470 } 14471 } 14472 14473 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 14474 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 14475 systemApp = (ps.pkg.applicationInfo.flags & 14476 ApplicationInfo.FLAG_SYSTEM) != 0; 14477 } 14478 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14479 } 14480 14481 // Check whether the newly-scanned package wants to define an already-defined perm 14482 int N = pkg.permissions.size(); 14483 for (int i = N-1; i >= 0; i--) { 14484 PackageParser.Permission perm = pkg.permissions.get(i); 14485 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 14486 if (bp != null) { 14487 // If the defining package is signed with our cert, it's okay. This 14488 // also includes the "updating the same package" case, of course. 14489 // "updating same package" could also involve key-rotation. 14490 final boolean sigsOk; 14491 if (bp.sourcePackage.equals(pkg.packageName) 14492 && (bp.packageSetting instanceof PackageSetting) 14493 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 14494 scanFlags))) { 14495 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 14496 } else { 14497 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 14498 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 14499 } 14500 if (!sigsOk) { 14501 // If the owning package is the system itself, we log but allow 14502 // install to proceed; we fail the install on all other permission 14503 // redefinitions. 14504 if (!bp.sourcePackage.equals("android")) { 14505 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 14506 + pkg.packageName + " attempting to redeclare permission " 14507 + perm.info.name + " already owned by " + bp.sourcePackage); 14508 res.origPermission = perm.info.name; 14509 res.origPackage = bp.sourcePackage; 14510 return; 14511 } else { 14512 Slog.w(TAG, "Package " + pkg.packageName 14513 + " attempting to redeclare system permission " 14514 + perm.info.name + "; ignoring new declaration"); 14515 pkg.permissions.remove(i); 14516 } 14517 } 14518 } 14519 } 14520 } 14521 14522 if (systemApp) { 14523 if (onExternal) { 14524 // Abort update; system app can't be replaced with app on sdcard 14525 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 14526 "Cannot install updates to system apps on sdcard"); 14527 return; 14528 } else if (ephemeral) { 14529 // Abort update; system app can't be replaced with an ephemeral app 14530 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 14531 "Cannot update a system app with an ephemeral app"); 14532 return; 14533 } 14534 } 14535 14536 if (args.move != null) { 14537 // We did an in-place move, so dex is ready to roll 14538 scanFlags |= SCAN_NO_DEX; 14539 scanFlags |= SCAN_MOVE; 14540 14541 synchronized (mPackages) { 14542 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14543 if (ps == null) { 14544 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 14545 "Missing settings for moved package " + pkgName); 14546 } 14547 14548 // We moved the entire application as-is, so bring over the 14549 // previously derived ABI information. 14550 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 14551 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 14552 } 14553 14554 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 14555 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 14556 scanFlags |= SCAN_NO_DEX; 14557 14558 try { 14559 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 14560 args.abiOverride : pkg.cpuAbiOverride); 14561 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 14562 true /* extract libs */); 14563 } catch (PackageManagerException pme) { 14564 Slog.e(TAG, "Error deriving application ABI", pme); 14565 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 14566 return; 14567 } 14568 14569 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 14570 // Do not run PackageDexOptimizer through the local performDexOpt 14571 // method because `pkg` is not in `mPackages` yet. 14572 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instructionSets */, 14573 false /* checkProfiles */, getCompilerFilterForReason(REASON_INSTALL)); 14574 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14575 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 14576 String msg = "Extracting package failed for " + pkgName; 14577 res.setError(INSTALL_FAILED_DEXOPT, msg); 14578 return; 14579 } 14580 14581 // Notify BackgroundDexOptService that the package has been changed. 14582 // If this is an update of a package which used to fail to compile, 14583 // BDOS will remove it from its blacklist. 14584 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 14585 } 14586 14587 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 14588 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 14589 return; 14590 } 14591 14592 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 14593 14594 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 14595 "installPackageLI")) { 14596 if (replace) { 14597 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 14598 installerPackageName, res); 14599 } else { 14600 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 14601 args.user, installerPackageName, volumeUuid, res); 14602 } 14603 } 14604 synchronized (mPackages) { 14605 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14606 if (ps != null) { 14607 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14608 } 14609 14610 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14611 for (int i = 0; i < childCount; i++) { 14612 PackageParser.Package childPkg = pkg.childPackages.get(i); 14613 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14614 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14615 if (childPs != null) { 14616 childRes.newUsers = childPs.queryInstalledUsers( 14617 sUserManager.getUserIds(), true); 14618 } 14619 } 14620 } 14621 } 14622 14623 private void startIntentFilterVerifications(int userId, boolean replacing, 14624 PackageParser.Package pkg) { 14625 if (mIntentFilterVerifierComponent == null) { 14626 Slog.w(TAG, "No IntentFilter verification will not be done as " 14627 + "there is no IntentFilterVerifier available!"); 14628 return; 14629 } 14630 14631 final int verifierUid = getPackageUid( 14632 mIntentFilterVerifierComponent.getPackageName(), 14633 MATCH_DEBUG_TRIAGED_MISSING, 14634 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 14635 14636 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14637 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 14638 mHandler.sendMessage(msg); 14639 14640 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14641 for (int i = 0; i < childCount; i++) { 14642 PackageParser.Package childPkg = pkg.childPackages.get(i); 14643 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14644 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 14645 mHandler.sendMessage(msg); 14646 } 14647 } 14648 14649 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 14650 PackageParser.Package pkg) { 14651 int size = pkg.activities.size(); 14652 if (size == 0) { 14653 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14654 "No activity, so no need to verify any IntentFilter!"); 14655 return; 14656 } 14657 14658 final boolean hasDomainURLs = hasDomainURLs(pkg); 14659 if (!hasDomainURLs) { 14660 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14661 "No domain URLs, so no need to verify any IntentFilter!"); 14662 return; 14663 } 14664 14665 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 14666 + " if any IntentFilter from the " + size 14667 + " Activities needs verification ..."); 14668 14669 int count = 0; 14670 final String packageName = pkg.packageName; 14671 14672 synchronized (mPackages) { 14673 // If this is a new install and we see that we've already run verification for this 14674 // package, we have nothing to do: it means the state was restored from backup. 14675 if (!replacing) { 14676 IntentFilterVerificationInfo ivi = 14677 mSettings.getIntentFilterVerificationLPr(packageName); 14678 if (ivi != null) { 14679 if (DEBUG_DOMAIN_VERIFICATION) { 14680 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 14681 + ivi.getStatusString()); 14682 } 14683 return; 14684 } 14685 } 14686 14687 // If any filters need to be verified, then all need to be. 14688 boolean needToVerify = false; 14689 for (PackageParser.Activity a : pkg.activities) { 14690 for (ActivityIntentInfo filter : a.intents) { 14691 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 14692 if (DEBUG_DOMAIN_VERIFICATION) { 14693 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 14694 } 14695 needToVerify = true; 14696 break; 14697 } 14698 } 14699 } 14700 14701 if (needToVerify) { 14702 final int verificationId = mIntentFilterVerificationToken++; 14703 for (PackageParser.Activity a : pkg.activities) { 14704 for (ActivityIntentInfo filter : a.intents) { 14705 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 14706 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14707 "Verification needed for IntentFilter:" + filter.toString()); 14708 mIntentFilterVerifier.addOneIntentFilterVerification( 14709 verifierUid, userId, verificationId, filter, packageName); 14710 count++; 14711 } 14712 } 14713 } 14714 } 14715 } 14716 14717 if (count > 0) { 14718 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 14719 + " IntentFilter verification" + (count > 1 ? "s" : "") 14720 + " for userId:" + userId); 14721 mIntentFilterVerifier.startVerifications(userId); 14722 } else { 14723 if (DEBUG_DOMAIN_VERIFICATION) { 14724 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 14725 } 14726 } 14727 } 14728 14729 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 14730 final ComponentName cn = filter.activity.getComponentName(); 14731 final String packageName = cn.getPackageName(); 14732 14733 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 14734 packageName); 14735 if (ivi == null) { 14736 return true; 14737 } 14738 int status = ivi.getStatus(); 14739 switch (status) { 14740 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 14741 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 14742 return true; 14743 14744 default: 14745 // Nothing to do 14746 return false; 14747 } 14748 } 14749 14750 private static boolean isMultiArch(ApplicationInfo info) { 14751 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 14752 } 14753 14754 private static boolean isExternal(PackageParser.Package pkg) { 14755 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 14756 } 14757 14758 private static boolean isExternal(PackageSetting ps) { 14759 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 14760 } 14761 14762 private static boolean isEphemeral(PackageParser.Package pkg) { 14763 return pkg.applicationInfo.isEphemeralApp(); 14764 } 14765 14766 private static boolean isEphemeral(PackageSetting ps) { 14767 return ps.pkg != null && isEphemeral(ps.pkg); 14768 } 14769 14770 private static boolean isSystemApp(PackageParser.Package pkg) { 14771 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 14772 } 14773 14774 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 14775 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14776 } 14777 14778 private static boolean hasDomainURLs(PackageParser.Package pkg) { 14779 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 14780 } 14781 14782 private static boolean isSystemApp(PackageSetting ps) { 14783 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 14784 } 14785 14786 private static boolean isUpdatedSystemApp(PackageSetting ps) { 14787 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 14788 } 14789 14790 private int packageFlagsToInstallFlags(PackageSetting ps) { 14791 int installFlags = 0; 14792 if (isEphemeral(ps)) { 14793 installFlags |= PackageManager.INSTALL_EPHEMERAL; 14794 } 14795 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 14796 // This existing package was an external ASEC install when we have 14797 // the external flag without a UUID 14798 installFlags |= PackageManager.INSTALL_EXTERNAL; 14799 } 14800 if (ps.isForwardLocked()) { 14801 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 14802 } 14803 return installFlags; 14804 } 14805 14806 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 14807 if (isExternal(pkg)) { 14808 if (TextUtils.isEmpty(pkg.volumeUuid)) { 14809 return StorageManager.UUID_PRIMARY_PHYSICAL; 14810 } else { 14811 return pkg.volumeUuid; 14812 } 14813 } else { 14814 return StorageManager.UUID_PRIVATE_INTERNAL; 14815 } 14816 } 14817 14818 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 14819 if (isExternal(pkg)) { 14820 if (TextUtils.isEmpty(pkg.volumeUuid)) { 14821 return mSettings.getExternalVersion(); 14822 } else { 14823 return mSettings.findOrCreateVersion(pkg.volumeUuid); 14824 } 14825 } else { 14826 return mSettings.getInternalVersion(); 14827 } 14828 } 14829 14830 private void deleteTempPackageFiles() { 14831 final FilenameFilter filter = new FilenameFilter() { 14832 public boolean accept(File dir, String name) { 14833 return name.startsWith("vmdl") && name.endsWith(".tmp"); 14834 } 14835 }; 14836 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 14837 file.delete(); 14838 } 14839 } 14840 14841 @Override 14842 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 14843 int flags) { 14844 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 14845 flags); 14846 } 14847 14848 @Override 14849 public void deletePackage(final String packageName, 14850 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 14851 mContext.enforceCallingOrSelfPermission( 14852 android.Manifest.permission.DELETE_PACKAGES, null); 14853 Preconditions.checkNotNull(packageName); 14854 Preconditions.checkNotNull(observer); 14855 final int uid = Binder.getCallingUid(); 14856 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 14857 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 14858 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 14859 mContext.enforceCallingOrSelfPermission( 14860 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 14861 "deletePackage for user " + userId); 14862 } 14863 14864 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 14865 try { 14866 observer.onPackageDeleted(packageName, 14867 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 14868 } catch (RemoteException re) { 14869 } 14870 return; 14871 } 14872 14873 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 14874 try { 14875 observer.onPackageDeleted(packageName, 14876 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 14877 } catch (RemoteException re) { 14878 } 14879 return; 14880 } 14881 14882 if (DEBUG_REMOVE) { 14883 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 14884 + " deleteAllUsers: " + deleteAllUsers ); 14885 } 14886 // Queue up an async operation since the package deletion may take a little while. 14887 mHandler.post(new Runnable() { 14888 public void run() { 14889 mHandler.removeCallbacks(this); 14890 int returnCode; 14891 if (!deleteAllUsers) { 14892 returnCode = deletePackageX(packageName, userId, deleteFlags); 14893 } else { 14894 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 14895 // If nobody is blocking uninstall, proceed with delete for all users 14896 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 14897 returnCode = deletePackageX(packageName, userId, deleteFlags); 14898 } else { 14899 // Otherwise uninstall individually for users with blockUninstalls=false 14900 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 14901 for (int userId : users) { 14902 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 14903 returnCode = deletePackageX(packageName, userId, userFlags); 14904 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 14905 Slog.w(TAG, "Package delete failed for user " + userId 14906 + ", returnCode " + returnCode); 14907 } 14908 } 14909 } 14910 // The app has only been marked uninstalled for certain users. 14911 // We still need to report that delete was blocked 14912 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 14913 } 14914 } 14915 try { 14916 observer.onPackageDeleted(packageName, returnCode, null); 14917 } catch (RemoteException e) { 14918 Log.i(TAG, "Observer no longer exists."); 14919 } //end catch 14920 } //end run 14921 }); 14922 } 14923 14924 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 14925 int[] result = EMPTY_INT_ARRAY; 14926 for (int userId : userIds) { 14927 if (getBlockUninstallForUser(packageName, userId)) { 14928 result = ArrayUtils.appendInt(result, userId); 14929 } 14930 } 14931 return result; 14932 } 14933 14934 @Override 14935 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 14936 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 14937 } 14938 14939 private boolean isPackageDeviceAdmin(String packageName, int userId) { 14940 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 14941 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 14942 try { 14943 if (dpm != null) { 14944 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 14945 /* callingUserOnly =*/ false); 14946 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 14947 : deviceOwnerComponentName.getPackageName(); 14948 // Does the package contains the device owner? 14949 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 14950 // this check is probably not needed, since DO should be registered as a device 14951 // admin on some user too. (Original bug for this: b/17657954) 14952 if (packageName.equals(deviceOwnerPackageName)) { 14953 return true; 14954 } 14955 // Does it contain a device admin for any user? 14956 int[] users; 14957 if (userId == UserHandle.USER_ALL) { 14958 users = sUserManager.getUserIds(); 14959 } else { 14960 users = new int[]{userId}; 14961 } 14962 for (int i = 0; i < users.length; ++i) { 14963 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 14964 return true; 14965 } 14966 } 14967 } 14968 } catch (RemoteException e) { 14969 } 14970 return false; 14971 } 14972 14973 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 14974 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 14975 } 14976 14977 /** 14978 * This method is an internal method that could be get invoked either 14979 * to delete an installed package or to clean up a failed installation. 14980 * After deleting an installed package, a broadcast is sent to notify any 14981 * listeners that the package has been removed. For cleaning up a failed 14982 * installation, the broadcast is not necessary since the package's 14983 * installation wouldn't have sent the initial broadcast either 14984 * The key steps in deleting a package are 14985 * deleting the package information in internal structures like mPackages, 14986 * deleting the packages base directories through installd 14987 * updating mSettings to reflect current status 14988 * persisting settings for later use 14989 * sending a broadcast if necessary 14990 */ 14991 private int deletePackageX(String packageName, int userId, int deleteFlags) { 14992 final PackageRemovedInfo info = new PackageRemovedInfo(); 14993 final boolean res; 14994 14995 final UserHandle removeForUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 14996 ? UserHandle.ALL : new UserHandle(userId); 14997 14998 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 14999 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 15000 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 15001 } 15002 15003 PackageSetting uninstalledPs = null; 15004 15005 // for the uninstall-updates case and restricted profiles, remember the per- 15006 // user handle installed state 15007 int[] allUsers; 15008 synchronized (mPackages) { 15009 uninstalledPs = mSettings.mPackages.get(packageName); 15010 if (uninstalledPs == null) { 15011 Slog.w(TAG, "Not removing non-existent package " + packageName); 15012 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15013 } 15014 allUsers = sUserManager.getUserIds(); 15015 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 15016 } 15017 15018 synchronized (mInstallLock) { 15019 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 15020 try (PackageFreezer freezer = freezePackageForDelete(packageName, deleteFlags, 15021 "deletePackageX")) { 15022 res = deletePackageLIF(packageName, removeForUser, true, allUsers, 15023 deleteFlags | REMOVE_CHATTY, info, true, null); 15024 } 15025 synchronized (mPackages) { 15026 if (res) { 15027 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 15028 } 15029 } 15030 } 15031 15032 if (res) { 15033 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 15034 info.sendPackageRemovedBroadcasts(killApp); 15035 info.sendSystemPackageUpdatedBroadcasts(); 15036 info.sendSystemPackageAppearedBroadcasts(); 15037 } 15038 // Force a gc here. 15039 Runtime.getRuntime().gc(); 15040 // Delete the resources here after sending the broadcast to let 15041 // other processes clean up before deleting resources. 15042 if (info.args != null) { 15043 synchronized (mInstallLock) { 15044 info.args.doPostDeleteLI(true); 15045 } 15046 } 15047 15048 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15049 } 15050 15051 class PackageRemovedInfo { 15052 String removedPackage; 15053 int uid = -1; 15054 int removedAppId = -1; 15055 int[] origUsers; 15056 int[] removedUsers = null; 15057 boolean isRemovedPackageSystemUpdate = false; 15058 boolean isUpdate; 15059 boolean dataRemoved; 15060 boolean removedForAllUsers; 15061 // Clean up resources deleted packages. 15062 InstallArgs args = null; 15063 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 15064 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 15065 15066 void sendPackageRemovedBroadcasts(boolean killApp) { 15067 sendPackageRemovedBroadcastInternal(killApp); 15068 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 15069 for (int i = 0; i < childCount; i++) { 15070 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15071 childInfo.sendPackageRemovedBroadcastInternal(killApp); 15072 } 15073 } 15074 15075 void sendSystemPackageUpdatedBroadcasts() { 15076 if (isRemovedPackageSystemUpdate) { 15077 sendSystemPackageUpdatedBroadcastsInternal(); 15078 final int childCount = (removedChildPackages != null) 15079 ? removedChildPackages.size() : 0; 15080 for (int i = 0; i < childCount; i++) { 15081 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15082 if (childInfo.isRemovedPackageSystemUpdate) { 15083 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 15084 } 15085 } 15086 } 15087 } 15088 15089 void sendSystemPackageAppearedBroadcasts() { 15090 final int packageCount = (appearedChildPackages != null) 15091 ? appearedChildPackages.size() : 0; 15092 for (int i = 0; i < packageCount; i++) { 15093 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 15094 for (int userId : installedInfo.newUsers) { 15095 sendPackageAddedForUser(installedInfo.name, true, 15096 UserHandle.getAppId(installedInfo.uid), userId); 15097 } 15098 } 15099 } 15100 15101 private void sendSystemPackageUpdatedBroadcastsInternal() { 15102 Bundle extras = new Bundle(2); 15103 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15104 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15105 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 15106 extras, 0, null, null, null); 15107 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 15108 extras, 0, null, null, null); 15109 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 15110 null, 0, removedPackage, null, null); 15111 } 15112 15113 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 15114 Bundle extras = new Bundle(2); 15115 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15116 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 15117 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 15118 if (isUpdate || isRemovedPackageSystemUpdate) { 15119 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15120 } 15121 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 15122 if (removedPackage != null) { 15123 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 15124 extras, 0, null, null, removedUsers); 15125 if (dataRemoved && !isRemovedPackageSystemUpdate) { 15126 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 15127 removedPackage, extras, 0, null, null, removedUsers); 15128 } 15129 } 15130 if (removedAppId >= 0) { 15131 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 15132 removedUsers); 15133 } 15134 } 15135 } 15136 15137 /* 15138 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 15139 * flag is not set, the data directory is removed as well. 15140 * make sure this flag is set for partially installed apps. If not its meaningless to 15141 * delete a partially installed application. 15142 */ 15143 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 15144 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 15145 String packageName = ps.name; 15146 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 15147 // Retrieve object to delete permissions for shared user later on 15148 final PackageParser.Package deletedPkg; 15149 final PackageSetting deletedPs; 15150 // reader 15151 synchronized (mPackages) { 15152 deletedPkg = mPackages.get(packageName); 15153 deletedPs = mSettings.mPackages.get(packageName); 15154 if (outInfo != null) { 15155 outInfo.removedPackage = packageName; 15156 outInfo.removedUsers = deletedPs != null 15157 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 15158 : null; 15159 } 15160 } 15161 15162 removePackageLI(ps, (flags & REMOVE_CHATTY) != 0); 15163 15164 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 15165 destroyAppDataLIF(deletedPkg, UserHandle.USER_ALL, 15166 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15167 destroyAppProfilesLIF(deletedPkg); 15168 if (outInfo != null) { 15169 outInfo.dataRemoved = true; 15170 } 15171 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 15172 } 15173 15174 // writer 15175 synchronized (mPackages) { 15176 if (deletedPs != null) { 15177 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 15178 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 15179 clearDefaultBrowserIfNeeded(packageName); 15180 if (outInfo != null) { 15181 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 15182 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 15183 } 15184 updatePermissionsLPw(deletedPs.name, null, 0); 15185 if (deletedPs.sharedUser != null) { 15186 // Remove permissions associated with package. Since runtime 15187 // permissions are per user we have to kill the removed package 15188 // or packages running under the shared user of the removed 15189 // package if revoking the permissions requested only by the removed 15190 // package is successful and this causes a change in gids. 15191 for (int userId : UserManagerService.getInstance().getUserIds()) { 15192 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 15193 userId); 15194 if (userIdToKill == UserHandle.USER_ALL 15195 || userIdToKill >= UserHandle.USER_SYSTEM) { 15196 // If gids changed for this user, kill all affected packages. 15197 mHandler.post(new Runnable() { 15198 @Override 15199 public void run() { 15200 // This has to happen with no lock held. 15201 killApplication(deletedPs.name, deletedPs.appId, 15202 KILL_APP_REASON_GIDS_CHANGED); 15203 } 15204 }); 15205 break; 15206 } 15207 } 15208 } 15209 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 15210 } 15211 // make sure to preserve per-user disabled state if this removal was just 15212 // a downgrade of a system app to the factory package 15213 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 15214 if (DEBUG_REMOVE) { 15215 Slog.d(TAG, "Propagating install state across downgrade"); 15216 } 15217 for (int userId : allUserHandles) { 15218 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15219 if (DEBUG_REMOVE) { 15220 Slog.d(TAG, " user " + userId + " => " + installed); 15221 } 15222 ps.setInstalled(installed, userId); 15223 } 15224 } 15225 } 15226 // can downgrade to reader 15227 if (writeSettings) { 15228 // Save settings now 15229 mSettings.writeLPr(); 15230 } 15231 } 15232 if (outInfo != null) { 15233 // A user ID was deleted here. Go through all users and remove it 15234 // from KeyStore. 15235 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 15236 } 15237 } 15238 15239 static boolean locationIsPrivileged(File path) { 15240 try { 15241 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 15242 .getCanonicalPath(); 15243 return path.getCanonicalPath().startsWith(privilegedAppDir); 15244 } catch (IOException e) { 15245 Slog.e(TAG, "Unable to access code path " + path); 15246 } 15247 return false; 15248 } 15249 15250 /* 15251 * Tries to delete system package. 15252 */ 15253 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 15254 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 15255 boolean writeSettings) { 15256 if (deletedPs.parentPackageName != null) { 15257 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 15258 return false; 15259 } 15260 15261 final boolean applyUserRestrictions 15262 = (allUserHandles != null) && (outInfo.origUsers != null); 15263 final PackageSetting disabledPs; 15264 // Confirm if the system package has been updated 15265 // An updated system app can be deleted. This will also have to restore 15266 // the system pkg from system partition 15267 // reader 15268 synchronized (mPackages) { 15269 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 15270 } 15271 15272 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 15273 + " disabledPs=" + disabledPs); 15274 15275 if (disabledPs == null) { 15276 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 15277 return false; 15278 } else if (DEBUG_REMOVE) { 15279 Slog.d(TAG, "Deleting system pkg from data partition"); 15280 } 15281 15282 if (DEBUG_REMOVE) { 15283 if (applyUserRestrictions) { 15284 Slog.d(TAG, "Remembering install states:"); 15285 for (int userId : allUserHandles) { 15286 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 15287 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 15288 } 15289 } 15290 } 15291 15292 // Delete the updated package 15293 outInfo.isRemovedPackageSystemUpdate = true; 15294 if (outInfo.removedChildPackages != null) { 15295 final int childCount = (deletedPs.childPackageNames != null) 15296 ? deletedPs.childPackageNames.size() : 0; 15297 for (int i = 0; i < childCount; i++) { 15298 String childPackageName = deletedPs.childPackageNames.get(i); 15299 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 15300 .contains(childPackageName)) { 15301 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15302 childPackageName); 15303 if (childInfo != null) { 15304 childInfo.isRemovedPackageSystemUpdate = true; 15305 } 15306 } 15307 } 15308 } 15309 15310 if (disabledPs.versionCode < deletedPs.versionCode) { 15311 // Delete data for downgrades 15312 flags &= ~PackageManager.DELETE_KEEP_DATA; 15313 } else { 15314 // Preserve data by setting flag 15315 flags |= PackageManager.DELETE_KEEP_DATA; 15316 } 15317 15318 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 15319 outInfo, writeSettings, disabledPs.pkg); 15320 if (!ret) { 15321 return false; 15322 } 15323 15324 // writer 15325 synchronized (mPackages) { 15326 // Reinstate the old system package 15327 enableSystemPackageLPw(disabledPs.pkg); 15328 // Remove any native libraries from the upgraded package. 15329 removeNativeBinariesLI(deletedPs); 15330 } 15331 15332 // Install the system package 15333 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 15334 int parseFlags = mDefParseFlags 15335 | PackageParser.PARSE_MUST_BE_APK 15336 | PackageParser.PARSE_IS_SYSTEM 15337 | PackageParser.PARSE_IS_SYSTEM_DIR; 15338 if (locationIsPrivileged(disabledPs.codePath)) { 15339 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 15340 } 15341 15342 final PackageParser.Package newPkg; 15343 try { 15344 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 15345 } catch (PackageManagerException e) { 15346 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 15347 + e.getMessage()); 15348 return false; 15349 } 15350 15351 prepareAppDataAfterInstallLIF(newPkg); 15352 15353 // writer 15354 synchronized (mPackages) { 15355 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 15356 15357 // Propagate the permissions state as we do not want to drop on the floor 15358 // runtime permissions. The update permissions method below will take 15359 // care of removing obsolete permissions and grant install permissions. 15360 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 15361 updatePermissionsLPw(newPkg.packageName, newPkg, 15362 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 15363 15364 if (applyUserRestrictions) { 15365 if (DEBUG_REMOVE) { 15366 Slog.d(TAG, "Propagating install state across reinstall"); 15367 } 15368 for (int userId : allUserHandles) { 15369 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15370 if (DEBUG_REMOVE) { 15371 Slog.d(TAG, " user " + userId + " => " + installed); 15372 } 15373 ps.setInstalled(installed, userId); 15374 15375 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 15376 } 15377 // Regardless of writeSettings we need to ensure that this restriction 15378 // state propagation is persisted 15379 mSettings.writeAllUsersPackageRestrictionsLPr(); 15380 } 15381 // can downgrade to reader here 15382 if (writeSettings) { 15383 mSettings.writeLPr(); 15384 } 15385 } 15386 return true; 15387 } 15388 15389 private boolean deleteInstalledPackageLIF(PackageSetting ps, 15390 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 15391 PackageRemovedInfo outInfo, boolean writeSettings, 15392 PackageParser.Package replacingPackage) { 15393 synchronized (mPackages) { 15394 if (outInfo != null) { 15395 outInfo.uid = ps.appId; 15396 } 15397 15398 if (outInfo != null && outInfo.removedChildPackages != null) { 15399 final int childCount = (ps.childPackageNames != null) 15400 ? ps.childPackageNames.size() : 0; 15401 for (int i = 0; i < childCount; i++) { 15402 String childPackageName = ps.childPackageNames.get(i); 15403 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 15404 if (childPs == null) { 15405 return false; 15406 } 15407 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15408 childPackageName); 15409 if (childInfo != null) { 15410 childInfo.uid = childPs.appId; 15411 } 15412 } 15413 } 15414 } 15415 15416 // Delete package data from internal structures and also remove data if flag is set 15417 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 15418 15419 // Delete the child packages data 15420 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 15421 for (int i = 0; i < childCount; i++) { 15422 PackageSetting childPs; 15423 synchronized (mPackages) { 15424 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 15425 } 15426 if (childPs != null) { 15427 PackageRemovedInfo childOutInfo = (outInfo != null 15428 && outInfo.removedChildPackages != null) 15429 ? outInfo.removedChildPackages.get(childPs.name) : null; 15430 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 15431 && (replacingPackage != null 15432 && !replacingPackage.hasChildPackage(childPs.name)) 15433 ? flags & ~DELETE_KEEP_DATA : flags; 15434 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 15435 deleteFlags, writeSettings); 15436 } 15437 } 15438 15439 // Delete application code and resources only for parent packages 15440 if (ps.parentPackageName == null) { 15441 if (deleteCodeAndResources && (outInfo != null)) { 15442 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 15443 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 15444 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 15445 } 15446 } 15447 15448 return true; 15449 } 15450 15451 @Override 15452 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 15453 int userId) { 15454 mContext.enforceCallingOrSelfPermission( 15455 android.Manifest.permission.DELETE_PACKAGES, null); 15456 synchronized (mPackages) { 15457 PackageSetting ps = mSettings.mPackages.get(packageName); 15458 if (ps == null) { 15459 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 15460 return false; 15461 } 15462 if (!ps.getInstalled(userId)) { 15463 // Can't block uninstall for an app that is not installed or enabled. 15464 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 15465 return false; 15466 } 15467 ps.setBlockUninstall(blockUninstall, userId); 15468 mSettings.writePackageRestrictionsLPr(userId); 15469 } 15470 return true; 15471 } 15472 15473 @Override 15474 public boolean getBlockUninstallForUser(String packageName, int userId) { 15475 synchronized (mPackages) { 15476 PackageSetting ps = mSettings.mPackages.get(packageName); 15477 if (ps == null) { 15478 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 15479 return false; 15480 } 15481 return ps.getBlockUninstall(userId); 15482 } 15483 } 15484 15485 @Override 15486 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 15487 int callingUid = Binder.getCallingUid(); 15488 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 15489 throw new SecurityException( 15490 "setRequiredForSystemUser can only be run by the system or root"); 15491 } 15492 synchronized (mPackages) { 15493 PackageSetting ps = mSettings.mPackages.get(packageName); 15494 if (ps == null) { 15495 Log.w(TAG, "Package doesn't exist: " + packageName); 15496 return false; 15497 } 15498 if (systemUserApp) { 15499 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15500 } else { 15501 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15502 } 15503 mSettings.writeLPr(); 15504 } 15505 return true; 15506 } 15507 15508 /* 15509 * This method handles package deletion in general 15510 */ 15511 private boolean deletePackageLIF(String packageName, UserHandle user, 15512 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 15513 PackageRemovedInfo outInfo, boolean writeSettings, 15514 PackageParser.Package replacingPackage) { 15515 if (packageName == null) { 15516 Slog.w(TAG, "Attempt to delete null packageName."); 15517 return false; 15518 } 15519 15520 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 15521 15522 PackageSetting ps; 15523 15524 synchronized (mPackages) { 15525 ps = mSettings.mPackages.get(packageName); 15526 if (ps == null) { 15527 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 15528 return false; 15529 } 15530 15531 if (ps.parentPackageName != null && (!isSystemApp(ps) 15532 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 15533 if (DEBUG_REMOVE) { 15534 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 15535 + ((user == null) ? UserHandle.USER_ALL : user)); 15536 } 15537 final int removedUserId = (user != null) ? user.getIdentifier() 15538 : UserHandle.USER_ALL; 15539 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 15540 return false; 15541 } 15542 markPackageUninstalledForUserLPw(ps, user); 15543 scheduleWritePackageRestrictionsLocked(user); 15544 return true; 15545 } 15546 } 15547 15548 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 15549 && user.getIdentifier() != UserHandle.USER_ALL)) { 15550 // The caller is asking that the package only be deleted for a single 15551 // user. To do this, we just mark its uninstalled state and delete 15552 // its data. If this is a system app, we only allow this to happen if 15553 // they have set the special DELETE_SYSTEM_APP which requests different 15554 // semantics than normal for uninstalling system apps. 15555 markPackageUninstalledForUserLPw(ps, user); 15556 15557 if (!isSystemApp(ps)) { 15558 // Do not uninstall the APK if an app should be cached 15559 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 15560 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 15561 // Other user still have this package installed, so all 15562 // we need to do is clear this user's data and save that 15563 // it is uninstalled. 15564 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 15565 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 15566 return false; 15567 } 15568 scheduleWritePackageRestrictionsLocked(user); 15569 return true; 15570 } else { 15571 // We need to set it back to 'installed' so the uninstall 15572 // broadcasts will be sent correctly. 15573 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 15574 ps.setInstalled(true, user.getIdentifier()); 15575 } 15576 } else { 15577 // This is a system app, so we assume that the 15578 // other users still have this package installed, so all 15579 // we need to do is clear this user's data and save that 15580 // it is uninstalled. 15581 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 15582 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 15583 return false; 15584 } 15585 scheduleWritePackageRestrictionsLocked(user); 15586 return true; 15587 } 15588 } 15589 15590 // If we are deleting a composite package for all users, keep track 15591 // of result for each child. 15592 if (ps.childPackageNames != null && outInfo != null) { 15593 synchronized (mPackages) { 15594 final int childCount = ps.childPackageNames.size(); 15595 outInfo.removedChildPackages = new ArrayMap<>(childCount); 15596 for (int i = 0; i < childCount; i++) { 15597 String childPackageName = ps.childPackageNames.get(i); 15598 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 15599 childInfo.removedPackage = childPackageName; 15600 outInfo.removedChildPackages.put(childPackageName, childInfo); 15601 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 15602 if (childPs != null) { 15603 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 15604 } 15605 } 15606 } 15607 } 15608 15609 boolean ret = false; 15610 if (isSystemApp(ps)) { 15611 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 15612 // When an updated system application is deleted we delete the existing resources 15613 // as well and fall back to existing code in system partition 15614 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 15615 } else { 15616 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 15617 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 15618 outInfo, writeSettings, replacingPackage); 15619 } 15620 15621 // Take a note whether we deleted the package for all users 15622 if (outInfo != null) { 15623 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 15624 if (outInfo.removedChildPackages != null) { 15625 synchronized (mPackages) { 15626 final int childCount = outInfo.removedChildPackages.size(); 15627 for (int i = 0; i < childCount; i++) { 15628 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 15629 if (childInfo != null) { 15630 childInfo.removedForAllUsers = mPackages.get( 15631 childInfo.removedPackage) == null; 15632 } 15633 } 15634 } 15635 } 15636 // If we uninstalled an update to a system app there may be some 15637 // child packages that appeared as they are declared in the system 15638 // app but were not declared in the update. 15639 if (isSystemApp(ps)) { 15640 synchronized (mPackages) { 15641 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 15642 final int childCount = (updatedPs.childPackageNames != null) 15643 ? updatedPs.childPackageNames.size() : 0; 15644 for (int i = 0; i < childCount; i++) { 15645 String childPackageName = updatedPs.childPackageNames.get(i); 15646 if (outInfo.removedChildPackages == null 15647 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 15648 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 15649 if (childPs == null) { 15650 continue; 15651 } 15652 PackageInstalledInfo installRes = new PackageInstalledInfo(); 15653 installRes.name = childPackageName; 15654 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 15655 installRes.pkg = mPackages.get(childPackageName); 15656 installRes.uid = childPs.pkg.applicationInfo.uid; 15657 if (outInfo.appearedChildPackages == null) { 15658 outInfo.appearedChildPackages = new ArrayMap<>(); 15659 } 15660 outInfo.appearedChildPackages.put(childPackageName, installRes); 15661 } 15662 } 15663 } 15664 } 15665 } 15666 15667 return ret; 15668 } 15669 15670 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 15671 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 15672 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 15673 for (int nextUserId : userIds) { 15674 if (DEBUG_REMOVE) { 15675 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 15676 } 15677 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 15678 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 15679 false /*hidden*/, false /*suspended*/, null, null, null, 15680 false /*blockUninstall*/, 15681 ps.readUserState(nextUserId).domainVerificationStatus, 0); 15682 } 15683 } 15684 15685 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 15686 PackageRemovedInfo outInfo) { 15687 final PackageParser.Package pkg; 15688 synchronized (mPackages) { 15689 pkg = mPackages.get(ps.name); 15690 } 15691 15692 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 15693 : new int[] {userId}; 15694 for (int nextUserId : userIds) { 15695 if (DEBUG_REMOVE) { 15696 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 15697 + nextUserId); 15698 } 15699 15700 destroyAppDataLIF(pkg, userId, 15701 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15702 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 15703 schedulePackageCleaning(ps.name, nextUserId, false); 15704 synchronized (mPackages) { 15705 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 15706 scheduleWritePackageRestrictionsLocked(nextUserId); 15707 } 15708 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 15709 } 15710 } 15711 15712 if (outInfo != null) { 15713 outInfo.removedPackage = ps.name; 15714 outInfo.removedAppId = ps.appId; 15715 outInfo.removedUsers = userIds; 15716 } 15717 15718 return true; 15719 } 15720 15721 private final class ClearStorageConnection implements ServiceConnection { 15722 IMediaContainerService mContainerService; 15723 15724 @Override 15725 public void onServiceConnected(ComponentName name, IBinder service) { 15726 synchronized (this) { 15727 mContainerService = IMediaContainerService.Stub.asInterface(service); 15728 notifyAll(); 15729 } 15730 } 15731 15732 @Override 15733 public void onServiceDisconnected(ComponentName name) { 15734 } 15735 } 15736 15737 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 15738 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 15739 15740 final boolean mounted; 15741 if (Environment.isExternalStorageEmulated()) { 15742 mounted = true; 15743 } else { 15744 final String status = Environment.getExternalStorageState(); 15745 15746 mounted = status.equals(Environment.MEDIA_MOUNTED) 15747 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 15748 } 15749 15750 if (!mounted) { 15751 return; 15752 } 15753 15754 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 15755 int[] users; 15756 if (userId == UserHandle.USER_ALL) { 15757 users = sUserManager.getUserIds(); 15758 } else { 15759 users = new int[] { userId }; 15760 } 15761 final ClearStorageConnection conn = new ClearStorageConnection(); 15762 if (mContext.bindServiceAsUser( 15763 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 15764 try { 15765 for (int curUser : users) { 15766 long timeout = SystemClock.uptimeMillis() + 5000; 15767 synchronized (conn) { 15768 long now = SystemClock.uptimeMillis(); 15769 while (conn.mContainerService == null && now < timeout) { 15770 try { 15771 conn.wait(timeout - now); 15772 } catch (InterruptedException e) { 15773 } 15774 } 15775 } 15776 if (conn.mContainerService == null) { 15777 return; 15778 } 15779 15780 final UserEnvironment userEnv = new UserEnvironment(curUser); 15781 clearDirectory(conn.mContainerService, 15782 userEnv.buildExternalStorageAppCacheDirs(packageName)); 15783 if (allData) { 15784 clearDirectory(conn.mContainerService, 15785 userEnv.buildExternalStorageAppDataDirs(packageName)); 15786 clearDirectory(conn.mContainerService, 15787 userEnv.buildExternalStorageAppMediaDirs(packageName)); 15788 } 15789 } 15790 } finally { 15791 mContext.unbindService(conn); 15792 } 15793 } 15794 } 15795 15796 @Override 15797 public void clearApplicationProfileData(String packageName) { 15798 enforceSystemOrRoot("Only the system can clear all profile data"); 15799 15800 final PackageParser.Package pkg; 15801 synchronized (mPackages) { 15802 pkg = mPackages.get(packageName); 15803 } 15804 15805 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 15806 synchronized (mInstallLock) { 15807 clearAppProfilesLIF(pkg); 15808 } 15809 } 15810 } 15811 15812 @Override 15813 public void clearApplicationUserData(final String packageName, 15814 final IPackageDataObserver observer, final int userId) { 15815 mContext.enforceCallingOrSelfPermission( 15816 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 15817 15818 enforceCrossUserPermission(Binder.getCallingUid(), userId, 15819 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 15820 15821 final DevicePolicyManagerInternal dpmi = LocalServices 15822 .getService(DevicePolicyManagerInternal.class); 15823 if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) { 15824 throw new SecurityException("Cannot clear data for a device owner or a profile owner"); 15825 } 15826 // Queue up an async operation since the package deletion may take a little while. 15827 mHandler.post(new Runnable() { 15828 public void run() { 15829 mHandler.removeCallbacks(this); 15830 final boolean succeeded; 15831 try (PackageFreezer freezer = freezePackage(packageName, 15832 "clearApplicationUserData")) { 15833 synchronized (mInstallLock) { 15834 succeeded = clearApplicationUserDataLIF(packageName, userId); 15835 } 15836 clearExternalStorageDataSync(packageName, userId, true); 15837 } 15838 if (succeeded) { 15839 // invoke DeviceStorageMonitor's update method to clear any notifications 15840 DeviceStorageMonitorInternal dsm = LocalServices 15841 .getService(DeviceStorageMonitorInternal.class); 15842 if (dsm != null) { 15843 dsm.checkMemory(); 15844 } 15845 } 15846 if(observer != null) { 15847 try { 15848 observer.onRemoveCompleted(packageName, succeeded); 15849 } catch (RemoteException e) { 15850 Log.i(TAG, "Observer no longer exists."); 15851 } 15852 } //end if observer 15853 } //end run 15854 }); 15855 } 15856 15857 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 15858 if (packageName == null) { 15859 Slog.w(TAG, "Attempt to delete null packageName."); 15860 return false; 15861 } 15862 15863 // Try finding details about the requested package 15864 PackageParser.Package pkg; 15865 synchronized (mPackages) { 15866 pkg = mPackages.get(packageName); 15867 if (pkg == null) { 15868 final PackageSetting ps = mSettings.mPackages.get(packageName); 15869 if (ps != null) { 15870 pkg = ps.pkg; 15871 } 15872 } 15873 15874 if (pkg == null) { 15875 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 15876 return false; 15877 } 15878 15879 PackageSetting ps = (PackageSetting) pkg.mExtras; 15880 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 15881 } 15882 15883 clearAppDataLIF(pkg, userId, 15884 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15885 15886 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 15887 removeKeystoreDataIfNeeded(userId, appId); 15888 15889 final UserManager um = mContext.getSystemService(UserManager.class); 15890 final int flags; 15891 if (um.isUserUnlocked(userId)) { 15892 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 15893 } else if (um.isUserRunning(userId)) { 15894 flags = StorageManager.FLAG_STORAGE_DE; 15895 } else { 15896 flags = 0; 15897 } 15898 prepareAppDataContentsLIF(pkg, userId, flags); 15899 15900 return true; 15901 } 15902 15903 /** 15904 * Reverts user permission state changes (permissions and flags) in 15905 * all packages for a given user. 15906 * 15907 * @param userId The device user for which to do a reset. 15908 */ 15909 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 15910 final int packageCount = mPackages.size(); 15911 for (int i = 0; i < packageCount; i++) { 15912 PackageParser.Package pkg = mPackages.valueAt(i); 15913 PackageSetting ps = (PackageSetting) pkg.mExtras; 15914 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 15915 } 15916 } 15917 15918 /** 15919 * Reverts user permission state changes (permissions and flags). 15920 * 15921 * @param ps The package for which to reset. 15922 * @param userId The device user for which to do a reset. 15923 */ 15924 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 15925 final PackageSetting ps, final int userId) { 15926 if (ps.pkg == null) { 15927 return; 15928 } 15929 15930 // These are flags that can change base on user actions. 15931 final int userSettableMask = FLAG_PERMISSION_USER_SET 15932 | FLAG_PERMISSION_USER_FIXED 15933 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 15934 | FLAG_PERMISSION_REVIEW_REQUIRED; 15935 15936 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 15937 | FLAG_PERMISSION_POLICY_FIXED; 15938 15939 boolean writeInstallPermissions = false; 15940 boolean writeRuntimePermissions = false; 15941 15942 final int permissionCount = ps.pkg.requestedPermissions.size(); 15943 for (int i = 0; i < permissionCount; i++) { 15944 String permission = ps.pkg.requestedPermissions.get(i); 15945 15946 BasePermission bp = mSettings.mPermissions.get(permission); 15947 if (bp == null) { 15948 continue; 15949 } 15950 15951 // If shared user we just reset the state to which only this app contributed. 15952 if (ps.sharedUser != null) { 15953 boolean used = false; 15954 final int packageCount = ps.sharedUser.packages.size(); 15955 for (int j = 0; j < packageCount; j++) { 15956 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 15957 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 15958 && pkg.pkg.requestedPermissions.contains(permission)) { 15959 used = true; 15960 break; 15961 } 15962 } 15963 if (used) { 15964 continue; 15965 } 15966 } 15967 15968 PermissionsState permissionsState = ps.getPermissionsState(); 15969 15970 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 15971 15972 // Always clear the user settable flags. 15973 final boolean hasInstallState = permissionsState.getInstallPermissionState( 15974 bp.name) != null; 15975 // If permission review is enabled and this is a legacy app, mark the 15976 // permission as requiring a review as this is the initial state. 15977 int flags = 0; 15978 if (Build.PERMISSIONS_REVIEW_REQUIRED 15979 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 15980 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 15981 } 15982 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 15983 if (hasInstallState) { 15984 writeInstallPermissions = true; 15985 } else { 15986 writeRuntimePermissions = true; 15987 } 15988 } 15989 15990 // Below is only runtime permission handling. 15991 if (!bp.isRuntime()) { 15992 continue; 15993 } 15994 15995 // Never clobber system or policy. 15996 if ((oldFlags & policyOrSystemFlags) != 0) { 15997 continue; 15998 } 15999 16000 // If this permission was granted by default, make sure it is. 16001 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 16002 if (permissionsState.grantRuntimePermission(bp, userId) 16003 != PERMISSION_OPERATION_FAILURE) { 16004 writeRuntimePermissions = true; 16005 } 16006 // If permission review is enabled the permissions for a legacy apps 16007 // are represented as constantly granted runtime ones, so don't revoke. 16008 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 16009 // Otherwise, reset the permission. 16010 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 16011 switch (revokeResult) { 16012 case PERMISSION_OPERATION_SUCCESS: 16013 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 16014 writeRuntimePermissions = true; 16015 final int appId = ps.appId; 16016 mHandler.post(new Runnable() { 16017 @Override 16018 public void run() { 16019 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 16020 } 16021 }); 16022 } break; 16023 } 16024 } 16025 } 16026 16027 // Synchronously write as we are taking permissions away. 16028 if (writeRuntimePermissions) { 16029 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 16030 } 16031 16032 // Synchronously write as we are taking permissions away. 16033 if (writeInstallPermissions) { 16034 mSettings.writeLPr(); 16035 } 16036 } 16037 16038 /** 16039 * Remove entries from the keystore daemon. Will only remove it if the 16040 * {@code appId} is valid. 16041 */ 16042 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 16043 if (appId < 0) { 16044 return; 16045 } 16046 16047 final KeyStore keyStore = KeyStore.getInstance(); 16048 if (keyStore != null) { 16049 if (userId == UserHandle.USER_ALL) { 16050 for (final int individual : sUserManager.getUserIds()) { 16051 keyStore.clearUid(UserHandle.getUid(individual, appId)); 16052 } 16053 } else { 16054 keyStore.clearUid(UserHandle.getUid(userId, appId)); 16055 } 16056 } else { 16057 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 16058 } 16059 } 16060 16061 @Override 16062 public void deleteApplicationCacheFiles(final String packageName, 16063 final IPackageDataObserver observer) { 16064 final int userId = UserHandle.getCallingUserId(); 16065 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 16066 } 16067 16068 @Override 16069 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 16070 final IPackageDataObserver observer) { 16071 mContext.enforceCallingOrSelfPermission( 16072 android.Manifest.permission.DELETE_CACHE_FILES, null); 16073 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16074 /* requireFullPermission= */ true, /* checkShell= */ false, 16075 "delete application cache files"); 16076 16077 final PackageParser.Package pkg; 16078 synchronized (mPackages) { 16079 pkg = mPackages.get(packageName); 16080 } 16081 16082 // Queue up an async operation since the package deletion may take a little while. 16083 mHandler.post(new Runnable() { 16084 public void run() { 16085 synchronized (mInstallLock) { 16086 final int flags = StorageManager.FLAG_STORAGE_DE 16087 | StorageManager.FLAG_STORAGE_CE; 16088 // We're only clearing cache files, so we don't care if the 16089 // app is unfrozen and still able to run 16090 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 16091 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16092 } 16093 clearExternalStorageDataSync(packageName, userId, false); 16094 if (observer != null) { 16095 try { 16096 observer.onRemoveCompleted(packageName, true); 16097 } catch (RemoteException e) { 16098 Log.i(TAG, "Observer no longer exists."); 16099 } 16100 } 16101 } 16102 }); 16103 } 16104 16105 @Override 16106 public void getPackageSizeInfo(final String packageName, int userHandle, 16107 final IPackageStatsObserver observer) { 16108 mContext.enforceCallingOrSelfPermission( 16109 android.Manifest.permission.GET_PACKAGE_SIZE, null); 16110 if (packageName == null) { 16111 throw new IllegalArgumentException("Attempt to get size of null packageName"); 16112 } 16113 16114 PackageStats stats = new PackageStats(packageName, userHandle); 16115 16116 /* 16117 * Queue up an async operation since the package measurement may take a 16118 * little while. 16119 */ 16120 Message msg = mHandler.obtainMessage(INIT_COPY); 16121 msg.obj = new MeasureParams(stats, observer); 16122 mHandler.sendMessage(msg); 16123 } 16124 16125 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 16126 final PackageSetting ps; 16127 synchronized (mPackages) { 16128 ps = mSettings.mPackages.get(packageName); 16129 if (ps == null) { 16130 Slog.w(TAG, "Failed to find settings for " + packageName); 16131 return false; 16132 } 16133 } 16134 try { 16135 mInstaller.getAppSize(ps.volumeUuid, packageName, userId, 16136 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 16137 ps.getCeDataInode(userId), ps.codePathString, stats); 16138 } catch (InstallerException e) { 16139 Slog.w(TAG, String.valueOf(e)); 16140 return false; 16141 } 16142 16143 // For now, ignore code size of packages on system partition 16144 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 16145 stats.codeSize = 0; 16146 } 16147 16148 return true; 16149 } 16150 16151 private int getUidTargetSdkVersionLockedLPr(int uid) { 16152 Object obj = mSettings.getUserIdLPr(uid); 16153 if (obj instanceof SharedUserSetting) { 16154 final SharedUserSetting sus = (SharedUserSetting) obj; 16155 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 16156 final Iterator<PackageSetting> it = sus.packages.iterator(); 16157 while (it.hasNext()) { 16158 final PackageSetting ps = it.next(); 16159 if (ps.pkg != null) { 16160 int v = ps.pkg.applicationInfo.targetSdkVersion; 16161 if (v < vers) vers = v; 16162 } 16163 } 16164 return vers; 16165 } else if (obj instanceof PackageSetting) { 16166 final PackageSetting ps = (PackageSetting) obj; 16167 if (ps.pkg != null) { 16168 return ps.pkg.applicationInfo.targetSdkVersion; 16169 } 16170 } 16171 return Build.VERSION_CODES.CUR_DEVELOPMENT; 16172 } 16173 16174 @Override 16175 public void addPreferredActivity(IntentFilter filter, int match, 16176 ComponentName[] set, ComponentName activity, int userId) { 16177 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16178 "Adding preferred"); 16179 } 16180 16181 private void addPreferredActivityInternal(IntentFilter filter, int match, 16182 ComponentName[] set, ComponentName activity, boolean always, int userId, 16183 String opname) { 16184 // writer 16185 int callingUid = Binder.getCallingUid(); 16186 enforceCrossUserPermission(callingUid, userId, 16187 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 16188 if (filter.countActions() == 0) { 16189 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16190 return; 16191 } 16192 synchronized (mPackages) { 16193 if (mContext.checkCallingOrSelfPermission( 16194 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16195 != PackageManager.PERMISSION_GRANTED) { 16196 if (getUidTargetSdkVersionLockedLPr(callingUid) 16197 < Build.VERSION_CODES.FROYO) { 16198 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 16199 + callingUid); 16200 return; 16201 } 16202 mContext.enforceCallingOrSelfPermission( 16203 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16204 } 16205 16206 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 16207 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 16208 + userId + ":"); 16209 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16210 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 16211 scheduleWritePackageRestrictionsLocked(userId); 16212 } 16213 } 16214 16215 @Override 16216 public void replacePreferredActivity(IntentFilter filter, int match, 16217 ComponentName[] set, ComponentName activity, int userId) { 16218 if (filter.countActions() != 1) { 16219 throw new IllegalArgumentException( 16220 "replacePreferredActivity expects filter to have only 1 action."); 16221 } 16222 if (filter.countDataAuthorities() != 0 16223 || filter.countDataPaths() != 0 16224 || filter.countDataSchemes() > 1 16225 || filter.countDataTypes() != 0) { 16226 throw new IllegalArgumentException( 16227 "replacePreferredActivity expects filter to have no data authorities, " + 16228 "paths, or types; and at most one scheme."); 16229 } 16230 16231 final int callingUid = Binder.getCallingUid(); 16232 enforceCrossUserPermission(callingUid, userId, 16233 true /* requireFullPermission */, false /* checkShell */, 16234 "replace preferred activity"); 16235 synchronized (mPackages) { 16236 if (mContext.checkCallingOrSelfPermission( 16237 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16238 != PackageManager.PERMISSION_GRANTED) { 16239 if (getUidTargetSdkVersionLockedLPr(callingUid) 16240 < Build.VERSION_CODES.FROYO) { 16241 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 16242 + Binder.getCallingUid()); 16243 return; 16244 } 16245 mContext.enforceCallingOrSelfPermission( 16246 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16247 } 16248 16249 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16250 if (pir != null) { 16251 // Get all of the existing entries that exactly match this filter. 16252 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 16253 if (existing != null && existing.size() == 1) { 16254 PreferredActivity cur = existing.get(0); 16255 if (DEBUG_PREFERRED) { 16256 Slog.i(TAG, "Checking replace of preferred:"); 16257 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16258 if (!cur.mPref.mAlways) { 16259 Slog.i(TAG, " -- CUR; not mAlways!"); 16260 } else { 16261 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 16262 Slog.i(TAG, " -- CUR: mSet=" 16263 + Arrays.toString(cur.mPref.mSetComponents)); 16264 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 16265 Slog.i(TAG, " -- NEW: mMatch=" 16266 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 16267 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 16268 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 16269 } 16270 } 16271 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 16272 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 16273 && cur.mPref.sameSet(set)) { 16274 // Setting the preferred activity to what it happens to be already 16275 if (DEBUG_PREFERRED) { 16276 Slog.i(TAG, "Replacing with same preferred activity " 16277 + cur.mPref.mShortComponent + " for user " 16278 + userId + ":"); 16279 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16280 } 16281 return; 16282 } 16283 } 16284 16285 if (existing != null) { 16286 if (DEBUG_PREFERRED) { 16287 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 16288 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16289 } 16290 for (int i = 0; i < existing.size(); i++) { 16291 PreferredActivity pa = existing.get(i); 16292 if (DEBUG_PREFERRED) { 16293 Slog.i(TAG, "Removing existing preferred activity " 16294 + pa.mPref.mComponent + ":"); 16295 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 16296 } 16297 pir.removeFilter(pa); 16298 } 16299 } 16300 } 16301 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16302 "Replacing preferred"); 16303 } 16304 } 16305 16306 @Override 16307 public void clearPackagePreferredActivities(String packageName) { 16308 final int uid = Binder.getCallingUid(); 16309 // writer 16310 synchronized (mPackages) { 16311 PackageParser.Package pkg = mPackages.get(packageName); 16312 if (pkg == null || pkg.applicationInfo.uid != uid) { 16313 if (mContext.checkCallingOrSelfPermission( 16314 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16315 != PackageManager.PERMISSION_GRANTED) { 16316 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 16317 < Build.VERSION_CODES.FROYO) { 16318 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 16319 + Binder.getCallingUid()); 16320 return; 16321 } 16322 mContext.enforceCallingOrSelfPermission( 16323 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16324 } 16325 } 16326 16327 int user = UserHandle.getCallingUserId(); 16328 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 16329 scheduleWritePackageRestrictionsLocked(user); 16330 } 16331 } 16332 } 16333 16334 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16335 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 16336 ArrayList<PreferredActivity> removed = null; 16337 boolean changed = false; 16338 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16339 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 16340 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16341 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 16342 continue; 16343 } 16344 Iterator<PreferredActivity> it = pir.filterIterator(); 16345 while (it.hasNext()) { 16346 PreferredActivity pa = it.next(); 16347 // Mark entry for removal only if it matches the package name 16348 // and the entry is of type "always". 16349 if (packageName == null || 16350 (pa.mPref.mComponent.getPackageName().equals(packageName) 16351 && pa.mPref.mAlways)) { 16352 if (removed == null) { 16353 removed = new ArrayList<PreferredActivity>(); 16354 } 16355 removed.add(pa); 16356 } 16357 } 16358 if (removed != null) { 16359 for (int j=0; j<removed.size(); j++) { 16360 PreferredActivity pa = removed.get(j); 16361 pir.removeFilter(pa); 16362 } 16363 changed = true; 16364 } 16365 } 16366 return changed; 16367 } 16368 16369 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16370 private void clearIntentFilterVerificationsLPw(int userId) { 16371 final int packageCount = mPackages.size(); 16372 for (int i = 0; i < packageCount; i++) { 16373 PackageParser.Package pkg = mPackages.valueAt(i); 16374 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 16375 } 16376 } 16377 16378 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16379 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 16380 if (userId == UserHandle.USER_ALL) { 16381 if (mSettings.removeIntentFilterVerificationLPw(packageName, 16382 sUserManager.getUserIds())) { 16383 for (int oneUserId : sUserManager.getUserIds()) { 16384 scheduleWritePackageRestrictionsLocked(oneUserId); 16385 } 16386 } 16387 } else { 16388 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 16389 scheduleWritePackageRestrictionsLocked(userId); 16390 } 16391 } 16392 } 16393 16394 void clearDefaultBrowserIfNeeded(String packageName) { 16395 for (int oneUserId : sUserManager.getUserIds()) { 16396 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 16397 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 16398 if (packageName.equals(defaultBrowserPackageName)) { 16399 setDefaultBrowserPackageName(null, oneUserId); 16400 } 16401 } 16402 } 16403 16404 @Override 16405 public void resetApplicationPreferences(int userId) { 16406 mContext.enforceCallingOrSelfPermission( 16407 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16408 // writer 16409 synchronized (mPackages) { 16410 final long identity = Binder.clearCallingIdentity(); 16411 try { 16412 clearPackagePreferredActivitiesLPw(null, userId); 16413 mSettings.applyDefaultPreferredAppsLPw(this, userId); 16414 // TODO: We have to reset the default SMS and Phone. This requires 16415 // significant refactoring to keep all default apps in the package 16416 // manager (cleaner but more work) or have the services provide 16417 // callbacks to the package manager to request a default app reset. 16418 applyFactoryDefaultBrowserLPw(userId); 16419 clearIntentFilterVerificationsLPw(userId); 16420 primeDomainVerificationsLPw(userId); 16421 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 16422 scheduleWritePackageRestrictionsLocked(userId); 16423 } finally { 16424 Binder.restoreCallingIdentity(identity); 16425 } 16426 } 16427 } 16428 16429 @Override 16430 public int getPreferredActivities(List<IntentFilter> outFilters, 16431 List<ComponentName> outActivities, String packageName) { 16432 16433 int num = 0; 16434 final int userId = UserHandle.getCallingUserId(); 16435 // reader 16436 synchronized (mPackages) { 16437 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16438 if (pir != null) { 16439 final Iterator<PreferredActivity> it = pir.filterIterator(); 16440 while (it.hasNext()) { 16441 final PreferredActivity pa = it.next(); 16442 if (packageName == null 16443 || (pa.mPref.mComponent.getPackageName().equals(packageName) 16444 && pa.mPref.mAlways)) { 16445 if (outFilters != null) { 16446 outFilters.add(new IntentFilter(pa)); 16447 } 16448 if (outActivities != null) { 16449 outActivities.add(pa.mPref.mComponent); 16450 } 16451 } 16452 } 16453 } 16454 } 16455 16456 return num; 16457 } 16458 16459 @Override 16460 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 16461 int userId) { 16462 int callingUid = Binder.getCallingUid(); 16463 if (callingUid != Process.SYSTEM_UID) { 16464 throw new SecurityException( 16465 "addPersistentPreferredActivity can only be run by the system"); 16466 } 16467 if (filter.countActions() == 0) { 16468 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16469 return; 16470 } 16471 synchronized (mPackages) { 16472 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 16473 ":"); 16474 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16475 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 16476 new PersistentPreferredActivity(filter, activity)); 16477 scheduleWritePackageRestrictionsLocked(userId); 16478 } 16479 } 16480 16481 @Override 16482 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 16483 int callingUid = Binder.getCallingUid(); 16484 if (callingUid != Process.SYSTEM_UID) { 16485 throw new SecurityException( 16486 "clearPackagePersistentPreferredActivities can only be run by the system"); 16487 } 16488 ArrayList<PersistentPreferredActivity> removed = null; 16489 boolean changed = false; 16490 synchronized (mPackages) { 16491 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 16492 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 16493 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 16494 .valueAt(i); 16495 if (userId != thisUserId) { 16496 continue; 16497 } 16498 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 16499 while (it.hasNext()) { 16500 PersistentPreferredActivity ppa = it.next(); 16501 // Mark entry for removal only if it matches the package name. 16502 if (ppa.mComponent.getPackageName().equals(packageName)) { 16503 if (removed == null) { 16504 removed = new ArrayList<PersistentPreferredActivity>(); 16505 } 16506 removed.add(ppa); 16507 } 16508 } 16509 if (removed != null) { 16510 for (int j=0; j<removed.size(); j++) { 16511 PersistentPreferredActivity ppa = removed.get(j); 16512 ppir.removeFilter(ppa); 16513 } 16514 changed = true; 16515 } 16516 } 16517 16518 if (changed) { 16519 scheduleWritePackageRestrictionsLocked(userId); 16520 } 16521 } 16522 } 16523 16524 /** 16525 * Common machinery for picking apart a restored XML blob and passing 16526 * it to a caller-supplied functor to be applied to the running system. 16527 */ 16528 private void restoreFromXml(XmlPullParser parser, int userId, 16529 String expectedStartTag, BlobXmlRestorer functor) 16530 throws IOException, XmlPullParserException { 16531 int type; 16532 while ((type = parser.next()) != XmlPullParser.START_TAG 16533 && type != XmlPullParser.END_DOCUMENT) { 16534 } 16535 if (type != XmlPullParser.START_TAG) { 16536 // oops didn't find a start tag?! 16537 if (DEBUG_BACKUP) { 16538 Slog.e(TAG, "Didn't find start tag during restore"); 16539 } 16540 return; 16541 } 16542Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 16543 // this is supposed to be TAG_PREFERRED_BACKUP 16544 if (!expectedStartTag.equals(parser.getName())) { 16545 if (DEBUG_BACKUP) { 16546 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 16547 } 16548 return; 16549 } 16550 16551 // skip interfering stuff, then we're aligned with the backing implementation 16552 while ((type = parser.next()) == XmlPullParser.TEXT) { } 16553Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 16554 functor.apply(parser, userId); 16555 } 16556 16557 private interface BlobXmlRestorer { 16558 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 16559 } 16560 16561 /** 16562 * Non-Binder method, support for the backup/restore mechanism: write the 16563 * full set of preferred activities in its canonical XML format. Returns the 16564 * XML output as a byte array, or null if there is none. 16565 */ 16566 @Override 16567 public byte[] getPreferredActivityBackup(int userId) { 16568 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16569 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 16570 } 16571 16572 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16573 try { 16574 final XmlSerializer serializer = new FastXmlSerializer(); 16575 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16576 serializer.startDocument(null, true); 16577 serializer.startTag(null, TAG_PREFERRED_BACKUP); 16578 16579 synchronized (mPackages) { 16580 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 16581 } 16582 16583 serializer.endTag(null, TAG_PREFERRED_BACKUP); 16584 serializer.endDocument(); 16585 serializer.flush(); 16586 } catch (Exception e) { 16587 if (DEBUG_BACKUP) { 16588 Slog.e(TAG, "Unable to write preferred activities for backup", e); 16589 } 16590 return null; 16591 } 16592 16593 return dataStream.toByteArray(); 16594 } 16595 16596 @Override 16597 public void restorePreferredActivities(byte[] backup, int userId) { 16598 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16599 throw new SecurityException("Only the system may call restorePreferredActivities()"); 16600 } 16601 16602 try { 16603 final XmlPullParser parser = Xml.newPullParser(); 16604 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16605 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 16606 new BlobXmlRestorer() { 16607 @Override 16608 public void apply(XmlPullParser parser, int userId) 16609 throws XmlPullParserException, IOException { 16610 synchronized (mPackages) { 16611 mSettings.readPreferredActivitiesLPw(parser, userId); 16612 } 16613 } 16614 } ); 16615 } catch (Exception e) { 16616 if (DEBUG_BACKUP) { 16617 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16618 } 16619 } 16620 } 16621 16622 /** 16623 * Non-Binder method, support for the backup/restore mechanism: write the 16624 * default browser (etc) settings in its canonical XML format. Returns the default 16625 * browser XML representation as a byte array, or null if there is none. 16626 */ 16627 @Override 16628 public byte[] getDefaultAppsBackup(int userId) { 16629 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16630 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 16631 } 16632 16633 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16634 try { 16635 final XmlSerializer serializer = new FastXmlSerializer(); 16636 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16637 serializer.startDocument(null, true); 16638 serializer.startTag(null, TAG_DEFAULT_APPS); 16639 16640 synchronized (mPackages) { 16641 mSettings.writeDefaultAppsLPr(serializer, userId); 16642 } 16643 16644 serializer.endTag(null, TAG_DEFAULT_APPS); 16645 serializer.endDocument(); 16646 serializer.flush(); 16647 } catch (Exception e) { 16648 if (DEBUG_BACKUP) { 16649 Slog.e(TAG, "Unable to write default apps for backup", e); 16650 } 16651 return null; 16652 } 16653 16654 return dataStream.toByteArray(); 16655 } 16656 16657 @Override 16658 public void restoreDefaultApps(byte[] backup, int userId) { 16659 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16660 throw new SecurityException("Only the system may call restoreDefaultApps()"); 16661 } 16662 16663 try { 16664 final XmlPullParser parser = Xml.newPullParser(); 16665 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16666 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 16667 new BlobXmlRestorer() { 16668 @Override 16669 public void apply(XmlPullParser parser, int userId) 16670 throws XmlPullParserException, IOException { 16671 synchronized (mPackages) { 16672 mSettings.readDefaultAppsLPw(parser, userId); 16673 } 16674 } 16675 } ); 16676 } catch (Exception e) { 16677 if (DEBUG_BACKUP) { 16678 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 16679 } 16680 } 16681 } 16682 16683 @Override 16684 public byte[] getIntentFilterVerificationBackup(int userId) { 16685 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16686 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 16687 } 16688 16689 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16690 try { 16691 final XmlSerializer serializer = new FastXmlSerializer(); 16692 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16693 serializer.startDocument(null, true); 16694 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 16695 16696 synchronized (mPackages) { 16697 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 16698 } 16699 16700 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 16701 serializer.endDocument(); 16702 serializer.flush(); 16703 } catch (Exception e) { 16704 if (DEBUG_BACKUP) { 16705 Slog.e(TAG, "Unable to write default apps for backup", e); 16706 } 16707 return null; 16708 } 16709 16710 return dataStream.toByteArray(); 16711 } 16712 16713 @Override 16714 public void restoreIntentFilterVerification(byte[] backup, int userId) { 16715 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16716 throw new SecurityException("Only the system may call restorePreferredActivities()"); 16717 } 16718 16719 try { 16720 final XmlPullParser parser = Xml.newPullParser(); 16721 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16722 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 16723 new BlobXmlRestorer() { 16724 @Override 16725 public void apply(XmlPullParser parser, int userId) 16726 throws XmlPullParserException, IOException { 16727 synchronized (mPackages) { 16728 mSettings.readAllDomainVerificationsLPr(parser, userId); 16729 mSettings.writeLPr(); 16730 } 16731 } 16732 } ); 16733 } catch (Exception e) { 16734 if (DEBUG_BACKUP) { 16735 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16736 } 16737 } 16738 } 16739 16740 @Override 16741 public byte[] getPermissionGrantBackup(int userId) { 16742 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16743 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 16744 } 16745 16746 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16747 try { 16748 final XmlSerializer serializer = new FastXmlSerializer(); 16749 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16750 serializer.startDocument(null, true); 16751 serializer.startTag(null, TAG_PERMISSION_BACKUP); 16752 16753 synchronized (mPackages) { 16754 serializeRuntimePermissionGrantsLPr(serializer, userId); 16755 } 16756 16757 serializer.endTag(null, TAG_PERMISSION_BACKUP); 16758 serializer.endDocument(); 16759 serializer.flush(); 16760 } catch (Exception e) { 16761 if (DEBUG_BACKUP) { 16762 Slog.e(TAG, "Unable to write default apps for backup", e); 16763 } 16764 return null; 16765 } 16766 16767 return dataStream.toByteArray(); 16768 } 16769 16770 @Override 16771 public void restorePermissionGrants(byte[] backup, int userId) { 16772 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16773 throw new SecurityException("Only the system may call restorePermissionGrants()"); 16774 } 16775 16776 try { 16777 final XmlPullParser parser = Xml.newPullParser(); 16778 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16779 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 16780 new BlobXmlRestorer() { 16781 @Override 16782 public void apply(XmlPullParser parser, int userId) 16783 throws XmlPullParserException, IOException { 16784 synchronized (mPackages) { 16785 processRestoredPermissionGrantsLPr(parser, userId); 16786 } 16787 } 16788 } ); 16789 } catch (Exception e) { 16790 if (DEBUG_BACKUP) { 16791 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16792 } 16793 } 16794 } 16795 16796 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 16797 throws IOException { 16798 serializer.startTag(null, TAG_ALL_GRANTS); 16799 16800 final int N = mSettings.mPackages.size(); 16801 for (int i = 0; i < N; i++) { 16802 final PackageSetting ps = mSettings.mPackages.valueAt(i); 16803 boolean pkgGrantsKnown = false; 16804 16805 PermissionsState packagePerms = ps.getPermissionsState(); 16806 16807 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 16808 final int grantFlags = state.getFlags(); 16809 // only look at grants that are not system/policy fixed 16810 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 16811 final boolean isGranted = state.isGranted(); 16812 // And only back up the user-twiddled state bits 16813 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 16814 final String packageName = mSettings.mPackages.keyAt(i); 16815 if (!pkgGrantsKnown) { 16816 serializer.startTag(null, TAG_GRANT); 16817 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 16818 pkgGrantsKnown = true; 16819 } 16820 16821 final boolean userSet = 16822 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 16823 final boolean userFixed = 16824 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 16825 final boolean revoke = 16826 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 16827 16828 serializer.startTag(null, TAG_PERMISSION); 16829 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 16830 if (isGranted) { 16831 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 16832 } 16833 if (userSet) { 16834 serializer.attribute(null, ATTR_USER_SET, "true"); 16835 } 16836 if (userFixed) { 16837 serializer.attribute(null, ATTR_USER_FIXED, "true"); 16838 } 16839 if (revoke) { 16840 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 16841 } 16842 serializer.endTag(null, TAG_PERMISSION); 16843 } 16844 } 16845 } 16846 16847 if (pkgGrantsKnown) { 16848 serializer.endTag(null, TAG_GRANT); 16849 } 16850 } 16851 16852 serializer.endTag(null, TAG_ALL_GRANTS); 16853 } 16854 16855 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 16856 throws XmlPullParserException, IOException { 16857 String pkgName = null; 16858 int outerDepth = parser.getDepth(); 16859 int type; 16860 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 16861 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 16862 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 16863 continue; 16864 } 16865 16866 final String tagName = parser.getName(); 16867 if (tagName.equals(TAG_GRANT)) { 16868 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 16869 if (DEBUG_BACKUP) { 16870 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 16871 } 16872 } else if (tagName.equals(TAG_PERMISSION)) { 16873 16874 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 16875 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 16876 16877 int newFlagSet = 0; 16878 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 16879 newFlagSet |= FLAG_PERMISSION_USER_SET; 16880 } 16881 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 16882 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 16883 } 16884 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 16885 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 16886 } 16887 if (DEBUG_BACKUP) { 16888 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 16889 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 16890 } 16891 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16892 if (ps != null) { 16893 // Already installed so we apply the grant immediately 16894 if (DEBUG_BACKUP) { 16895 Slog.v(TAG, " + already installed; applying"); 16896 } 16897 PermissionsState perms = ps.getPermissionsState(); 16898 BasePermission bp = mSettings.mPermissions.get(permName); 16899 if (bp != null) { 16900 if (isGranted) { 16901 perms.grantRuntimePermission(bp, userId); 16902 } 16903 if (newFlagSet != 0) { 16904 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 16905 } 16906 } 16907 } else { 16908 // Need to wait for post-restore install to apply the grant 16909 if (DEBUG_BACKUP) { 16910 Slog.v(TAG, " - not yet installed; saving for later"); 16911 } 16912 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 16913 isGranted, newFlagSet, userId); 16914 } 16915 } else { 16916 PackageManagerService.reportSettingsProblem(Log.WARN, 16917 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 16918 XmlUtils.skipCurrentTag(parser); 16919 } 16920 } 16921 16922 scheduleWriteSettingsLocked(); 16923 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 16924 } 16925 16926 @Override 16927 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 16928 int sourceUserId, int targetUserId, int flags) { 16929 mContext.enforceCallingOrSelfPermission( 16930 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 16931 int callingUid = Binder.getCallingUid(); 16932 enforceOwnerRights(ownerPackage, callingUid); 16933 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 16934 if (intentFilter.countActions() == 0) { 16935 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 16936 return; 16937 } 16938 synchronized (mPackages) { 16939 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 16940 ownerPackage, targetUserId, flags); 16941 CrossProfileIntentResolver resolver = 16942 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 16943 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 16944 // We have all those whose filter is equal. Now checking if the rest is equal as well. 16945 if (existing != null) { 16946 int size = existing.size(); 16947 for (int i = 0; i < size; i++) { 16948 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 16949 return; 16950 } 16951 } 16952 } 16953 resolver.addFilter(newFilter); 16954 scheduleWritePackageRestrictionsLocked(sourceUserId); 16955 } 16956 } 16957 16958 @Override 16959 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 16960 mContext.enforceCallingOrSelfPermission( 16961 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 16962 int callingUid = Binder.getCallingUid(); 16963 enforceOwnerRights(ownerPackage, callingUid); 16964 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 16965 synchronized (mPackages) { 16966 CrossProfileIntentResolver resolver = 16967 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 16968 ArraySet<CrossProfileIntentFilter> set = 16969 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 16970 for (CrossProfileIntentFilter filter : set) { 16971 if (filter.getOwnerPackage().equals(ownerPackage)) { 16972 resolver.removeFilter(filter); 16973 } 16974 } 16975 scheduleWritePackageRestrictionsLocked(sourceUserId); 16976 } 16977 } 16978 16979 // Enforcing that callingUid is owning pkg on userId 16980 private void enforceOwnerRights(String pkg, int callingUid) { 16981 // The system owns everything. 16982 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 16983 return; 16984 } 16985 int callingUserId = UserHandle.getUserId(callingUid); 16986 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 16987 if (pi == null) { 16988 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 16989 + callingUserId); 16990 } 16991 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 16992 throw new SecurityException("Calling uid " + callingUid 16993 + " does not own package " + pkg); 16994 } 16995 } 16996 16997 @Override 16998 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 16999 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 17000 } 17001 17002 private Intent getHomeIntent() { 17003 Intent intent = new Intent(Intent.ACTION_MAIN); 17004 intent.addCategory(Intent.CATEGORY_HOME); 17005 return intent; 17006 } 17007 17008 private IntentFilter getHomeFilter() { 17009 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 17010 filter.addCategory(Intent.CATEGORY_HOME); 17011 filter.addCategory(Intent.CATEGORY_DEFAULT); 17012 return filter; 17013 } 17014 17015 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 17016 int userId) { 17017 Intent intent = getHomeIntent(); 17018 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 17019 PackageManager.GET_META_DATA, userId); 17020 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 17021 true, false, false, userId); 17022 17023 allHomeCandidates.clear(); 17024 if (list != null) { 17025 for (ResolveInfo ri : list) { 17026 allHomeCandidates.add(ri); 17027 } 17028 } 17029 return (preferred == null || preferred.activityInfo == null) 17030 ? null 17031 : new ComponentName(preferred.activityInfo.packageName, 17032 preferred.activityInfo.name); 17033 } 17034 17035 @Override 17036 public void setHomeActivity(ComponentName comp, int userId) { 17037 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 17038 getHomeActivitiesAsUser(homeActivities, userId); 17039 17040 boolean found = false; 17041 17042 final int size = homeActivities.size(); 17043 final ComponentName[] set = new ComponentName[size]; 17044 for (int i = 0; i < size; i++) { 17045 final ResolveInfo candidate = homeActivities.get(i); 17046 final ActivityInfo info = candidate.activityInfo; 17047 final ComponentName activityName = new ComponentName(info.packageName, info.name); 17048 set[i] = activityName; 17049 if (!found && activityName.equals(comp)) { 17050 found = true; 17051 } 17052 } 17053 if (!found) { 17054 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 17055 + userId); 17056 } 17057 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 17058 set, comp, userId); 17059 } 17060 17061 private @Nullable String getSetupWizardPackageName() { 17062 final Intent intent = new Intent(Intent.ACTION_MAIN); 17063 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 17064 17065 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 17066 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 17067 | MATCH_DISABLED_COMPONENTS, 17068 UserHandle.myUserId()); 17069 if (matches.size() == 1) { 17070 return matches.get(0).getComponentInfo().packageName; 17071 } else { 17072 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 17073 + ": matches=" + matches); 17074 return null; 17075 } 17076 } 17077 17078 @Override 17079 public void setApplicationEnabledSetting(String appPackageName, 17080 int newState, int flags, int userId, String callingPackage) { 17081 if (!sUserManager.exists(userId)) return; 17082 if (callingPackage == null) { 17083 callingPackage = Integer.toString(Binder.getCallingUid()); 17084 } 17085 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 17086 } 17087 17088 @Override 17089 public void setComponentEnabledSetting(ComponentName componentName, 17090 int newState, int flags, int userId) { 17091 if (!sUserManager.exists(userId)) return; 17092 setEnabledSetting(componentName.getPackageName(), 17093 componentName.getClassName(), newState, flags, userId, null); 17094 } 17095 17096 private void setEnabledSetting(final String packageName, String className, int newState, 17097 final int flags, int userId, String callingPackage) { 17098 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 17099 || newState == COMPONENT_ENABLED_STATE_ENABLED 17100 || newState == COMPONENT_ENABLED_STATE_DISABLED 17101 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17102 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 17103 throw new IllegalArgumentException("Invalid new component state: " 17104 + newState); 17105 } 17106 PackageSetting pkgSetting; 17107 final int uid = Binder.getCallingUid(); 17108 final int permission; 17109 if (uid == Process.SYSTEM_UID) { 17110 permission = PackageManager.PERMISSION_GRANTED; 17111 } else { 17112 permission = mContext.checkCallingOrSelfPermission( 17113 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17114 } 17115 enforceCrossUserPermission(uid, userId, 17116 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 17117 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17118 boolean sendNow = false; 17119 boolean isApp = (className == null); 17120 String componentName = isApp ? packageName : className; 17121 int packageUid = -1; 17122 ArrayList<String> components; 17123 17124 // writer 17125 synchronized (mPackages) { 17126 pkgSetting = mSettings.mPackages.get(packageName); 17127 if (pkgSetting == null) { 17128 if (className == null) { 17129 throw new IllegalArgumentException("Unknown package: " + packageName); 17130 } 17131 throw new IllegalArgumentException( 17132 "Unknown component: " + packageName + "/" + className); 17133 } 17134 // Allow root and verify that userId is not being specified by a different user 17135 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 17136 throw new SecurityException( 17137 "Permission Denial: attempt to change component state from pid=" 17138 + Binder.getCallingPid() 17139 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 17140 } 17141 if (className == null) { 17142 // We're dealing with an application/package level state change 17143 if (pkgSetting.getEnabled(userId) == newState) { 17144 // Nothing to do 17145 return; 17146 } 17147 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 17148 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 17149 // Don't care about who enables an app. 17150 callingPackage = null; 17151 } 17152 pkgSetting.setEnabled(newState, userId, callingPackage); 17153 // pkgSetting.pkg.mSetEnabled = newState; 17154 } else { 17155 // We're dealing with a component level state change 17156 // First, verify that this is a valid class name. 17157 PackageParser.Package pkg = pkgSetting.pkg; 17158 if (pkg == null || !pkg.hasComponentClassName(className)) { 17159 if (pkg != null && 17160 pkg.applicationInfo.targetSdkVersion >= 17161 Build.VERSION_CODES.JELLY_BEAN) { 17162 throw new IllegalArgumentException("Component class " + className 17163 + " does not exist in " + packageName); 17164 } else { 17165 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 17166 + className + " does not exist in " + packageName); 17167 } 17168 } 17169 switch (newState) { 17170 case COMPONENT_ENABLED_STATE_ENABLED: 17171 if (!pkgSetting.enableComponentLPw(className, userId)) { 17172 return; 17173 } 17174 break; 17175 case COMPONENT_ENABLED_STATE_DISABLED: 17176 if (!pkgSetting.disableComponentLPw(className, userId)) { 17177 return; 17178 } 17179 break; 17180 case COMPONENT_ENABLED_STATE_DEFAULT: 17181 if (!pkgSetting.restoreComponentLPw(className, userId)) { 17182 return; 17183 } 17184 break; 17185 default: 17186 Slog.e(TAG, "Invalid new component state: " + newState); 17187 return; 17188 } 17189 } 17190 scheduleWritePackageRestrictionsLocked(userId); 17191 components = mPendingBroadcasts.get(userId, packageName); 17192 final boolean newPackage = components == null; 17193 if (newPackage) { 17194 components = new ArrayList<String>(); 17195 } 17196 if (!components.contains(componentName)) { 17197 components.add(componentName); 17198 } 17199 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 17200 sendNow = true; 17201 // Purge entry from pending broadcast list if another one exists already 17202 // since we are sending one right away. 17203 mPendingBroadcasts.remove(userId, packageName); 17204 } else { 17205 if (newPackage) { 17206 mPendingBroadcasts.put(userId, packageName, components); 17207 } 17208 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 17209 // Schedule a message 17210 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 17211 } 17212 } 17213 } 17214 17215 long callingId = Binder.clearCallingIdentity(); 17216 try { 17217 if (sendNow) { 17218 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 17219 sendPackageChangedBroadcast(packageName, 17220 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 17221 } 17222 } finally { 17223 Binder.restoreCallingIdentity(callingId); 17224 } 17225 } 17226 17227 @Override 17228 public void flushPackageRestrictionsAsUser(int userId) { 17229 if (!sUserManager.exists(userId)) { 17230 return; 17231 } 17232 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 17233 false /* checkShell */, "flushPackageRestrictions"); 17234 synchronized (mPackages) { 17235 mSettings.writePackageRestrictionsLPr(userId); 17236 mDirtyUsers.remove(userId); 17237 if (mDirtyUsers.isEmpty()) { 17238 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 17239 } 17240 } 17241 } 17242 17243 private void sendPackageChangedBroadcast(String packageName, 17244 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 17245 if (DEBUG_INSTALL) 17246 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 17247 + componentNames); 17248 Bundle extras = new Bundle(4); 17249 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 17250 String nameList[] = new String[componentNames.size()]; 17251 componentNames.toArray(nameList); 17252 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 17253 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 17254 extras.putInt(Intent.EXTRA_UID, packageUid); 17255 // If this is not reporting a change of the overall package, then only send it 17256 // to registered receivers. We don't want to launch a swath of apps for every 17257 // little component state change. 17258 final int flags = !componentNames.contains(packageName) 17259 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 17260 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 17261 new int[] {UserHandle.getUserId(packageUid)}); 17262 } 17263 17264 @Override 17265 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 17266 if (!sUserManager.exists(userId)) return; 17267 final int uid = Binder.getCallingUid(); 17268 final int permission = mContext.checkCallingOrSelfPermission( 17269 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17270 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17271 enforceCrossUserPermission(uid, userId, 17272 true /* requireFullPermission */, true /* checkShell */, "stop package"); 17273 // writer 17274 synchronized (mPackages) { 17275 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 17276 allowedByPermission, uid, userId)) { 17277 scheduleWritePackageRestrictionsLocked(userId); 17278 } 17279 } 17280 } 17281 17282 @Override 17283 public String getInstallerPackageName(String packageName) { 17284 // reader 17285 synchronized (mPackages) { 17286 return mSettings.getInstallerPackageNameLPr(packageName); 17287 } 17288 } 17289 17290 @Override 17291 public int getApplicationEnabledSetting(String packageName, int userId) { 17292 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17293 int uid = Binder.getCallingUid(); 17294 enforceCrossUserPermission(uid, userId, 17295 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 17296 // reader 17297 synchronized (mPackages) { 17298 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 17299 } 17300 } 17301 17302 @Override 17303 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 17304 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17305 int uid = Binder.getCallingUid(); 17306 enforceCrossUserPermission(uid, userId, 17307 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 17308 // reader 17309 synchronized (mPackages) { 17310 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 17311 } 17312 } 17313 17314 @Override 17315 public void enterSafeMode() { 17316 enforceSystemOrRoot("Only the system can request entering safe mode"); 17317 17318 if (!mSystemReady) { 17319 mSafeMode = true; 17320 } 17321 } 17322 17323 @Override 17324 public void systemReady() { 17325 mSystemReady = true; 17326 17327 // Read the compatibilty setting when the system is ready. 17328 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 17329 mContext.getContentResolver(), 17330 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 17331 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 17332 if (DEBUG_SETTINGS) { 17333 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 17334 } 17335 17336 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 17337 17338 synchronized (mPackages) { 17339 // Verify that all of the preferred activity components actually 17340 // exist. It is possible for applications to be updated and at 17341 // that point remove a previously declared activity component that 17342 // had been set as a preferred activity. We try to clean this up 17343 // the next time we encounter that preferred activity, but it is 17344 // possible for the user flow to never be able to return to that 17345 // situation so here we do a sanity check to make sure we haven't 17346 // left any junk around. 17347 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 17348 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17349 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17350 removed.clear(); 17351 for (PreferredActivity pa : pir.filterSet()) { 17352 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 17353 removed.add(pa); 17354 } 17355 } 17356 if (removed.size() > 0) { 17357 for (int r=0; r<removed.size(); r++) { 17358 PreferredActivity pa = removed.get(r); 17359 Slog.w(TAG, "Removing dangling preferred activity: " 17360 + pa.mPref.mComponent); 17361 pir.removeFilter(pa); 17362 } 17363 mSettings.writePackageRestrictionsLPr( 17364 mSettings.mPreferredActivities.keyAt(i)); 17365 } 17366 } 17367 17368 for (int userId : UserManagerService.getInstance().getUserIds()) { 17369 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 17370 grantPermissionsUserIds = ArrayUtils.appendInt( 17371 grantPermissionsUserIds, userId); 17372 } 17373 } 17374 } 17375 sUserManager.systemReady(); 17376 17377 // If we upgraded grant all default permissions before kicking off. 17378 for (int userId : grantPermissionsUserIds) { 17379 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 17380 } 17381 17382 // Kick off any messages waiting for system ready 17383 if (mPostSystemReadyMessages != null) { 17384 for (Message msg : mPostSystemReadyMessages) { 17385 msg.sendToTarget(); 17386 } 17387 mPostSystemReadyMessages = null; 17388 } 17389 17390 // Watch for external volumes that come and go over time 17391 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17392 storage.registerListener(mStorageListener); 17393 17394 mInstallerService.systemReady(); 17395 mPackageDexOptimizer.systemReady(); 17396 17397 MountServiceInternal mountServiceInternal = LocalServices.getService( 17398 MountServiceInternal.class); 17399 mountServiceInternal.addExternalStoragePolicy( 17400 new MountServiceInternal.ExternalStorageMountPolicy() { 17401 @Override 17402 public int getMountMode(int uid, String packageName) { 17403 if (Process.isIsolated(uid)) { 17404 return Zygote.MOUNT_EXTERNAL_NONE; 17405 } 17406 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 17407 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17408 } 17409 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17410 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17411 } 17412 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17413 return Zygote.MOUNT_EXTERNAL_READ; 17414 } 17415 return Zygote.MOUNT_EXTERNAL_WRITE; 17416 } 17417 17418 @Override 17419 public boolean hasExternalStorage(int uid, String packageName) { 17420 return true; 17421 } 17422 }); 17423 17424 // Now that we're mostly running, clean up stale users and apps 17425 reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 17426 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 17427 } 17428 17429 @Override 17430 public boolean isSafeMode() { 17431 return mSafeMode; 17432 } 17433 17434 @Override 17435 public boolean hasSystemUidErrors() { 17436 return mHasSystemUidErrors; 17437 } 17438 17439 static String arrayToString(int[] array) { 17440 StringBuffer buf = new StringBuffer(128); 17441 buf.append('['); 17442 if (array != null) { 17443 for (int i=0; i<array.length; i++) { 17444 if (i > 0) buf.append(", "); 17445 buf.append(array[i]); 17446 } 17447 } 17448 buf.append(']'); 17449 return buf.toString(); 17450 } 17451 17452 static class DumpState { 17453 public static final int DUMP_LIBS = 1 << 0; 17454 public static final int DUMP_FEATURES = 1 << 1; 17455 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 17456 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 17457 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 17458 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 17459 public static final int DUMP_PERMISSIONS = 1 << 6; 17460 public static final int DUMP_PACKAGES = 1 << 7; 17461 public static final int DUMP_SHARED_USERS = 1 << 8; 17462 public static final int DUMP_MESSAGES = 1 << 9; 17463 public static final int DUMP_PROVIDERS = 1 << 10; 17464 public static final int DUMP_VERIFIERS = 1 << 11; 17465 public static final int DUMP_PREFERRED = 1 << 12; 17466 public static final int DUMP_PREFERRED_XML = 1 << 13; 17467 public static final int DUMP_KEYSETS = 1 << 14; 17468 public static final int DUMP_VERSION = 1 << 15; 17469 public static final int DUMP_INSTALLS = 1 << 16; 17470 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 17471 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 17472 public static final int DUMP_FROZEN = 1 << 19; 17473 17474 public static final int OPTION_SHOW_FILTERS = 1 << 0; 17475 17476 private int mTypes; 17477 17478 private int mOptions; 17479 17480 private boolean mTitlePrinted; 17481 17482 private SharedUserSetting mSharedUser; 17483 17484 public boolean isDumping(int type) { 17485 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 17486 return true; 17487 } 17488 17489 return (mTypes & type) != 0; 17490 } 17491 17492 public void setDump(int type) { 17493 mTypes |= type; 17494 } 17495 17496 public boolean isOptionEnabled(int option) { 17497 return (mOptions & option) != 0; 17498 } 17499 17500 public void setOptionEnabled(int option) { 17501 mOptions |= option; 17502 } 17503 17504 public boolean onTitlePrinted() { 17505 final boolean printed = mTitlePrinted; 17506 mTitlePrinted = true; 17507 return printed; 17508 } 17509 17510 public boolean getTitlePrinted() { 17511 return mTitlePrinted; 17512 } 17513 17514 public void setTitlePrinted(boolean enabled) { 17515 mTitlePrinted = enabled; 17516 } 17517 17518 public SharedUserSetting getSharedUser() { 17519 return mSharedUser; 17520 } 17521 17522 public void setSharedUser(SharedUserSetting user) { 17523 mSharedUser = user; 17524 } 17525 } 17526 17527 @Override 17528 public void onShellCommand(FileDescriptor in, FileDescriptor out, 17529 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 17530 (new PackageManagerShellCommand(this)).exec( 17531 this, in, out, err, args, resultReceiver); 17532 } 17533 17534 @Override 17535 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 17536 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 17537 != PackageManager.PERMISSION_GRANTED) { 17538 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 17539 + Binder.getCallingPid() 17540 + ", uid=" + Binder.getCallingUid() 17541 + " without permission " 17542 + android.Manifest.permission.DUMP); 17543 return; 17544 } 17545 17546 DumpState dumpState = new DumpState(); 17547 boolean fullPreferred = false; 17548 boolean checkin = false; 17549 17550 String packageName = null; 17551 ArraySet<String> permissionNames = null; 17552 17553 int opti = 0; 17554 while (opti < args.length) { 17555 String opt = args[opti]; 17556 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 17557 break; 17558 } 17559 opti++; 17560 17561 if ("-a".equals(opt)) { 17562 // Right now we only know how to print all. 17563 } else if ("-h".equals(opt)) { 17564 pw.println("Package manager dump options:"); 17565 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 17566 pw.println(" --checkin: dump for a checkin"); 17567 pw.println(" -f: print details of intent filters"); 17568 pw.println(" -h: print this help"); 17569 pw.println(" cmd may be one of:"); 17570 pw.println(" l[ibraries]: list known shared libraries"); 17571 pw.println(" f[eatures]: list device features"); 17572 pw.println(" k[eysets]: print known keysets"); 17573 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 17574 pw.println(" perm[issions]: dump permissions"); 17575 pw.println(" permission [name ...]: dump declaration and use of given permission"); 17576 pw.println(" pref[erred]: print preferred package settings"); 17577 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 17578 pw.println(" prov[iders]: dump content providers"); 17579 pw.println(" p[ackages]: dump installed packages"); 17580 pw.println(" s[hared-users]: dump shared user IDs"); 17581 pw.println(" m[essages]: print collected runtime messages"); 17582 pw.println(" v[erifiers]: print package verifier info"); 17583 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 17584 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 17585 pw.println(" version: print database version info"); 17586 pw.println(" write: write current settings now"); 17587 pw.println(" installs: details about install sessions"); 17588 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 17589 pw.println(" <package.name>: info about given package"); 17590 return; 17591 } else if ("--checkin".equals(opt)) { 17592 checkin = true; 17593 } else if ("-f".equals(opt)) { 17594 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 17595 } else { 17596 pw.println("Unknown argument: " + opt + "; use -h for help"); 17597 } 17598 } 17599 17600 // Is the caller requesting to dump a particular piece of data? 17601 if (opti < args.length) { 17602 String cmd = args[opti]; 17603 opti++; 17604 // Is this a package name? 17605 if ("android".equals(cmd) || cmd.contains(".")) { 17606 packageName = cmd; 17607 // When dumping a single package, we always dump all of its 17608 // filter information since the amount of data will be reasonable. 17609 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 17610 } else if ("check-permission".equals(cmd)) { 17611 if (opti >= args.length) { 17612 pw.println("Error: check-permission missing permission argument"); 17613 return; 17614 } 17615 String perm = args[opti]; 17616 opti++; 17617 if (opti >= args.length) { 17618 pw.println("Error: check-permission missing package argument"); 17619 return; 17620 } 17621 String pkg = args[opti]; 17622 opti++; 17623 int user = UserHandle.getUserId(Binder.getCallingUid()); 17624 if (opti < args.length) { 17625 try { 17626 user = Integer.parseInt(args[opti]); 17627 } catch (NumberFormatException e) { 17628 pw.println("Error: check-permission user argument is not a number: " 17629 + args[opti]); 17630 return; 17631 } 17632 } 17633 pw.println(checkPermission(perm, pkg, user)); 17634 return; 17635 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 17636 dumpState.setDump(DumpState.DUMP_LIBS); 17637 } else if ("f".equals(cmd) || "features".equals(cmd)) { 17638 dumpState.setDump(DumpState.DUMP_FEATURES); 17639 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 17640 if (opti >= args.length) { 17641 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 17642 | DumpState.DUMP_SERVICE_RESOLVERS 17643 | DumpState.DUMP_RECEIVER_RESOLVERS 17644 | DumpState.DUMP_CONTENT_RESOLVERS); 17645 } else { 17646 while (opti < args.length) { 17647 String name = args[opti]; 17648 if ("a".equals(name) || "activity".equals(name)) { 17649 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 17650 } else if ("s".equals(name) || "service".equals(name)) { 17651 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 17652 } else if ("r".equals(name) || "receiver".equals(name)) { 17653 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 17654 } else if ("c".equals(name) || "content".equals(name)) { 17655 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 17656 } else { 17657 pw.println("Error: unknown resolver table type: " + name); 17658 return; 17659 } 17660 opti++; 17661 } 17662 } 17663 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 17664 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 17665 } else if ("permission".equals(cmd)) { 17666 if (opti >= args.length) { 17667 pw.println("Error: permission requires permission name"); 17668 return; 17669 } 17670 permissionNames = new ArraySet<>(); 17671 while (opti < args.length) { 17672 permissionNames.add(args[opti]); 17673 opti++; 17674 } 17675 dumpState.setDump(DumpState.DUMP_PERMISSIONS 17676 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 17677 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 17678 dumpState.setDump(DumpState.DUMP_PREFERRED); 17679 } else if ("preferred-xml".equals(cmd)) { 17680 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 17681 if (opti < args.length && "--full".equals(args[opti])) { 17682 fullPreferred = true; 17683 opti++; 17684 } 17685 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 17686 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 17687 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 17688 dumpState.setDump(DumpState.DUMP_PACKAGES); 17689 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 17690 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 17691 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 17692 dumpState.setDump(DumpState.DUMP_PROVIDERS); 17693 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 17694 dumpState.setDump(DumpState.DUMP_MESSAGES); 17695 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 17696 dumpState.setDump(DumpState.DUMP_VERIFIERS); 17697 } else if ("i".equals(cmd) || "ifv".equals(cmd) 17698 || "intent-filter-verifiers".equals(cmd)) { 17699 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 17700 } else if ("version".equals(cmd)) { 17701 dumpState.setDump(DumpState.DUMP_VERSION); 17702 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 17703 dumpState.setDump(DumpState.DUMP_KEYSETS); 17704 } else if ("installs".equals(cmd)) { 17705 dumpState.setDump(DumpState.DUMP_INSTALLS); 17706 } else if ("frozen".equals(cmd)) { 17707 dumpState.setDump(DumpState.DUMP_FROZEN); 17708 } else if ("write".equals(cmd)) { 17709 synchronized (mPackages) { 17710 mSettings.writeLPr(); 17711 pw.println("Settings written."); 17712 return; 17713 } 17714 } 17715 } 17716 17717 if (checkin) { 17718 pw.println("vers,1"); 17719 } 17720 17721 // reader 17722 synchronized (mPackages) { 17723 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 17724 if (!checkin) { 17725 if (dumpState.onTitlePrinted()) 17726 pw.println(); 17727 pw.println("Database versions:"); 17728 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 17729 } 17730 } 17731 17732 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 17733 if (!checkin) { 17734 if (dumpState.onTitlePrinted()) 17735 pw.println(); 17736 pw.println("Verifiers:"); 17737 pw.print(" Required: "); 17738 pw.print(mRequiredVerifierPackage); 17739 pw.print(" (uid="); 17740 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 17741 UserHandle.USER_SYSTEM)); 17742 pw.println(")"); 17743 } else if (mRequiredVerifierPackage != null) { 17744 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 17745 pw.print(","); 17746 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 17747 UserHandle.USER_SYSTEM)); 17748 } 17749 } 17750 17751 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 17752 packageName == null) { 17753 if (mIntentFilterVerifierComponent != null) { 17754 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 17755 if (!checkin) { 17756 if (dumpState.onTitlePrinted()) 17757 pw.println(); 17758 pw.println("Intent Filter Verifier:"); 17759 pw.print(" Using: "); 17760 pw.print(verifierPackageName); 17761 pw.print(" (uid="); 17762 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 17763 UserHandle.USER_SYSTEM)); 17764 pw.println(")"); 17765 } else if (verifierPackageName != null) { 17766 pw.print("ifv,"); pw.print(verifierPackageName); 17767 pw.print(","); 17768 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 17769 UserHandle.USER_SYSTEM)); 17770 } 17771 } else { 17772 pw.println(); 17773 pw.println("No Intent Filter Verifier available!"); 17774 } 17775 } 17776 17777 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 17778 boolean printedHeader = false; 17779 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 17780 while (it.hasNext()) { 17781 String name = it.next(); 17782 SharedLibraryEntry ent = mSharedLibraries.get(name); 17783 if (!checkin) { 17784 if (!printedHeader) { 17785 if (dumpState.onTitlePrinted()) 17786 pw.println(); 17787 pw.println("Libraries:"); 17788 printedHeader = true; 17789 } 17790 pw.print(" "); 17791 } else { 17792 pw.print("lib,"); 17793 } 17794 pw.print(name); 17795 if (!checkin) { 17796 pw.print(" -> "); 17797 } 17798 if (ent.path != null) { 17799 if (!checkin) { 17800 pw.print("(jar) "); 17801 pw.print(ent.path); 17802 } else { 17803 pw.print(",jar,"); 17804 pw.print(ent.path); 17805 } 17806 } else { 17807 if (!checkin) { 17808 pw.print("(apk) "); 17809 pw.print(ent.apk); 17810 } else { 17811 pw.print(",apk,"); 17812 pw.print(ent.apk); 17813 } 17814 } 17815 pw.println(); 17816 } 17817 } 17818 17819 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 17820 if (dumpState.onTitlePrinted()) 17821 pw.println(); 17822 if (!checkin) { 17823 pw.println("Features:"); 17824 } 17825 17826 for (FeatureInfo feat : mAvailableFeatures.values()) { 17827 if (checkin) { 17828 pw.print("feat,"); 17829 pw.print(feat.name); 17830 pw.print(","); 17831 pw.println(feat.version); 17832 } else { 17833 pw.print(" "); 17834 pw.print(feat.name); 17835 if (feat.version > 0) { 17836 pw.print(" version="); 17837 pw.print(feat.version); 17838 } 17839 pw.println(); 17840 } 17841 } 17842 } 17843 17844 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 17845 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 17846 : "Activity Resolver Table:", " ", packageName, 17847 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17848 dumpState.setTitlePrinted(true); 17849 } 17850 } 17851 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 17852 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 17853 : "Receiver Resolver Table:", " ", packageName, 17854 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17855 dumpState.setTitlePrinted(true); 17856 } 17857 } 17858 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 17859 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 17860 : "Service Resolver Table:", " ", packageName, 17861 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17862 dumpState.setTitlePrinted(true); 17863 } 17864 } 17865 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 17866 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 17867 : "Provider Resolver Table:", " ", packageName, 17868 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17869 dumpState.setTitlePrinted(true); 17870 } 17871 } 17872 17873 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 17874 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17875 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17876 int user = mSettings.mPreferredActivities.keyAt(i); 17877 if (pir.dump(pw, 17878 dumpState.getTitlePrinted() 17879 ? "\nPreferred Activities User " + user + ":" 17880 : "Preferred Activities User " + user + ":", " ", 17881 packageName, true, false)) { 17882 dumpState.setTitlePrinted(true); 17883 } 17884 } 17885 } 17886 17887 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 17888 pw.flush(); 17889 FileOutputStream fout = new FileOutputStream(fd); 17890 BufferedOutputStream str = new BufferedOutputStream(fout); 17891 XmlSerializer serializer = new FastXmlSerializer(); 17892 try { 17893 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 17894 serializer.startDocument(null, true); 17895 serializer.setFeature( 17896 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 17897 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 17898 serializer.endDocument(); 17899 serializer.flush(); 17900 } catch (IllegalArgumentException e) { 17901 pw.println("Failed writing: " + e); 17902 } catch (IllegalStateException e) { 17903 pw.println("Failed writing: " + e); 17904 } catch (IOException e) { 17905 pw.println("Failed writing: " + e); 17906 } 17907 } 17908 17909 if (!checkin 17910 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 17911 && packageName == null) { 17912 pw.println(); 17913 int count = mSettings.mPackages.size(); 17914 if (count == 0) { 17915 pw.println("No applications!"); 17916 pw.println(); 17917 } else { 17918 final String prefix = " "; 17919 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 17920 if (allPackageSettings.size() == 0) { 17921 pw.println("No domain preferred apps!"); 17922 pw.println(); 17923 } else { 17924 pw.println("App verification status:"); 17925 pw.println(); 17926 count = 0; 17927 for (PackageSetting ps : allPackageSettings) { 17928 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 17929 if (ivi == null || ivi.getPackageName() == null) continue; 17930 pw.println(prefix + "Package: " + ivi.getPackageName()); 17931 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 17932 pw.println(prefix + "Status: " + ivi.getStatusString()); 17933 pw.println(); 17934 count++; 17935 } 17936 if (count == 0) { 17937 pw.println(prefix + "No app verification established."); 17938 pw.println(); 17939 } 17940 for (int userId : sUserManager.getUserIds()) { 17941 pw.println("App linkages for user " + userId + ":"); 17942 pw.println(); 17943 count = 0; 17944 for (PackageSetting ps : allPackageSettings) { 17945 final long status = ps.getDomainVerificationStatusForUser(userId); 17946 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 17947 continue; 17948 } 17949 pw.println(prefix + "Package: " + ps.name); 17950 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 17951 String statusStr = IntentFilterVerificationInfo. 17952 getStatusStringFromValue(status); 17953 pw.println(prefix + "Status: " + statusStr); 17954 pw.println(); 17955 count++; 17956 } 17957 if (count == 0) { 17958 pw.println(prefix + "No configured app linkages."); 17959 pw.println(); 17960 } 17961 } 17962 } 17963 } 17964 } 17965 17966 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 17967 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 17968 if (packageName == null && permissionNames == null) { 17969 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 17970 if (iperm == 0) { 17971 if (dumpState.onTitlePrinted()) 17972 pw.println(); 17973 pw.println("AppOp Permissions:"); 17974 } 17975 pw.print(" AppOp Permission "); 17976 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 17977 pw.println(":"); 17978 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 17979 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 17980 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 17981 } 17982 } 17983 } 17984 } 17985 17986 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 17987 boolean printedSomething = false; 17988 for (PackageParser.Provider p : mProviders.mProviders.values()) { 17989 if (packageName != null && !packageName.equals(p.info.packageName)) { 17990 continue; 17991 } 17992 if (!printedSomething) { 17993 if (dumpState.onTitlePrinted()) 17994 pw.println(); 17995 pw.println("Registered ContentProviders:"); 17996 printedSomething = true; 17997 } 17998 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 17999 pw.print(" "); pw.println(p.toString()); 18000 } 18001 printedSomething = false; 18002 for (Map.Entry<String, PackageParser.Provider> entry : 18003 mProvidersByAuthority.entrySet()) { 18004 PackageParser.Provider p = entry.getValue(); 18005 if (packageName != null && !packageName.equals(p.info.packageName)) { 18006 continue; 18007 } 18008 if (!printedSomething) { 18009 if (dumpState.onTitlePrinted()) 18010 pw.println(); 18011 pw.println("ContentProvider Authorities:"); 18012 printedSomething = true; 18013 } 18014 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 18015 pw.print(" "); pw.println(p.toString()); 18016 if (p.info != null && p.info.applicationInfo != null) { 18017 final String appInfo = p.info.applicationInfo.toString(); 18018 pw.print(" applicationInfo="); pw.println(appInfo); 18019 } 18020 } 18021 } 18022 18023 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 18024 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 18025 } 18026 18027 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 18028 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 18029 } 18030 18031 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 18032 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 18033 } 18034 18035 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 18036 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 18037 } 18038 18039 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 18040 // XXX should handle packageName != null by dumping only install data that 18041 // the given package is involved with. 18042 if (dumpState.onTitlePrinted()) pw.println(); 18043 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 18044 } 18045 18046 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 18047 // XXX should handle packageName != null by dumping only install data that 18048 // the given package is involved with. 18049 if (dumpState.onTitlePrinted()) pw.println(); 18050 18051 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18052 ipw.println(); 18053 ipw.println("Frozen packages:"); 18054 ipw.increaseIndent(); 18055 if (mFrozenPackages.size() == 0) { 18056 ipw.println("(none)"); 18057 } else { 18058 for (int i = 0; i < mFrozenPackages.size(); i++) { 18059 ipw.println(mFrozenPackages.valueAt(i)); 18060 } 18061 } 18062 ipw.decreaseIndent(); 18063 } 18064 18065 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 18066 if (dumpState.onTitlePrinted()) pw.println(); 18067 mSettings.dumpReadMessagesLPr(pw, dumpState); 18068 18069 pw.println(); 18070 pw.println("Package warning messages:"); 18071 BufferedReader in = null; 18072 String line = null; 18073 try { 18074 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18075 while ((line = in.readLine()) != null) { 18076 if (line.contains("ignored: updated version")) continue; 18077 pw.println(line); 18078 } 18079 } catch (IOException ignored) { 18080 } finally { 18081 IoUtils.closeQuietly(in); 18082 } 18083 } 18084 18085 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 18086 BufferedReader in = null; 18087 String line = null; 18088 try { 18089 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18090 while ((line = in.readLine()) != null) { 18091 if (line.contains("ignored: updated version")) continue; 18092 pw.print("msg,"); 18093 pw.println(line); 18094 } 18095 } catch (IOException ignored) { 18096 } finally { 18097 IoUtils.closeQuietly(in); 18098 } 18099 } 18100 } 18101 } 18102 18103 private String dumpDomainString(String packageName) { 18104 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 18105 .getList(); 18106 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 18107 18108 ArraySet<String> result = new ArraySet<>(); 18109 if (iviList.size() > 0) { 18110 for (IntentFilterVerificationInfo ivi : iviList) { 18111 for (String host : ivi.getDomains()) { 18112 result.add(host); 18113 } 18114 } 18115 } 18116 if (filters != null && filters.size() > 0) { 18117 for (IntentFilter filter : filters) { 18118 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 18119 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 18120 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 18121 result.addAll(filter.getHostsList()); 18122 } 18123 } 18124 } 18125 18126 StringBuilder sb = new StringBuilder(result.size() * 16); 18127 for (String domain : result) { 18128 if (sb.length() > 0) sb.append(" "); 18129 sb.append(domain); 18130 } 18131 return sb.toString(); 18132 } 18133 18134 // ------- apps on sdcard specific code ------- 18135 static final boolean DEBUG_SD_INSTALL = false; 18136 18137 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 18138 18139 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 18140 18141 private boolean mMediaMounted = false; 18142 18143 static String getEncryptKey() { 18144 try { 18145 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 18146 SD_ENCRYPTION_KEYSTORE_NAME); 18147 if (sdEncKey == null) { 18148 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 18149 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 18150 if (sdEncKey == null) { 18151 Slog.e(TAG, "Failed to create encryption keys"); 18152 return null; 18153 } 18154 } 18155 return sdEncKey; 18156 } catch (NoSuchAlgorithmException nsae) { 18157 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 18158 return null; 18159 } catch (IOException ioe) { 18160 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 18161 return null; 18162 } 18163 } 18164 18165 /* 18166 * Update media status on PackageManager. 18167 */ 18168 @Override 18169 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 18170 int callingUid = Binder.getCallingUid(); 18171 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 18172 throw new SecurityException("Media status can only be updated by the system"); 18173 } 18174 // reader; this apparently protects mMediaMounted, but should probably 18175 // be a different lock in that case. 18176 synchronized (mPackages) { 18177 Log.i(TAG, "Updating external media status from " 18178 + (mMediaMounted ? "mounted" : "unmounted") + " to " 18179 + (mediaStatus ? "mounted" : "unmounted")); 18180 if (DEBUG_SD_INSTALL) 18181 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 18182 + ", mMediaMounted=" + mMediaMounted); 18183 if (mediaStatus == mMediaMounted) { 18184 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 18185 : 0, -1); 18186 mHandler.sendMessage(msg); 18187 return; 18188 } 18189 mMediaMounted = mediaStatus; 18190 } 18191 // Queue up an async operation since the package installation may take a 18192 // little while. 18193 mHandler.post(new Runnable() { 18194 public void run() { 18195 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 18196 } 18197 }); 18198 } 18199 18200 /** 18201 * Called by MountService when the initial ASECs to scan are available. 18202 * Should block until all the ASEC containers are finished being scanned. 18203 */ 18204 public void scanAvailableAsecs() { 18205 updateExternalMediaStatusInner(true, false, false); 18206 } 18207 18208 /* 18209 * Collect information of applications on external media, map them against 18210 * existing containers and update information based on current mount status. 18211 * Please note that we always have to report status if reportStatus has been 18212 * set to true especially when unloading packages. 18213 */ 18214 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 18215 boolean externalStorage) { 18216 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 18217 int[] uidArr = EmptyArray.INT; 18218 18219 final String[] list = PackageHelper.getSecureContainerList(); 18220 if (ArrayUtils.isEmpty(list)) { 18221 Log.i(TAG, "No secure containers found"); 18222 } else { 18223 // Process list of secure containers and categorize them 18224 // as active or stale based on their package internal state. 18225 18226 // reader 18227 synchronized (mPackages) { 18228 for (String cid : list) { 18229 // Leave stages untouched for now; installer service owns them 18230 if (PackageInstallerService.isStageName(cid)) continue; 18231 18232 if (DEBUG_SD_INSTALL) 18233 Log.i(TAG, "Processing container " + cid); 18234 String pkgName = getAsecPackageName(cid); 18235 if (pkgName == null) { 18236 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 18237 continue; 18238 } 18239 if (DEBUG_SD_INSTALL) 18240 Log.i(TAG, "Looking for pkg : " + pkgName); 18241 18242 final PackageSetting ps = mSettings.mPackages.get(pkgName); 18243 if (ps == null) { 18244 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 18245 continue; 18246 } 18247 18248 /* 18249 * Skip packages that are not external if we're unmounting 18250 * external storage. 18251 */ 18252 if (externalStorage && !isMounted && !isExternal(ps)) { 18253 continue; 18254 } 18255 18256 final AsecInstallArgs args = new AsecInstallArgs(cid, 18257 getAppDexInstructionSets(ps), ps.isForwardLocked()); 18258 // The package status is changed only if the code path 18259 // matches between settings and the container id. 18260 if (ps.codePathString != null 18261 && ps.codePathString.startsWith(args.getCodePath())) { 18262 if (DEBUG_SD_INSTALL) { 18263 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 18264 + " at code path: " + ps.codePathString); 18265 } 18266 18267 // We do have a valid package installed on sdcard 18268 processCids.put(args, ps.codePathString); 18269 final int uid = ps.appId; 18270 if (uid != -1) { 18271 uidArr = ArrayUtils.appendInt(uidArr, uid); 18272 } 18273 } else { 18274 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 18275 + ps.codePathString); 18276 } 18277 } 18278 } 18279 18280 Arrays.sort(uidArr); 18281 } 18282 18283 // Process packages with valid entries. 18284 if (isMounted) { 18285 if (DEBUG_SD_INSTALL) 18286 Log.i(TAG, "Loading packages"); 18287 loadMediaPackages(processCids, uidArr, externalStorage); 18288 startCleaningPackages(); 18289 mInstallerService.onSecureContainersAvailable(); 18290 } else { 18291 if (DEBUG_SD_INSTALL) 18292 Log.i(TAG, "Unloading packages"); 18293 unloadMediaPackages(processCids, uidArr, reportStatus); 18294 } 18295 } 18296 18297 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18298 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 18299 final int size = infos.size(); 18300 final String[] packageNames = new String[size]; 18301 final int[] packageUids = new int[size]; 18302 for (int i = 0; i < size; i++) { 18303 final ApplicationInfo info = infos.get(i); 18304 packageNames[i] = info.packageName; 18305 packageUids[i] = info.uid; 18306 } 18307 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 18308 finishedReceiver); 18309 } 18310 18311 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18312 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18313 sendResourcesChangedBroadcast(mediaStatus, replacing, 18314 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 18315 } 18316 18317 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18318 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18319 int size = pkgList.length; 18320 if (size > 0) { 18321 // Send broadcasts here 18322 Bundle extras = new Bundle(); 18323 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 18324 if (uidArr != null) { 18325 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 18326 } 18327 if (replacing) { 18328 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 18329 } 18330 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 18331 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 18332 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 18333 } 18334 } 18335 18336 /* 18337 * Look at potentially valid container ids from processCids If package 18338 * information doesn't match the one on record or package scanning fails, 18339 * the cid is added to list of removeCids. We currently don't delete stale 18340 * containers. 18341 */ 18342 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 18343 boolean externalStorage) { 18344 ArrayList<String> pkgList = new ArrayList<String>(); 18345 Set<AsecInstallArgs> keys = processCids.keySet(); 18346 18347 for (AsecInstallArgs args : keys) { 18348 String codePath = processCids.get(args); 18349 if (DEBUG_SD_INSTALL) 18350 Log.i(TAG, "Loading container : " + args.cid); 18351 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 18352 try { 18353 // Make sure there are no container errors first. 18354 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 18355 Slog.e(TAG, "Failed to mount cid : " + args.cid 18356 + " when installing from sdcard"); 18357 continue; 18358 } 18359 // Check code path here. 18360 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 18361 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 18362 + " does not match one in settings " + codePath); 18363 continue; 18364 } 18365 // Parse package 18366 int parseFlags = mDefParseFlags; 18367 if (args.isExternalAsec()) { 18368 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 18369 } 18370 if (args.isFwdLocked()) { 18371 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 18372 } 18373 18374 synchronized (mInstallLock) { 18375 PackageParser.Package pkg = null; 18376 try { 18377 // Sadly we don't know the package name yet to freeze it 18378 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 18379 SCAN_IGNORE_FROZEN, 0, null); 18380 } catch (PackageManagerException e) { 18381 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 18382 } 18383 // Scan the package 18384 if (pkg != null) { 18385 /* 18386 * TODO why is the lock being held? doPostInstall is 18387 * called in other places without the lock. This needs 18388 * to be straightened out. 18389 */ 18390 // writer 18391 synchronized (mPackages) { 18392 retCode = PackageManager.INSTALL_SUCCEEDED; 18393 pkgList.add(pkg.packageName); 18394 // Post process args 18395 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 18396 pkg.applicationInfo.uid); 18397 } 18398 } else { 18399 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 18400 } 18401 } 18402 18403 } finally { 18404 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 18405 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 18406 } 18407 } 18408 } 18409 // writer 18410 synchronized (mPackages) { 18411 // If the platform SDK has changed since the last time we booted, 18412 // we need to re-grant app permission to catch any new ones that 18413 // appear. This is really a hack, and means that apps can in some 18414 // cases get permissions that the user didn't initially explicitly 18415 // allow... it would be nice to have some better way to handle 18416 // this situation. 18417 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 18418 : mSettings.getInternalVersion(); 18419 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 18420 : StorageManager.UUID_PRIVATE_INTERNAL; 18421 18422 int updateFlags = UPDATE_PERMISSIONS_ALL; 18423 if (ver.sdkVersion != mSdkVersion) { 18424 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 18425 + mSdkVersion + "; regranting permissions for external"); 18426 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 18427 } 18428 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 18429 18430 // Yay, everything is now upgraded 18431 ver.forceCurrent(); 18432 18433 // can downgrade to reader 18434 // Persist settings 18435 mSettings.writeLPr(); 18436 } 18437 // Send a broadcast to let everyone know we are done processing 18438 if (pkgList.size() > 0) { 18439 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 18440 } 18441 } 18442 18443 /* 18444 * Utility method to unload a list of specified containers 18445 */ 18446 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 18447 // Just unmount all valid containers. 18448 for (AsecInstallArgs arg : cidArgs) { 18449 synchronized (mInstallLock) { 18450 arg.doPostDeleteLI(false); 18451 } 18452 } 18453 } 18454 18455 /* 18456 * Unload packages mounted on external media. This involves deleting package 18457 * data from internal structures, sending broadcasts about disabled packages, 18458 * gc'ing to free up references, unmounting all secure containers 18459 * corresponding to packages on external media, and posting a 18460 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 18461 * that we always have to post this message if status has been requested no 18462 * matter what. 18463 */ 18464 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 18465 final boolean reportStatus) { 18466 if (DEBUG_SD_INSTALL) 18467 Log.i(TAG, "unloading media packages"); 18468 ArrayList<String> pkgList = new ArrayList<String>(); 18469 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 18470 final Set<AsecInstallArgs> keys = processCids.keySet(); 18471 for (AsecInstallArgs args : keys) { 18472 String pkgName = args.getPackageName(); 18473 if (DEBUG_SD_INSTALL) 18474 Log.i(TAG, "Trying to unload pkg : " + pkgName); 18475 // Delete package internally 18476 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 18477 synchronized (mInstallLock) { 18478 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 18479 final boolean res; 18480 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 18481 "unloadMediaPackages")) { 18482 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 18483 null); 18484 } 18485 if (res) { 18486 pkgList.add(pkgName); 18487 } else { 18488 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 18489 failedList.add(args); 18490 } 18491 } 18492 } 18493 18494 // reader 18495 synchronized (mPackages) { 18496 // We didn't update the settings after removing each package; 18497 // write them now for all packages. 18498 mSettings.writeLPr(); 18499 } 18500 18501 // We have to absolutely send UPDATED_MEDIA_STATUS only 18502 // after confirming that all the receivers processed the ordered 18503 // broadcast when packages get disabled, force a gc to clean things up. 18504 // and unload all the containers. 18505 if (pkgList.size() > 0) { 18506 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 18507 new IIntentReceiver.Stub() { 18508 public void performReceive(Intent intent, int resultCode, String data, 18509 Bundle extras, boolean ordered, boolean sticky, 18510 int sendingUser) throws RemoteException { 18511 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 18512 reportStatus ? 1 : 0, 1, keys); 18513 mHandler.sendMessage(msg); 18514 } 18515 }); 18516 } else { 18517 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 18518 keys); 18519 mHandler.sendMessage(msg); 18520 } 18521 } 18522 18523 private void loadPrivatePackages(final VolumeInfo vol) { 18524 mHandler.post(new Runnable() { 18525 @Override 18526 public void run() { 18527 loadPrivatePackagesInner(vol); 18528 } 18529 }); 18530 } 18531 18532 private void loadPrivatePackagesInner(VolumeInfo vol) { 18533 final String volumeUuid = vol.fsUuid; 18534 if (TextUtils.isEmpty(volumeUuid)) { 18535 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 18536 return; 18537 } 18538 18539 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 18540 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 18541 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 18542 18543 final VersionInfo ver; 18544 final List<PackageSetting> packages; 18545 synchronized (mPackages) { 18546 ver = mSettings.findOrCreateVersion(volumeUuid); 18547 packages = mSettings.getVolumePackagesLPr(volumeUuid); 18548 } 18549 18550 for (PackageSetting ps : packages) { 18551 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 18552 synchronized (mInstallLock) { 18553 final PackageParser.Package pkg; 18554 try { 18555 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 18556 loaded.add(pkg.applicationInfo); 18557 18558 } catch (PackageManagerException e) { 18559 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 18560 } 18561 18562 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 18563 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 18564 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 18565 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 18566 } 18567 } 18568 } 18569 18570 // Reconcile app data for all started/unlocked users 18571 final StorageManager sm = mContext.getSystemService(StorageManager.class); 18572 final UserManager um = mContext.getSystemService(UserManager.class); 18573 for (UserInfo user : um.getUsers()) { 18574 final int flags; 18575 if (um.isUserUnlocked(user.id)) { 18576 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18577 } else if (um.isUserRunning(user.id)) { 18578 flags = StorageManager.FLAG_STORAGE_DE; 18579 } else { 18580 continue; 18581 } 18582 18583 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 18584 synchronized (mInstallLock) { 18585 reconcileAppsDataLI(volumeUuid, user.id, flags); 18586 } 18587 } 18588 18589 synchronized (mPackages) { 18590 int updateFlags = UPDATE_PERMISSIONS_ALL; 18591 if (ver.sdkVersion != mSdkVersion) { 18592 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 18593 + mSdkVersion + "; regranting permissions for " + volumeUuid); 18594 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 18595 } 18596 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 18597 18598 // Yay, everything is now upgraded 18599 ver.forceCurrent(); 18600 18601 mSettings.writeLPr(); 18602 } 18603 18604 for (PackageFreezer freezer : freezers) { 18605 freezer.close(); 18606 } 18607 18608 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 18609 sendResourcesChangedBroadcast(true, false, loaded, null); 18610 } 18611 18612 private void unloadPrivatePackages(final VolumeInfo vol) { 18613 mHandler.post(new Runnable() { 18614 @Override 18615 public void run() { 18616 unloadPrivatePackagesInner(vol); 18617 } 18618 }); 18619 } 18620 18621 private void unloadPrivatePackagesInner(VolumeInfo vol) { 18622 final String volumeUuid = vol.fsUuid; 18623 if (TextUtils.isEmpty(volumeUuid)) { 18624 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 18625 return; 18626 } 18627 18628 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 18629 synchronized (mInstallLock) { 18630 synchronized (mPackages) { 18631 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 18632 for (PackageSetting ps : packages) { 18633 if (ps.pkg == null) continue; 18634 18635 final ApplicationInfo info = ps.pkg.applicationInfo; 18636 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 18637 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 18638 18639 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 18640 "unloadPrivatePackagesInner")) { 18641 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 18642 false, null)) { 18643 unloaded.add(info); 18644 } else { 18645 Slog.w(TAG, "Failed to unload " + ps.codePath); 18646 } 18647 } 18648 } 18649 18650 mSettings.writeLPr(); 18651 } 18652 } 18653 18654 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 18655 sendResourcesChangedBroadcast(false, false, unloaded, null); 18656 } 18657 18658 /** 18659 * Prepare storage areas for given user on all mounted devices. 18660 */ 18661 void prepareUserData(int userId, int userSerial, int flags) { 18662 synchronized (mInstallLock) { 18663 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18664 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 18665 final String volumeUuid = vol.getFsUuid(); 18666 prepareUserDataLI(volumeUuid, userId, userSerial, flags, true); 18667 } 18668 } 18669 } 18670 18671 private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags, 18672 boolean allowRecover) { 18673 // Prepare storage and verify that serial numbers are consistent; if 18674 // there's a mismatch we need to destroy to avoid leaking data 18675 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18676 try { 18677 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags); 18678 18679 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 18680 UserManagerService.enforceSerialNumber( 18681 Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial); 18682 } 18683 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18684 UserManagerService.enforceSerialNumber( 18685 Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial); 18686 } 18687 18688 synchronized (mInstallLock) { 18689 mInstaller.createUserData(volumeUuid, userId, userSerial, flags); 18690 } 18691 } catch (Exception e) { 18692 logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid 18693 + " because we failed to prepare: " + e); 18694 destroyUserDataLI(volumeUuid, userId, flags); 18695 18696 if (allowRecover) { 18697 // Try one last time; if we fail again we're really in trouble 18698 prepareUserDataLI(volumeUuid, userId, userSerial, flags, false); 18699 } 18700 } 18701 } 18702 18703 /** 18704 * Destroy storage areas for given user on all mounted devices. 18705 */ 18706 void destroyUserData(int userId, int flags) { 18707 synchronized (mInstallLock) { 18708 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18709 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 18710 final String volumeUuid = vol.getFsUuid(); 18711 destroyUserDataLI(volumeUuid, userId, flags); 18712 } 18713 } 18714 } 18715 18716 private void destroyUserDataLI(String volumeUuid, int userId, int flags) { 18717 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18718 try { 18719 // Clean up app data, profile data, and media data 18720 mInstaller.destroyUserData(volumeUuid, userId, flags); 18721 18722 // Clean up system data 18723 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 18724 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 18725 FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId)); 18726 FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId)); 18727 } 18728 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18729 FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId)); 18730 } 18731 } 18732 18733 // Data with special labels is now gone, so finish the job 18734 storage.destroyUserStorage(volumeUuid, userId, flags); 18735 18736 } catch (Exception e) { 18737 logCriticalInfo(Log.WARN, 18738 "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e); 18739 } 18740 } 18741 18742 /** 18743 * Examine all users present on given mounted volume, and destroy data 18744 * belonging to users that are no longer valid, or whose user ID has been 18745 * recycled. 18746 */ 18747 private void reconcileUsers(String volumeUuid) { 18748 final List<File> files = new ArrayList<>(); 18749 Collections.addAll(files, FileUtils 18750 .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid))); 18751 Collections.addAll(files, FileUtils 18752 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid))); 18753 for (File file : files) { 18754 if (!file.isDirectory()) continue; 18755 18756 final int userId; 18757 final UserInfo info; 18758 try { 18759 userId = Integer.parseInt(file.getName()); 18760 info = sUserManager.getUserInfo(userId); 18761 } catch (NumberFormatException e) { 18762 Slog.w(TAG, "Invalid user directory " + file); 18763 continue; 18764 } 18765 18766 boolean destroyUser = false; 18767 if (info == null) { 18768 logCriticalInfo(Log.WARN, "Destroying user directory " + file 18769 + " because no matching user was found"); 18770 destroyUser = true; 18771 } else { 18772 try { 18773 UserManagerService.enforceSerialNumber(file, info.serialNumber); 18774 } catch (IOException e) { 18775 logCriticalInfo(Log.WARN, "Destroying user directory " + file 18776 + " because we failed to enforce serial number: " + e); 18777 destroyUser = true; 18778 } 18779 } 18780 18781 if (destroyUser) { 18782 synchronized (mInstallLock) { 18783 destroyUserDataLI(volumeUuid, userId, 18784 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18785 } 18786 } 18787 } 18788 } 18789 18790 private void assertPackageKnown(String volumeUuid, String packageName) 18791 throws PackageManagerException { 18792 synchronized (mPackages) { 18793 final PackageSetting ps = mSettings.mPackages.get(packageName); 18794 if (ps == null) { 18795 throw new PackageManagerException("Package " + packageName + " is unknown"); 18796 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 18797 throw new PackageManagerException( 18798 "Package " + packageName + " found on unknown volume " + volumeUuid 18799 + "; expected volume " + ps.volumeUuid); 18800 } 18801 } 18802 } 18803 18804 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 18805 throws PackageManagerException { 18806 synchronized (mPackages) { 18807 final PackageSetting ps = mSettings.mPackages.get(packageName); 18808 if (ps == null) { 18809 throw new PackageManagerException("Package " + packageName + " is unknown"); 18810 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 18811 throw new PackageManagerException( 18812 "Package " + packageName + " found on unknown volume " + volumeUuid 18813 + "; expected volume " + ps.volumeUuid); 18814 } else if (!ps.getInstalled(userId)) { 18815 throw new PackageManagerException( 18816 "Package " + packageName + " not installed for user " + userId); 18817 } 18818 } 18819 } 18820 18821 /** 18822 * Examine all apps present on given mounted volume, and destroy apps that 18823 * aren't expected, either due to uninstallation or reinstallation on 18824 * another volume. 18825 */ 18826 private void reconcileApps(String volumeUuid) { 18827 final File[] files = FileUtils 18828 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 18829 for (File file : files) { 18830 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 18831 && !PackageInstallerService.isStageName(file.getName()); 18832 if (!isPackage) { 18833 // Ignore entries which are not packages 18834 continue; 18835 } 18836 18837 try { 18838 final PackageLite pkg = PackageParser.parsePackageLite(file, 18839 PackageParser.PARSE_MUST_BE_APK); 18840 assertPackageKnown(volumeUuid, pkg.packageName); 18841 18842 } catch (PackageParserException | PackageManagerException e) { 18843 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 18844 synchronized (mInstallLock) { 18845 removeCodePathLI(file); 18846 } 18847 } 18848 } 18849 } 18850 18851 /** 18852 * Reconcile all app data for the given user. 18853 * <p> 18854 * Verifies that directories exist and that ownership and labeling is 18855 * correct for all installed apps on all mounted volumes. 18856 */ 18857 void reconcileAppsData(int userId, int flags) { 18858 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18859 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 18860 final String volumeUuid = vol.getFsUuid(); 18861 synchronized (mInstallLock) { 18862 reconcileAppsDataLI(volumeUuid, userId, flags); 18863 } 18864 } 18865 } 18866 18867 /** 18868 * Reconcile all app data on given mounted volume. 18869 * <p> 18870 * Destroys app data that isn't expected, either due to uninstallation or 18871 * reinstallation on another volume. 18872 * <p> 18873 * Verifies that directories exist and that ownership and labeling is 18874 * correct for all installed apps. 18875 */ 18876 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) { 18877 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 18878 + Integer.toHexString(flags)); 18879 18880 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 18881 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 18882 18883 boolean restoreconNeeded = false; 18884 18885 // First look for stale data that doesn't belong, and check if things 18886 // have changed since we did our last restorecon 18887 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18888 if (!isUserKeyUnlocked(userId)) { 18889 throw new RuntimeException( 18890 "Yikes, someone asked us to reconcile CE storage while " + userId 18891 + " was still locked; this would have caused massive data loss!"); 18892 } 18893 18894 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 18895 18896 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 18897 for (File file : files) { 18898 final String packageName = file.getName(); 18899 try { 18900 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 18901 } catch (PackageManagerException e) { 18902 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 18903 try { 18904 mInstaller.destroyAppData(volumeUuid, packageName, userId, 18905 StorageManager.FLAG_STORAGE_CE, 0); 18906 } catch (InstallerException e2) { 18907 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 18908 } 18909 } 18910 } 18911 } 18912 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 18913 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 18914 18915 final File[] files = FileUtils.listFilesOrEmpty(deDir); 18916 for (File file : files) { 18917 final String packageName = file.getName(); 18918 try { 18919 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 18920 } catch (PackageManagerException e) { 18921 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 18922 try { 18923 mInstaller.destroyAppData(volumeUuid, packageName, userId, 18924 StorageManager.FLAG_STORAGE_DE, 0); 18925 } catch (InstallerException e2) { 18926 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 18927 } 18928 } 18929 } 18930 } 18931 18932 // Ensure that data directories are ready to roll for all packages 18933 // installed for this volume and user 18934 final List<PackageSetting> packages; 18935 synchronized (mPackages) { 18936 packages = mSettings.getVolumePackagesLPr(volumeUuid); 18937 } 18938 int preparedCount = 0; 18939 for (PackageSetting ps : packages) { 18940 final String packageName = ps.name; 18941 if (ps.pkg == null) { 18942 Slog.w(TAG, "Odd, missing scanned package " + packageName); 18943 // TODO: might be due to legacy ASEC apps; we should circle back 18944 // and reconcile again once they're scanned 18945 continue; 18946 } 18947 18948 if (ps.getInstalled(userId)) { 18949 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 18950 18951 if (maybeMigrateAppDataLIF(ps.pkg, userId)) { 18952 // We may have just shuffled around app data directories, so 18953 // prepare them one more time 18954 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 18955 } 18956 18957 preparedCount++; 18958 } 18959 } 18960 18961 if (restoreconNeeded) { 18962 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18963 SELinuxMMAC.setRestoreconDone(ceDir); 18964 } 18965 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 18966 SELinuxMMAC.setRestoreconDone(deDir); 18967 } 18968 } 18969 18970 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 18971 + " packages; restoreconNeeded was " + restoreconNeeded); 18972 } 18973 18974 /** 18975 * Prepare app data for the given app just after it was installed or 18976 * upgraded. This method carefully only touches users that it's installed 18977 * for, and it forces a restorecon to handle any seinfo changes. 18978 * <p> 18979 * Verifies that directories exist and that ownership and labeling is 18980 * correct for all installed apps. If there is an ownership mismatch, it 18981 * will try recovering system apps by wiping data; third-party app data is 18982 * left intact. 18983 * <p> 18984 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 18985 */ 18986 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 18987 final PackageSetting ps; 18988 synchronized (mPackages) { 18989 ps = mSettings.mPackages.get(pkg.packageName); 18990 mSettings.writeKernelMappingLPr(ps); 18991 } 18992 18993 final UserManager um = mContext.getSystemService(UserManager.class); 18994 for (UserInfo user : um.getUsers()) { 18995 final int flags; 18996 if (um.isUserUnlocked(user.id)) { 18997 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18998 } else if (um.isUserRunning(user.id)) { 18999 flags = StorageManager.FLAG_STORAGE_DE; 19000 } else { 19001 continue; 19002 } 19003 19004 if (ps.getInstalled(user.id)) { 19005 // Whenever an app changes, force a restorecon of its data 19006 // TODO: when user data is locked, mark that we're still dirty 19007 prepareAppDataLIF(pkg, user.id, flags, true); 19008 } 19009 } 19010 } 19011 19012 /** 19013 * Prepare app data for the given app. 19014 * <p> 19015 * Verifies that directories exist and that ownership and labeling is 19016 * correct for all installed apps. If there is an ownership mismatch, this 19017 * will try recovering system apps by wiping data; third-party app data is 19018 * left intact. 19019 */ 19020 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags, 19021 boolean restoreconNeeded) { 19022 if (pkg == null) { 19023 Slog.wtf(TAG, "Package was null!", new Throwable()); 19024 return; 19025 } 19026 prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded); 19027 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19028 for (int i = 0; i < childCount; i++) { 19029 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded); 19030 } 19031 } 19032 19033 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags, 19034 boolean restoreconNeeded) { 19035 if (DEBUG_APP_DATA) { 19036 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 19037 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 19038 } 19039 19040 final String volumeUuid = pkg.volumeUuid; 19041 final String packageName = pkg.packageName; 19042 final ApplicationInfo app = pkg.applicationInfo; 19043 final int appId = UserHandle.getAppId(app.uid); 19044 19045 Preconditions.checkNotNull(app.seinfo); 19046 19047 try { 19048 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19049 appId, app.seinfo, app.targetSdkVersion); 19050 } catch (InstallerException e) { 19051 if (app.isSystemApp()) { 19052 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 19053 + ", but trying to recover: " + e); 19054 destroyAppDataLeafLIF(pkg, userId, flags); 19055 try { 19056 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19057 appId, app.seinfo, app.targetSdkVersion); 19058 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 19059 } catch (InstallerException e2) { 19060 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 19061 } 19062 } else { 19063 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 19064 } 19065 } 19066 19067 if (restoreconNeeded) { 19068 try { 19069 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, 19070 app.seinfo); 19071 } catch (InstallerException e) { 19072 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 19073 } 19074 } 19075 19076 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19077 try { 19078 // CE storage is unlocked right now, so read out the inode and 19079 // remember for use later when it's locked 19080 // TODO: mark this structure as dirty so we persist it! 19081 final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId, 19082 StorageManager.FLAG_STORAGE_CE); 19083 synchronized (mPackages) { 19084 final PackageSetting ps = mSettings.mPackages.get(packageName); 19085 if (ps != null) { 19086 ps.setCeDataInode(ceDataInode, userId); 19087 } 19088 } 19089 } catch (InstallerException e) { 19090 Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e); 19091 } 19092 } 19093 19094 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19095 } 19096 19097 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 19098 if (pkg == null) { 19099 Slog.wtf(TAG, "Package was null!", new Throwable()); 19100 return; 19101 } 19102 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19103 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19104 for (int i = 0; i < childCount; i++) { 19105 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 19106 } 19107 } 19108 19109 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 19110 final String volumeUuid = pkg.volumeUuid; 19111 final String packageName = pkg.packageName; 19112 final ApplicationInfo app = pkg.applicationInfo; 19113 19114 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19115 // Create a native library symlink only if we have native libraries 19116 // and if the native libraries are 32 bit libraries. We do not provide 19117 // this symlink for 64 bit libraries. 19118 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 19119 final String nativeLibPath = app.nativeLibraryDir; 19120 try { 19121 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 19122 nativeLibPath, userId); 19123 } catch (InstallerException e) { 19124 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 19125 } 19126 } 19127 } 19128 } 19129 19130 /** 19131 * For system apps on non-FBE devices, this method migrates any existing 19132 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 19133 * requested by the app. 19134 */ 19135 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 19136 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 19137 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 19138 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 19139 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 19140 try { 19141 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 19142 storageTarget); 19143 } catch (InstallerException e) { 19144 logCriticalInfo(Log.WARN, 19145 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 19146 } 19147 return true; 19148 } else { 19149 return false; 19150 } 19151 } 19152 19153 public PackageFreezer freezePackage(String packageName, String killReason) { 19154 return new PackageFreezer(packageName, killReason); 19155 } 19156 19157 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 19158 String killReason) { 19159 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 19160 return new PackageFreezer(); 19161 } else { 19162 return freezePackage(packageName, killReason); 19163 } 19164 } 19165 19166 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 19167 String killReason) { 19168 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 19169 return new PackageFreezer(); 19170 } else { 19171 return freezePackage(packageName, killReason); 19172 } 19173 } 19174 19175 /** 19176 * Class that freezes and kills the given package upon creation, and 19177 * unfreezes it upon closing. This is typically used when doing surgery on 19178 * app code/data to prevent the app from running while you're working. 19179 */ 19180 private class PackageFreezer implements AutoCloseable { 19181 private final String mPackageName; 19182 private final PackageFreezer[] mChildren; 19183 19184 private final boolean mWeFroze; 19185 19186 private final AtomicBoolean mClosed = new AtomicBoolean(); 19187 private final CloseGuard mCloseGuard = CloseGuard.get(); 19188 19189 /** 19190 * Create and return a stub freezer that doesn't actually do anything, 19191 * typically used when someone requested 19192 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 19193 * {@link PackageManager#DELETE_DONT_KILL_APP}. 19194 */ 19195 public PackageFreezer() { 19196 mPackageName = null; 19197 mChildren = null; 19198 mWeFroze = false; 19199 mCloseGuard.open("close"); 19200 } 19201 19202 public PackageFreezer(String packageName, String killReason) { 19203 synchronized (mPackages) { 19204 mPackageName = packageName; 19205 mWeFroze = mFrozenPackages.add(mPackageName); 19206 19207 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 19208 if (ps != null) { 19209 killApplication(ps.name, ps.appId, killReason); 19210 } 19211 19212 final PackageParser.Package p = mPackages.get(packageName); 19213 if (p != null && p.childPackages != null) { 19214 final int N = p.childPackages.size(); 19215 mChildren = new PackageFreezer[N]; 19216 for (int i = 0; i < N; i++) { 19217 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 19218 killReason); 19219 } 19220 } else { 19221 mChildren = null; 19222 } 19223 } 19224 mCloseGuard.open("close"); 19225 } 19226 19227 @Override 19228 protected void finalize() throws Throwable { 19229 try { 19230 mCloseGuard.warnIfOpen(); 19231 close(); 19232 } finally { 19233 super.finalize(); 19234 } 19235 } 19236 19237 @Override 19238 public void close() { 19239 mCloseGuard.close(); 19240 if (mClosed.compareAndSet(false, true)) { 19241 synchronized (mPackages) { 19242 if (mWeFroze) { 19243 mFrozenPackages.remove(mPackageName); 19244 } 19245 19246 if (mChildren != null) { 19247 for (PackageFreezer freezer : mChildren) { 19248 freezer.close(); 19249 } 19250 } 19251 } 19252 } 19253 } 19254 } 19255 19256 /** 19257 * Verify that given package is currently frozen. 19258 */ 19259 private void checkPackageFrozen(String packageName) { 19260 synchronized (mPackages) { 19261 if (!mFrozenPackages.contains(packageName)) { 19262 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 19263 } 19264 } 19265 } 19266 19267 @Override 19268 public int movePackage(final String packageName, final String volumeUuid) { 19269 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19270 19271 final int moveId = mNextMoveId.getAndIncrement(); 19272 mHandler.post(new Runnable() { 19273 @Override 19274 public void run() { 19275 try { 19276 movePackageInternal(packageName, volumeUuid, moveId); 19277 } catch (PackageManagerException e) { 19278 Slog.w(TAG, "Failed to move " + packageName, e); 19279 mMoveCallbacks.notifyStatusChanged(moveId, 19280 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19281 } 19282 } 19283 }); 19284 return moveId; 19285 } 19286 19287 private void movePackageInternal(final String packageName, final String volumeUuid, 19288 final int moveId) throws PackageManagerException { 19289 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 19290 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19291 final PackageManager pm = mContext.getPackageManager(); 19292 19293 final boolean currentAsec; 19294 final String currentVolumeUuid; 19295 final File codeFile; 19296 final String installerPackageName; 19297 final String packageAbiOverride; 19298 final int appId; 19299 final String seinfo; 19300 final String label; 19301 final int targetSdkVersion; 19302 final PackageFreezer freezer; 19303 19304 // reader 19305 synchronized (mPackages) { 19306 final PackageParser.Package pkg = mPackages.get(packageName); 19307 final PackageSetting ps = mSettings.mPackages.get(packageName); 19308 if (pkg == null || ps == null) { 19309 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 19310 } 19311 19312 if (pkg.applicationInfo.isSystemApp()) { 19313 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 19314 "Cannot move system application"); 19315 } 19316 19317 if (pkg.applicationInfo.isExternalAsec()) { 19318 currentAsec = true; 19319 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 19320 } else if (pkg.applicationInfo.isForwardLocked()) { 19321 currentAsec = true; 19322 currentVolumeUuid = "forward_locked"; 19323 } else { 19324 currentAsec = false; 19325 currentVolumeUuid = ps.volumeUuid; 19326 19327 final File probe = new File(pkg.codePath); 19328 final File probeOat = new File(probe, "oat"); 19329 if (!probe.isDirectory() || !probeOat.isDirectory()) { 19330 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19331 "Move only supported for modern cluster style installs"); 19332 } 19333 } 19334 19335 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 19336 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19337 "Package already moved to " + volumeUuid); 19338 } 19339 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 19340 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 19341 "Device admin cannot be moved"); 19342 } 19343 19344 if (mFrozenPackages.contains(packageName)) { 19345 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 19346 "Failed to move already frozen package"); 19347 } 19348 19349 codeFile = new File(pkg.codePath); 19350 installerPackageName = ps.installerPackageName; 19351 packageAbiOverride = ps.cpuAbiOverrideString; 19352 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 19353 seinfo = pkg.applicationInfo.seinfo; 19354 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 19355 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 19356 freezer = new PackageFreezer(packageName, "movePackageInternal"); 19357 } 19358 19359 final Bundle extras = new Bundle(); 19360 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 19361 extras.putString(Intent.EXTRA_TITLE, label); 19362 mMoveCallbacks.notifyCreated(moveId, extras); 19363 19364 int installFlags; 19365 final boolean moveCompleteApp; 19366 final File measurePath; 19367 19368 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 19369 installFlags = INSTALL_INTERNAL; 19370 moveCompleteApp = !currentAsec; 19371 measurePath = Environment.getDataAppDirectory(volumeUuid); 19372 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 19373 installFlags = INSTALL_EXTERNAL; 19374 moveCompleteApp = false; 19375 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 19376 } else { 19377 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 19378 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 19379 || !volume.isMountedWritable()) { 19380 freezer.close(); 19381 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19382 "Move location not mounted private volume"); 19383 } 19384 19385 Preconditions.checkState(!currentAsec); 19386 19387 installFlags = INSTALL_INTERNAL; 19388 moveCompleteApp = true; 19389 measurePath = Environment.getDataAppDirectory(volumeUuid); 19390 } 19391 19392 final PackageStats stats = new PackageStats(null, -1); 19393 synchronized (mInstaller) { 19394 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 19395 freezer.close(); 19396 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19397 "Failed to measure package size"); 19398 } 19399 } 19400 19401 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 19402 + stats.dataSize); 19403 19404 final long startFreeBytes = measurePath.getFreeSpace(); 19405 final long sizeBytes; 19406 if (moveCompleteApp) { 19407 sizeBytes = stats.codeSize + stats.dataSize; 19408 } else { 19409 sizeBytes = stats.codeSize; 19410 } 19411 19412 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 19413 freezer.close(); 19414 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19415 "Not enough free space to move"); 19416 } 19417 19418 mMoveCallbacks.notifyStatusChanged(moveId, 10); 19419 19420 final CountDownLatch installedLatch = new CountDownLatch(1); 19421 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 19422 @Override 19423 public void onUserActionRequired(Intent intent) throws RemoteException { 19424 throw new IllegalStateException(); 19425 } 19426 19427 @Override 19428 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 19429 Bundle extras) throws RemoteException { 19430 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 19431 + PackageManager.installStatusToString(returnCode, msg)); 19432 19433 installedLatch.countDown(); 19434 freezer.close(); 19435 19436 final int status = PackageManager.installStatusToPublicStatus(returnCode); 19437 switch (status) { 19438 case PackageInstaller.STATUS_SUCCESS: 19439 mMoveCallbacks.notifyStatusChanged(moveId, 19440 PackageManager.MOVE_SUCCEEDED); 19441 break; 19442 case PackageInstaller.STATUS_FAILURE_STORAGE: 19443 mMoveCallbacks.notifyStatusChanged(moveId, 19444 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 19445 break; 19446 default: 19447 mMoveCallbacks.notifyStatusChanged(moveId, 19448 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19449 break; 19450 } 19451 } 19452 }; 19453 19454 final MoveInfo move; 19455 if (moveCompleteApp) { 19456 // Kick off a thread to report progress estimates 19457 new Thread() { 19458 @Override 19459 public void run() { 19460 while (true) { 19461 try { 19462 if (installedLatch.await(1, TimeUnit.SECONDS)) { 19463 break; 19464 } 19465 } catch (InterruptedException ignored) { 19466 } 19467 19468 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 19469 final int progress = 10 + (int) MathUtils.constrain( 19470 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 19471 mMoveCallbacks.notifyStatusChanged(moveId, progress); 19472 } 19473 } 19474 }.start(); 19475 19476 final String dataAppName = codeFile.getName(); 19477 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 19478 dataAppName, appId, seinfo, targetSdkVersion); 19479 } else { 19480 move = null; 19481 } 19482 19483 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 19484 19485 final Message msg = mHandler.obtainMessage(INIT_COPY); 19486 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 19487 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 19488 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 19489 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/); 19490 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 19491 msg.obj = params; 19492 19493 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 19494 System.identityHashCode(msg.obj)); 19495 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 19496 System.identityHashCode(msg.obj)); 19497 19498 mHandler.sendMessage(msg); 19499 } 19500 19501 @Override 19502 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 19503 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19504 19505 final int realMoveId = mNextMoveId.getAndIncrement(); 19506 final Bundle extras = new Bundle(); 19507 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 19508 mMoveCallbacks.notifyCreated(realMoveId, extras); 19509 19510 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 19511 @Override 19512 public void onCreated(int moveId, Bundle extras) { 19513 // Ignored 19514 } 19515 19516 @Override 19517 public void onStatusChanged(int moveId, int status, long estMillis) { 19518 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 19519 } 19520 }; 19521 19522 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19523 storage.setPrimaryStorageUuid(volumeUuid, callback); 19524 return realMoveId; 19525 } 19526 19527 @Override 19528 public int getMoveStatus(int moveId) { 19529 mContext.enforceCallingOrSelfPermission( 19530 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19531 return mMoveCallbacks.mLastStatus.get(moveId); 19532 } 19533 19534 @Override 19535 public void registerMoveCallback(IPackageMoveObserver callback) { 19536 mContext.enforceCallingOrSelfPermission( 19537 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19538 mMoveCallbacks.register(callback); 19539 } 19540 19541 @Override 19542 public void unregisterMoveCallback(IPackageMoveObserver callback) { 19543 mContext.enforceCallingOrSelfPermission( 19544 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19545 mMoveCallbacks.unregister(callback); 19546 } 19547 19548 @Override 19549 public boolean setInstallLocation(int loc) { 19550 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 19551 null); 19552 if (getInstallLocation() == loc) { 19553 return true; 19554 } 19555 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 19556 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 19557 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 19558 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 19559 return true; 19560 } 19561 return false; 19562 } 19563 19564 @Override 19565 public int getInstallLocation() { 19566 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 19567 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 19568 PackageHelper.APP_INSTALL_AUTO); 19569 } 19570 19571 /** Called by UserManagerService */ 19572 void cleanUpUser(UserManagerService userManager, int userHandle) { 19573 synchronized (mPackages) { 19574 mDirtyUsers.remove(userHandle); 19575 mUserNeedsBadging.delete(userHandle); 19576 mSettings.removeUserLPw(userHandle); 19577 mPendingBroadcasts.remove(userHandle); 19578 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 19579 removeUnusedPackagesLPw(userManager, userHandle); 19580 } 19581 } 19582 19583 /** 19584 * We're removing userHandle and would like to remove any downloaded packages 19585 * that are no longer in use by any other user. 19586 * @param userHandle the user being removed 19587 */ 19588 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 19589 final boolean DEBUG_CLEAN_APKS = false; 19590 int [] users = userManager.getUserIds(); 19591 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 19592 while (psit.hasNext()) { 19593 PackageSetting ps = psit.next(); 19594 if (ps.pkg == null) { 19595 continue; 19596 } 19597 final String packageName = ps.pkg.packageName; 19598 // Skip over if system app 19599 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 19600 continue; 19601 } 19602 if (DEBUG_CLEAN_APKS) { 19603 Slog.i(TAG, "Checking package " + packageName); 19604 } 19605 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 19606 if (keep) { 19607 if (DEBUG_CLEAN_APKS) { 19608 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 19609 } 19610 } else { 19611 for (int i = 0; i < users.length; i++) { 19612 if (users[i] != userHandle && ps.getInstalled(users[i])) { 19613 keep = true; 19614 if (DEBUG_CLEAN_APKS) { 19615 Slog.i(TAG, " Keeping package " + packageName + " for user " 19616 + users[i]); 19617 } 19618 break; 19619 } 19620 } 19621 } 19622 if (!keep) { 19623 if (DEBUG_CLEAN_APKS) { 19624 Slog.i(TAG, " Removing package " + packageName); 19625 } 19626 mHandler.post(new Runnable() { 19627 public void run() { 19628 deletePackageX(packageName, userHandle, 0); 19629 } //end run 19630 }); 19631 } 19632 } 19633 } 19634 19635 /** Called by UserManagerService */ 19636 void createNewUser(int userHandle) { 19637 synchronized (mInstallLock) { 19638 mSettings.createNewUserLI(this, mInstaller, userHandle); 19639 } 19640 synchronized (mPackages) { 19641 applyFactoryDefaultBrowserLPw(userHandle); 19642 primeDomainVerificationsLPw(userHandle); 19643 } 19644 } 19645 19646 void newUserCreated(final int userHandle) { 19647 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 19648 // If permission review for legacy apps is required, we represent 19649 // dagerous permissions for such apps as always granted runtime 19650 // permissions to keep per user flag state whether review is needed. 19651 // Hence, if a new user is added we have to propagate dangerous 19652 // permission grants for these legacy apps. 19653 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 19654 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 19655 | UPDATE_PERMISSIONS_REPLACE_ALL); 19656 } 19657 } 19658 19659 @Override 19660 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 19661 mContext.enforceCallingOrSelfPermission( 19662 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 19663 "Only package verification agents can read the verifier device identity"); 19664 19665 synchronized (mPackages) { 19666 return mSettings.getVerifierDeviceIdentityLPw(); 19667 } 19668 } 19669 19670 @Override 19671 public void setPermissionEnforced(String permission, boolean enforced) { 19672 // TODO: Now that we no longer change GID for storage, this should to away. 19673 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 19674 "setPermissionEnforced"); 19675 if (READ_EXTERNAL_STORAGE.equals(permission)) { 19676 synchronized (mPackages) { 19677 if (mSettings.mReadExternalStorageEnforced == null 19678 || mSettings.mReadExternalStorageEnforced != enforced) { 19679 mSettings.mReadExternalStorageEnforced = enforced; 19680 mSettings.writeLPr(); 19681 } 19682 } 19683 // kill any non-foreground processes so we restart them and 19684 // grant/revoke the GID. 19685 final IActivityManager am = ActivityManagerNative.getDefault(); 19686 if (am != null) { 19687 final long token = Binder.clearCallingIdentity(); 19688 try { 19689 am.killProcessesBelowForeground("setPermissionEnforcement"); 19690 } catch (RemoteException e) { 19691 } finally { 19692 Binder.restoreCallingIdentity(token); 19693 } 19694 } 19695 } else { 19696 throw new IllegalArgumentException("No selective enforcement for " + permission); 19697 } 19698 } 19699 19700 @Override 19701 @Deprecated 19702 public boolean isPermissionEnforced(String permission) { 19703 return true; 19704 } 19705 19706 @Override 19707 public boolean isStorageLow() { 19708 final long token = Binder.clearCallingIdentity(); 19709 try { 19710 final DeviceStorageMonitorInternal 19711 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 19712 if (dsm != null) { 19713 return dsm.isMemoryLow(); 19714 } else { 19715 return false; 19716 } 19717 } finally { 19718 Binder.restoreCallingIdentity(token); 19719 } 19720 } 19721 19722 @Override 19723 public IPackageInstaller getPackageInstaller() { 19724 return mInstallerService; 19725 } 19726 19727 private boolean userNeedsBadging(int userId) { 19728 int index = mUserNeedsBadging.indexOfKey(userId); 19729 if (index < 0) { 19730 final UserInfo userInfo; 19731 final long token = Binder.clearCallingIdentity(); 19732 try { 19733 userInfo = sUserManager.getUserInfo(userId); 19734 } finally { 19735 Binder.restoreCallingIdentity(token); 19736 } 19737 final boolean b; 19738 if (userInfo != null && userInfo.isManagedProfile()) { 19739 b = true; 19740 } else { 19741 b = false; 19742 } 19743 mUserNeedsBadging.put(userId, b); 19744 return b; 19745 } 19746 return mUserNeedsBadging.valueAt(index); 19747 } 19748 19749 @Override 19750 public KeySet getKeySetByAlias(String packageName, String alias) { 19751 if (packageName == null || alias == null) { 19752 return null; 19753 } 19754 synchronized(mPackages) { 19755 final PackageParser.Package pkg = mPackages.get(packageName); 19756 if (pkg == null) { 19757 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19758 throw new IllegalArgumentException("Unknown package: " + packageName); 19759 } 19760 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19761 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 19762 } 19763 } 19764 19765 @Override 19766 public KeySet getSigningKeySet(String packageName) { 19767 if (packageName == null) { 19768 return null; 19769 } 19770 synchronized(mPackages) { 19771 final PackageParser.Package pkg = mPackages.get(packageName); 19772 if (pkg == null) { 19773 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19774 throw new IllegalArgumentException("Unknown package: " + packageName); 19775 } 19776 if (pkg.applicationInfo.uid != Binder.getCallingUid() 19777 && Process.SYSTEM_UID != Binder.getCallingUid()) { 19778 throw new SecurityException("May not access signing KeySet of other apps."); 19779 } 19780 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19781 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 19782 } 19783 } 19784 19785 @Override 19786 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 19787 if (packageName == null || ks == null) { 19788 return false; 19789 } 19790 synchronized(mPackages) { 19791 final PackageParser.Package pkg = mPackages.get(packageName); 19792 if (pkg == null) { 19793 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19794 throw new IllegalArgumentException("Unknown package: " + packageName); 19795 } 19796 IBinder ksh = ks.getToken(); 19797 if (ksh instanceof KeySetHandle) { 19798 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19799 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 19800 } 19801 return false; 19802 } 19803 } 19804 19805 @Override 19806 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 19807 if (packageName == null || ks == null) { 19808 return false; 19809 } 19810 synchronized(mPackages) { 19811 final PackageParser.Package pkg = mPackages.get(packageName); 19812 if (pkg == null) { 19813 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19814 throw new IllegalArgumentException("Unknown package: " + packageName); 19815 } 19816 IBinder ksh = ks.getToken(); 19817 if (ksh instanceof KeySetHandle) { 19818 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19819 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 19820 } 19821 return false; 19822 } 19823 } 19824 19825 private void deletePackageIfUnusedLPr(final String packageName) { 19826 PackageSetting ps = mSettings.mPackages.get(packageName); 19827 if (ps == null) { 19828 return; 19829 } 19830 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 19831 // TODO Implement atomic delete if package is unused 19832 // It is currently possible that the package will be deleted even if it is installed 19833 // after this method returns. 19834 mHandler.post(new Runnable() { 19835 public void run() { 19836 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 19837 } 19838 }); 19839 } 19840 } 19841 19842 /** 19843 * Check and throw if the given before/after packages would be considered a 19844 * downgrade. 19845 */ 19846 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 19847 throws PackageManagerException { 19848 if (after.versionCode < before.mVersionCode) { 19849 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 19850 "Update version code " + after.versionCode + " is older than current " 19851 + before.mVersionCode); 19852 } else if (after.versionCode == before.mVersionCode) { 19853 if (after.baseRevisionCode < before.baseRevisionCode) { 19854 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 19855 "Update base revision code " + after.baseRevisionCode 19856 + " is older than current " + before.baseRevisionCode); 19857 } 19858 19859 if (!ArrayUtils.isEmpty(after.splitNames)) { 19860 for (int i = 0; i < after.splitNames.length; i++) { 19861 final String splitName = after.splitNames[i]; 19862 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 19863 if (j != -1) { 19864 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 19865 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 19866 "Update split " + splitName + " revision code " 19867 + after.splitRevisionCodes[i] + " is older than current " 19868 + before.splitRevisionCodes[j]); 19869 } 19870 } 19871 } 19872 } 19873 } 19874 } 19875 19876 private static class MoveCallbacks extends Handler { 19877 private static final int MSG_CREATED = 1; 19878 private static final int MSG_STATUS_CHANGED = 2; 19879 19880 private final RemoteCallbackList<IPackageMoveObserver> 19881 mCallbacks = new RemoteCallbackList<>(); 19882 19883 private final SparseIntArray mLastStatus = new SparseIntArray(); 19884 19885 public MoveCallbacks(Looper looper) { 19886 super(looper); 19887 } 19888 19889 public void register(IPackageMoveObserver callback) { 19890 mCallbacks.register(callback); 19891 } 19892 19893 public void unregister(IPackageMoveObserver callback) { 19894 mCallbacks.unregister(callback); 19895 } 19896 19897 @Override 19898 public void handleMessage(Message msg) { 19899 final SomeArgs args = (SomeArgs) msg.obj; 19900 final int n = mCallbacks.beginBroadcast(); 19901 for (int i = 0; i < n; i++) { 19902 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 19903 try { 19904 invokeCallback(callback, msg.what, args); 19905 } catch (RemoteException ignored) { 19906 } 19907 } 19908 mCallbacks.finishBroadcast(); 19909 args.recycle(); 19910 } 19911 19912 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 19913 throws RemoteException { 19914 switch (what) { 19915 case MSG_CREATED: { 19916 callback.onCreated(args.argi1, (Bundle) args.arg2); 19917 break; 19918 } 19919 case MSG_STATUS_CHANGED: { 19920 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 19921 break; 19922 } 19923 } 19924 } 19925 19926 private void notifyCreated(int moveId, Bundle extras) { 19927 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 19928 19929 final SomeArgs args = SomeArgs.obtain(); 19930 args.argi1 = moveId; 19931 args.arg2 = extras; 19932 obtainMessage(MSG_CREATED, args).sendToTarget(); 19933 } 19934 19935 private void notifyStatusChanged(int moveId, int status) { 19936 notifyStatusChanged(moveId, status, -1); 19937 } 19938 19939 private void notifyStatusChanged(int moveId, int status, long estMillis) { 19940 Slog.v(TAG, "Move " + moveId + " status " + status); 19941 19942 final SomeArgs args = SomeArgs.obtain(); 19943 args.argi1 = moveId; 19944 args.argi2 = status; 19945 args.arg3 = estMillis; 19946 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 19947 19948 synchronized (mLastStatus) { 19949 mLastStatus.put(moveId, status); 19950 } 19951 } 19952 } 19953 19954 private final static class OnPermissionChangeListeners extends Handler { 19955 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 19956 19957 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 19958 new RemoteCallbackList<>(); 19959 19960 public OnPermissionChangeListeners(Looper looper) { 19961 super(looper); 19962 } 19963 19964 @Override 19965 public void handleMessage(Message msg) { 19966 switch (msg.what) { 19967 case MSG_ON_PERMISSIONS_CHANGED: { 19968 final int uid = msg.arg1; 19969 handleOnPermissionsChanged(uid); 19970 } break; 19971 } 19972 } 19973 19974 public void addListenerLocked(IOnPermissionsChangeListener listener) { 19975 mPermissionListeners.register(listener); 19976 19977 } 19978 19979 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 19980 mPermissionListeners.unregister(listener); 19981 } 19982 19983 public void onPermissionsChanged(int uid) { 19984 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 19985 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 19986 } 19987 } 19988 19989 private void handleOnPermissionsChanged(int uid) { 19990 final int count = mPermissionListeners.beginBroadcast(); 19991 try { 19992 for (int i = 0; i < count; i++) { 19993 IOnPermissionsChangeListener callback = mPermissionListeners 19994 .getBroadcastItem(i); 19995 try { 19996 callback.onPermissionsChanged(uid); 19997 } catch (RemoteException e) { 19998 Log.e(TAG, "Permission listener is dead", e); 19999 } 20000 } 20001 } finally { 20002 mPermissionListeners.finishBroadcast(); 20003 } 20004 } 20005 } 20006 20007 private class PackageManagerInternalImpl extends PackageManagerInternal { 20008 @Override 20009 public void setLocationPackagesProvider(PackagesProvider provider) { 20010 synchronized (mPackages) { 20011 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 20012 } 20013 } 20014 20015 @Override 20016 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 20017 synchronized (mPackages) { 20018 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 20019 } 20020 } 20021 20022 @Override 20023 public void setSmsAppPackagesProvider(PackagesProvider provider) { 20024 synchronized (mPackages) { 20025 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 20026 } 20027 } 20028 20029 @Override 20030 public void setDialerAppPackagesProvider(PackagesProvider provider) { 20031 synchronized (mPackages) { 20032 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 20033 } 20034 } 20035 20036 @Override 20037 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 20038 synchronized (mPackages) { 20039 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 20040 } 20041 } 20042 20043 @Override 20044 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 20045 synchronized (mPackages) { 20046 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 20047 } 20048 } 20049 20050 @Override 20051 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 20052 synchronized (mPackages) { 20053 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 20054 packageName, userId); 20055 } 20056 } 20057 20058 @Override 20059 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 20060 synchronized (mPackages) { 20061 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 20062 packageName, userId); 20063 } 20064 } 20065 20066 @Override 20067 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 20068 synchronized (mPackages) { 20069 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 20070 packageName, userId); 20071 } 20072 } 20073 20074 @Override 20075 public void setKeepUninstalledPackages(final List<String> packageList) { 20076 Preconditions.checkNotNull(packageList); 20077 List<String> removedFromList = null; 20078 synchronized (mPackages) { 20079 if (mKeepUninstalledPackages != null) { 20080 final int packagesCount = mKeepUninstalledPackages.size(); 20081 for (int i = 0; i < packagesCount; i++) { 20082 String oldPackage = mKeepUninstalledPackages.get(i); 20083 if (packageList != null && packageList.contains(oldPackage)) { 20084 continue; 20085 } 20086 if (removedFromList == null) { 20087 removedFromList = new ArrayList<>(); 20088 } 20089 removedFromList.add(oldPackage); 20090 } 20091 } 20092 mKeepUninstalledPackages = new ArrayList<>(packageList); 20093 if (removedFromList != null) { 20094 final int removedCount = removedFromList.size(); 20095 for (int i = 0; i < removedCount; i++) { 20096 deletePackageIfUnusedLPr(removedFromList.get(i)); 20097 } 20098 } 20099 } 20100 } 20101 20102 @Override 20103 public boolean isPermissionsReviewRequired(String packageName, int userId) { 20104 synchronized (mPackages) { 20105 // If we do not support permission review, done. 20106 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 20107 return false; 20108 } 20109 20110 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 20111 if (packageSetting == null) { 20112 return false; 20113 } 20114 20115 // Permission review applies only to apps not supporting the new permission model. 20116 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 20117 return false; 20118 } 20119 20120 // Legacy apps have the permission and get user consent on launch. 20121 PermissionsState permissionsState = packageSetting.getPermissionsState(); 20122 return permissionsState.isPermissionReviewRequired(userId); 20123 } 20124 } 20125 20126 @Override 20127 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 20128 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 20129 } 20130 20131 @Override 20132 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 20133 int userId) { 20134 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 20135 } 20136 } 20137 20138 @Override 20139 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 20140 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 20141 synchronized (mPackages) { 20142 final long identity = Binder.clearCallingIdentity(); 20143 try { 20144 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 20145 packageNames, userId); 20146 } finally { 20147 Binder.restoreCallingIdentity(identity); 20148 } 20149 } 20150 } 20151 20152 private static void enforceSystemOrPhoneCaller(String tag) { 20153 int callingUid = Binder.getCallingUid(); 20154 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 20155 throw new SecurityException( 20156 "Cannot call " + tag + " from UID " + callingUid); 20157 } 20158 } 20159 20160 boolean isHistoricalPackageUsageAvailable() { 20161 return mPackageUsage.isHistoricalPackageUsageAvailable(); 20162 } 20163 20164 /** 20165 * Return a <b>copy</b> of the collection of packages known to the package manager. 20166 * @return A copy of the values of mPackages. 20167 */ 20168 Collection<PackageParser.Package> getPackages() { 20169 synchronized (mPackages) { 20170 return new ArrayList<>(mPackages.values()); 20171 } 20172 } 20173 20174 /** 20175 * Logs process start information (including base APK hash) to the security log. 20176 * @hide 20177 */ 20178 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 20179 String apkFile, int pid) { 20180 if (!SecurityLog.isLoggingEnabled()) { 20181 return; 20182 } 20183 Bundle data = new Bundle(); 20184 data.putLong("startTimestamp", System.currentTimeMillis()); 20185 data.putString("processName", processName); 20186 data.putInt("uid", uid); 20187 data.putString("seinfo", seinfo); 20188 data.putString("apkFile", apkFile); 20189 data.putInt("pid", pid); 20190 Message msg = mProcessLoggingHandler.obtainMessage( 20191 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 20192 msg.setData(data); 20193 mProcessLoggingHandler.sendMessage(msg); 20194 } 20195} 20196