PackageManagerService.java revision 214bea1b599ba2deccfca6e72a77bf411c724696
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 final int[] userIds = sUserManager.getUserIds(); 13423 synchronized (mInstallLock) { 13424 // Clean up both app data and code 13425 // All package moves are frozen until finished 13426 for (int userId : userIds) { 13427 try { 13428 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 13429 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 13430 } catch (InstallerException e) { 13431 Slog.w(TAG, String.valueOf(e)); 13432 } 13433 } 13434 removeCodePathLI(codeFile); 13435 } 13436 return true; 13437 } 13438 13439 void cleanUpResourcesLI() { 13440 throw new UnsupportedOperationException(); 13441 } 13442 13443 boolean doPostDeleteLI(boolean delete) { 13444 throw new UnsupportedOperationException(); 13445 } 13446 } 13447 13448 static String getAsecPackageName(String packageCid) { 13449 int idx = packageCid.lastIndexOf("-"); 13450 if (idx == -1) { 13451 return packageCid; 13452 } 13453 return packageCid.substring(0, idx); 13454 } 13455 13456 // Utility method used to create code paths based on package name and available index. 13457 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 13458 String idxStr = ""; 13459 int idx = 1; 13460 // Fall back to default value of idx=1 if prefix is not 13461 // part of oldCodePath 13462 if (oldCodePath != null) { 13463 String subStr = oldCodePath; 13464 // Drop the suffix right away 13465 if (suffix != null && subStr.endsWith(suffix)) { 13466 subStr = subStr.substring(0, subStr.length() - suffix.length()); 13467 } 13468 // If oldCodePath already contains prefix find out the 13469 // ending index to either increment or decrement. 13470 int sidx = subStr.lastIndexOf(prefix); 13471 if (sidx != -1) { 13472 subStr = subStr.substring(sidx + prefix.length()); 13473 if (subStr != null) { 13474 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 13475 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 13476 } 13477 try { 13478 idx = Integer.parseInt(subStr); 13479 if (idx <= 1) { 13480 idx++; 13481 } else { 13482 idx--; 13483 } 13484 } catch(NumberFormatException e) { 13485 } 13486 } 13487 } 13488 } 13489 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 13490 return prefix + idxStr; 13491 } 13492 13493 private File getNextCodePath(File targetDir, String packageName) { 13494 int suffix = 1; 13495 File result; 13496 do { 13497 result = new File(targetDir, packageName + "-" + suffix); 13498 suffix++; 13499 } while (result.exists()); 13500 return result; 13501 } 13502 13503 // Utility method that returns the relative package path with respect 13504 // to the installation directory. Like say for /data/data/com.test-1.apk 13505 // string com.test-1 is returned. 13506 static String deriveCodePathName(String codePath) { 13507 if (codePath == null) { 13508 return null; 13509 } 13510 final File codeFile = new File(codePath); 13511 final String name = codeFile.getName(); 13512 if (codeFile.isDirectory()) { 13513 return name; 13514 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 13515 final int lastDot = name.lastIndexOf('.'); 13516 return name.substring(0, lastDot); 13517 } else { 13518 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 13519 return null; 13520 } 13521 } 13522 13523 static class PackageInstalledInfo { 13524 String name; 13525 int uid; 13526 // The set of users that originally had this package installed. 13527 int[] origUsers; 13528 // The set of users that now have this package installed. 13529 int[] newUsers; 13530 PackageParser.Package pkg; 13531 int returnCode; 13532 String returnMsg; 13533 PackageRemovedInfo removedInfo; 13534 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 13535 13536 public void setError(int code, String msg) { 13537 setReturnCode(code); 13538 setReturnMessage(msg); 13539 Slog.w(TAG, msg); 13540 } 13541 13542 public void setError(String msg, PackageParserException e) { 13543 setReturnCode(e.error); 13544 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13545 Slog.w(TAG, msg, e); 13546 } 13547 13548 public void setError(String msg, PackageManagerException e) { 13549 returnCode = e.error; 13550 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13551 Slog.w(TAG, msg, e); 13552 } 13553 13554 public void setReturnCode(int returnCode) { 13555 this.returnCode = returnCode; 13556 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13557 for (int i = 0; i < childCount; i++) { 13558 addedChildPackages.valueAt(i).returnCode = returnCode; 13559 } 13560 } 13561 13562 private void setReturnMessage(String returnMsg) { 13563 this.returnMsg = returnMsg; 13564 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13565 for (int i = 0; i < childCount; i++) { 13566 addedChildPackages.valueAt(i).returnMsg = returnMsg; 13567 } 13568 } 13569 13570 // In some error cases we want to convey more info back to the observer 13571 String origPackage; 13572 String origPermission; 13573 } 13574 13575 /* 13576 * Install a non-existing package. 13577 */ 13578 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 13579 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 13580 PackageInstalledInfo res) { 13581 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 13582 13583 // Remember this for later, in case we need to rollback this install 13584 String pkgName = pkg.packageName; 13585 13586 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 13587 13588 synchronized(mPackages) { 13589 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 13590 // A package with the same name is already installed, though 13591 // it has been renamed to an older name. The package we 13592 // are trying to install should be installed as an update to 13593 // the existing one, but that has not been requested, so bail. 13594 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13595 + " without first uninstalling package running as " 13596 + mSettings.mRenamedPackages.get(pkgName)); 13597 return; 13598 } 13599 if (mPackages.containsKey(pkgName)) { 13600 // Don't allow installation over an existing package with the same name. 13601 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13602 + " without first uninstalling."); 13603 return; 13604 } 13605 } 13606 13607 try { 13608 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 13609 System.currentTimeMillis(), user); 13610 13611 updateSettingsLI(newPackage, installerPackageName, null, res, user); 13612 13613 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13614 prepareAppDataAfterInstallLIF(newPackage); 13615 13616 } else { 13617 // Remove package from internal structures, but keep around any 13618 // data that might have already existed 13619 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 13620 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 13621 } 13622 } catch (PackageManagerException e) { 13623 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13624 } 13625 13626 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13627 } 13628 13629 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 13630 // Can't rotate keys during boot or if sharedUser. 13631 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 13632 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 13633 return false; 13634 } 13635 // app is using upgradeKeySets; make sure all are valid 13636 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13637 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 13638 for (int i = 0; i < upgradeKeySets.length; i++) { 13639 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 13640 Slog.wtf(TAG, "Package " 13641 + (oldPs.name != null ? oldPs.name : "<null>") 13642 + " contains upgrade-key-set reference to unknown key-set: " 13643 + upgradeKeySets[i] 13644 + " reverting to signatures check."); 13645 return false; 13646 } 13647 } 13648 return true; 13649 } 13650 13651 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 13652 // Upgrade keysets are being used. Determine if new package has a superset of the 13653 // required keys. 13654 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 13655 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13656 for (int i = 0; i < upgradeKeySets.length; i++) { 13657 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 13658 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 13659 return true; 13660 } 13661 } 13662 return false; 13663 } 13664 13665 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 13666 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 13667 final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 13668 13669 final PackageParser.Package oldPackage; 13670 final String pkgName = pkg.packageName; 13671 final int[] allUsers; 13672 13673 // First find the old package info and check signatures 13674 synchronized(mPackages) { 13675 oldPackage = mPackages.get(pkgName); 13676 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 13677 if (isEphemeral && !oldIsEphemeral) { 13678 // can't downgrade from full to ephemeral 13679 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 13680 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 13681 return; 13682 } 13683 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 13684 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13685 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 13686 if (!checkUpgradeKeySetLP(ps, pkg)) { 13687 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13688 "New package not signed by keys specified by upgrade-keysets: " 13689 + pkgName); 13690 return; 13691 } 13692 } else { 13693 // default to original signature matching 13694 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 13695 != PackageManager.SIGNATURE_MATCH) { 13696 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13697 "New package has a different signature: " + pkgName); 13698 return; 13699 } 13700 } 13701 13702 // Check for shared user id changes 13703 String invalidPackageName = 13704 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 13705 if (invalidPackageName != null) { 13706 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 13707 "Package " + invalidPackageName + " tried to change user " 13708 + oldPackage.mSharedUserId); 13709 return; 13710 } 13711 13712 // In case of rollback, remember per-user/profile install state 13713 allUsers = sUserManager.getUserIds(); 13714 } 13715 13716 // Update what is removed 13717 res.removedInfo = new PackageRemovedInfo(); 13718 res.removedInfo.uid = oldPackage.applicationInfo.uid; 13719 res.removedInfo.removedPackage = oldPackage.packageName; 13720 res.removedInfo.isUpdate = true; 13721 final int childCount = (oldPackage.childPackages != null) 13722 ? oldPackage.childPackages.size() : 0; 13723 for (int i = 0; i < childCount; i++) { 13724 boolean childPackageUpdated = false; 13725 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 13726 if (res.addedChildPackages != null) { 13727 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 13728 if (childRes != null) { 13729 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 13730 childRes.removedInfo.removedPackage = childPkg.packageName; 13731 childRes.removedInfo.isUpdate = true; 13732 childPackageUpdated = true; 13733 } 13734 } 13735 if (!childPackageUpdated) { 13736 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 13737 childRemovedRes.removedPackage = childPkg.packageName; 13738 childRemovedRes.isUpdate = false; 13739 childRemovedRes.dataRemoved = true; 13740 synchronized (mPackages) { 13741 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 13742 if (childPs != null) { 13743 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 13744 } 13745 } 13746 if (res.removedInfo.removedChildPackages == null) { 13747 res.removedInfo.removedChildPackages = new ArrayMap<>(); 13748 } 13749 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 13750 } 13751 } 13752 13753 boolean sysPkg = (isSystemApp(oldPackage)); 13754 if (sysPkg) { 13755 // Set the system/privileged flags as needed 13756 final boolean privileged = 13757 (oldPackage.applicationInfo.privateFlags 13758 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 13759 final int systemPolicyFlags = policyFlags 13760 | PackageParser.PARSE_IS_SYSTEM 13761 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 13762 13763 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 13764 user, allUsers, installerPackageName, res); 13765 } else { 13766 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 13767 user, allUsers, installerPackageName, res); 13768 } 13769 } 13770 13771 public List<String> getPreviousCodePaths(String packageName) { 13772 final PackageSetting ps = mSettings.mPackages.get(packageName); 13773 final List<String> result = new ArrayList<String>(); 13774 if (ps != null && ps.oldCodePaths != null) { 13775 result.addAll(ps.oldCodePaths); 13776 } 13777 return result; 13778 } 13779 13780 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 13781 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 13782 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 13783 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 13784 + deletedPackage); 13785 13786 String pkgName = deletedPackage.packageName; 13787 boolean deletedPkg = true; 13788 boolean addedPkg = false; 13789 boolean updatedSettings = false; 13790 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 13791 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 13792 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 13793 13794 final long origUpdateTime = (pkg.mExtras != null) 13795 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 13796 13797 // First delete the existing package while retaining the data directory 13798 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 13799 res.removedInfo, true, pkg)) { 13800 // If the existing package wasn't successfully deleted 13801 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 13802 deletedPkg = false; 13803 } else { 13804 // Successfully deleted the old package; proceed with replace. 13805 13806 // If deleted package lived in a container, give users a chance to 13807 // relinquish resources before killing. 13808 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 13809 if (DEBUG_INSTALL) { 13810 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 13811 } 13812 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 13813 final ArrayList<String> pkgList = new ArrayList<String>(1); 13814 pkgList.add(deletedPackage.applicationInfo.packageName); 13815 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 13816 } 13817 13818 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 13819 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 13820 clearAppProfilesLIF(pkg); 13821 13822 try { 13823 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 13824 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 13825 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 13826 13827 // Update the in-memory copy of the previous code paths. 13828 PackageSetting ps = mSettings.mPackages.get(pkgName); 13829 if (!killApp) { 13830 if (ps.oldCodePaths == null) { 13831 ps.oldCodePaths = new ArraySet<>(); 13832 } 13833 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 13834 if (deletedPackage.splitCodePaths != null) { 13835 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 13836 } 13837 } else { 13838 ps.oldCodePaths = null; 13839 } 13840 if (ps.childPackageNames != null) { 13841 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 13842 final String childPkgName = ps.childPackageNames.get(i); 13843 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 13844 childPs.oldCodePaths = ps.oldCodePaths; 13845 } 13846 } 13847 prepareAppDataAfterInstallLIF(newPackage); 13848 addedPkg = true; 13849 } catch (PackageManagerException e) { 13850 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13851 } 13852 } 13853 13854 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 13855 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 13856 13857 // Revert all internal state mutations and added folders for the failed install 13858 if (addedPkg) { 13859 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 13860 res.removedInfo, true, null); 13861 } 13862 13863 // Restore the old package 13864 if (deletedPkg) { 13865 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 13866 File restoreFile = new File(deletedPackage.codePath); 13867 // Parse old package 13868 boolean oldExternal = isExternal(deletedPackage); 13869 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 13870 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 13871 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 13872 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 13873 try { 13874 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 13875 null); 13876 } catch (PackageManagerException e) { 13877 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 13878 + e.getMessage()); 13879 return; 13880 } 13881 13882 synchronized (mPackages) { 13883 // Ensure the installer package name up to date 13884 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 13885 13886 // Update permissions for restored package 13887 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 13888 13889 mSettings.writeLPr(); 13890 } 13891 13892 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 13893 } 13894 } else { 13895 synchronized (mPackages) { 13896 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 13897 if (ps != null) { 13898 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 13899 if (res.removedInfo.removedChildPackages != null) { 13900 final int childCount = res.removedInfo.removedChildPackages.size(); 13901 // Iterate in reverse as we may modify the collection 13902 for (int i = childCount - 1; i >= 0; i--) { 13903 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 13904 if (res.addedChildPackages.containsKey(childPackageName)) { 13905 res.removedInfo.removedChildPackages.removeAt(i); 13906 } else { 13907 PackageRemovedInfo childInfo = res.removedInfo 13908 .removedChildPackages.valueAt(i); 13909 childInfo.removedForAllUsers = mPackages.get( 13910 childInfo.removedPackage) == null; 13911 } 13912 } 13913 } 13914 } 13915 } 13916 } 13917 } 13918 13919 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 13920 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 13921 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 13922 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 13923 + ", old=" + deletedPackage); 13924 13925 final boolean disabledSystem; 13926 13927 // Remove existing system package 13928 removePackageLI(deletedPackage, true); 13929 13930 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 13931 if (!disabledSystem) { 13932 // We didn't need to disable the .apk as a current system package, 13933 // which means we are replacing another update that is already 13934 // installed. We need to make sure to delete the older one's .apk. 13935 res.removedInfo.args = createInstallArgsForExisting(0, 13936 deletedPackage.applicationInfo.getCodePath(), 13937 deletedPackage.applicationInfo.getResourcePath(), 13938 getAppDexInstructionSets(deletedPackage.applicationInfo)); 13939 } else { 13940 res.removedInfo.args = null; 13941 } 13942 13943 // Successfully disabled the old package. Now proceed with re-installation 13944 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 13945 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 13946 clearAppProfilesLIF(pkg); 13947 13948 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 13949 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 13950 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 13951 13952 PackageParser.Package newPackage = null; 13953 try { 13954 // Add the package to the internal data structures 13955 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 13956 13957 // Set the update and install times 13958 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 13959 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 13960 System.currentTimeMillis()); 13961 13962 // Update the package dynamic state if succeeded 13963 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13964 // Now that the install succeeded make sure we remove data 13965 // directories for any child package the update removed. 13966 final int deletedChildCount = (deletedPackage.childPackages != null) 13967 ? deletedPackage.childPackages.size() : 0; 13968 final int newChildCount = (newPackage.childPackages != null) 13969 ? newPackage.childPackages.size() : 0; 13970 for (int i = 0; i < deletedChildCount; i++) { 13971 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 13972 boolean childPackageDeleted = true; 13973 for (int j = 0; j < newChildCount; j++) { 13974 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 13975 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 13976 childPackageDeleted = false; 13977 break; 13978 } 13979 } 13980 if (childPackageDeleted) { 13981 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 13982 deletedChildPkg.packageName); 13983 if (ps != null && res.removedInfo.removedChildPackages != null) { 13984 PackageRemovedInfo removedChildRes = res.removedInfo 13985 .removedChildPackages.get(deletedChildPkg.packageName); 13986 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 13987 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 13988 } 13989 } 13990 } 13991 13992 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 13993 prepareAppDataAfterInstallLIF(newPackage); 13994 } 13995 } catch (PackageManagerException e) { 13996 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 13997 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13998 } 13999 14000 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14001 // Re installation failed. Restore old information 14002 // Remove new pkg information 14003 if (newPackage != null) { 14004 removeInstalledPackageLI(newPackage, true); 14005 } 14006 // Add back the old system package 14007 try { 14008 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 14009 } catch (PackageManagerException e) { 14010 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 14011 } 14012 14013 synchronized (mPackages) { 14014 if (disabledSystem) { 14015 enableSystemPackageLPw(deletedPackage); 14016 } 14017 14018 // Ensure the installer package name up to date 14019 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14020 14021 // Update permissions for restored package 14022 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14023 14024 mSettings.writeLPr(); 14025 } 14026 14027 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 14028 + " after failed upgrade"); 14029 } 14030 } 14031 14032 /** 14033 * Checks whether the parent or any of the child packages have a change shared 14034 * user. For a package to be a valid update the shred users of the parent and 14035 * the children should match. We may later support changing child shared users. 14036 * @param oldPkg The updated package. 14037 * @param newPkg The update package. 14038 * @return The shared user that change between the versions. 14039 */ 14040 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 14041 PackageParser.Package newPkg) { 14042 // Check parent shared user 14043 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 14044 return newPkg.packageName; 14045 } 14046 // Check child shared users 14047 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14048 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 14049 for (int i = 0; i < newChildCount; i++) { 14050 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 14051 // If this child was present, did it have the same shared user? 14052 for (int j = 0; j < oldChildCount; j++) { 14053 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 14054 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 14055 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 14056 return newChildPkg.packageName; 14057 } 14058 } 14059 } 14060 return null; 14061 } 14062 14063 private void removeNativeBinariesLI(PackageSetting ps) { 14064 // Remove the lib path for the parent package 14065 if (ps != null) { 14066 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 14067 // Remove the lib path for the child packages 14068 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 14069 for (int i = 0; i < childCount; i++) { 14070 PackageSetting childPs = null; 14071 synchronized (mPackages) { 14072 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 14073 } 14074 if (childPs != null) { 14075 NativeLibraryHelper.removeNativeBinariesLI(childPs 14076 .legacyNativeLibraryPathString); 14077 } 14078 } 14079 } 14080 } 14081 14082 private void enableSystemPackageLPw(PackageParser.Package pkg) { 14083 // Enable the parent package 14084 mSettings.enableSystemPackageLPw(pkg.packageName); 14085 // Enable the child packages 14086 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14087 for (int i = 0; i < childCount; i++) { 14088 PackageParser.Package childPkg = pkg.childPackages.get(i); 14089 mSettings.enableSystemPackageLPw(childPkg.packageName); 14090 } 14091 } 14092 14093 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 14094 PackageParser.Package newPkg) { 14095 // Disable the parent package (parent always replaced) 14096 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 14097 // Disable the child packages 14098 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14099 for (int i = 0; i < childCount; i++) { 14100 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 14101 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 14102 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 14103 } 14104 return disabled; 14105 } 14106 14107 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 14108 String installerPackageName) { 14109 // Enable the parent package 14110 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 14111 // Enable the child packages 14112 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14113 for (int i = 0; i < childCount; i++) { 14114 PackageParser.Package childPkg = pkg.childPackages.get(i); 14115 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 14116 } 14117 } 14118 14119 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 14120 // Collect all used permissions in the UID 14121 ArraySet<String> usedPermissions = new ArraySet<>(); 14122 final int packageCount = su.packages.size(); 14123 for (int i = 0; i < packageCount; i++) { 14124 PackageSetting ps = su.packages.valueAt(i); 14125 if (ps.pkg == null) { 14126 continue; 14127 } 14128 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 14129 for (int j = 0; j < requestedPermCount; j++) { 14130 String permission = ps.pkg.requestedPermissions.get(j); 14131 BasePermission bp = mSettings.mPermissions.get(permission); 14132 if (bp != null) { 14133 usedPermissions.add(permission); 14134 } 14135 } 14136 } 14137 14138 PermissionsState permissionsState = su.getPermissionsState(); 14139 // Prune install permissions 14140 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 14141 final int installPermCount = installPermStates.size(); 14142 for (int i = installPermCount - 1; i >= 0; i--) { 14143 PermissionState permissionState = installPermStates.get(i); 14144 if (!usedPermissions.contains(permissionState.getName())) { 14145 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14146 if (bp != null) { 14147 permissionsState.revokeInstallPermission(bp); 14148 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 14149 PackageManager.MASK_PERMISSION_FLAGS, 0); 14150 } 14151 } 14152 } 14153 14154 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 14155 14156 // Prune runtime permissions 14157 for (int userId : allUserIds) { 14158 List<PermissionState> runtimePermStates = permissionsState 14159 .getRuntimePermissionStates(userId); 14160 final int runtimePermCount = runtimePermStates.size(); 14161 for (int i = runtimePermCount - 1; i >= 0; i--) { 14162 PermissionState permissionState = runtimePermStates.get(i); 14163 if (!usedPermissions.contains(permissionState.getName())) { 14164 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14165 if (bp != null) { 14166 permissionsState.revokeRuntimePermission(bp, userId); 14167 permissionsState.updatePermissionFlags(bp, userId, 14168 PackageManager.MASK_PERMISSION_FLAGS, 0); 14169 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 14170 runtimePermissionChangedUserIds, userId); 14171 } 14172 } 14173 } 14174 } 14175 14176 return runtimePermissionChangedUserIds; 14177 } 14178 14179 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 14180 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 14181 // Update the parent package setting 14182 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 14183 res, user); 14184 // Update the child packages setting 14185 final int childCount = (newPackage.childPackages != null) 14186 ? newPackage.childPackages.size() : 0; 14187 for (int i = 0; i < childCount; i++) { 14188 PackageParser.Package childPackage = newPackage.childPackages.get(i); 14189 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 14190 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 14191 childRes.origUsers, childRes, user); 14192 } 14193 } 14194 14195 private void updateSettingsInternalLI(PackageParser.Package newPackage, 14196 String installerPackageName, int[] allUsers, int[] installedForUsers, 14197 PackageInstalledInfo res, UserHandle user) { 14198 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 14199 14200 String pkgName = newPackage.packageName; 14201 synchronized (mPackages) { 14202 //write settings. the installStatus will be incomplete at this stage. 14203 //note that the new package setting would have already been 14204 //added to mPackages. It hasn't been persisted yet. 14205 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 14206 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14207 mSettings.writeLPr(); 14208 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14209 } 14210 14211 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 14212 synchronized (mPackages) { 14213 updatePermissionsLPw(newPackage.packageName, newPackage, 14214 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 14215 ? UPDATE_PERMISSIONS_ALL : 0)); 14216 // For system-bundled packages, we assume that installing an upgraded version 14217 // of the package implies that the user actually wants to run that new code, 14218 // so we enable the package. 14219 PackageSetting ps = mSettings.mPackages.get(pkgName); 14220 final int userId = user.getIdentifier(); 14221 if (ps != null) { 14222 if (isSystemApp(newPackage)) { 14223 if (DEBUG_INSTALL) { 14224 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 14225 } 14226 // Enable system package for requested users 14227 if (res.origUsers != null) { 14228 for (int origUserId : res.origUsers) { 14229 if (userId == UserHandle.USER_ALL || userId == origUserId) { 14230 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 14231 origUserId, installerPackageName); 14232 } 14233 } 14234 } 14235 // Also convey the prior install/uninstall state 14236 if (allUsers != null && installedForUsers != null) { 14237 for (int currentUserId : allUsers) { 14238 final boolean installed = ArrayUtils.contains( 14239 installedForUsers, currentUserId); 14240 if (DEBUG_INSTALL) { 14241 Slog.d(TAG, " user " + currentUserId + " => " + installed); 14242 } 14243 ps.setInstalled(installed, currentUserId); 14244 } 14245 // these install state changes will be persisted in the 14246 // upcoming call to mSettings.writeLPr(). 14247 } 14248 } 14249 // It's implied that when a user requests installation, they want the app to be 14250 // installed and enabled. 14251 if (userId != UserHandle.USER_ALL) { 14252 ps.setInstalled(true, userId); 14253 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 14254 } 14255 } 14256 res.name = pkgName; 14257 res.uid = newPackage.applicationInfo.uid; 14258 res.pkg = newPackage; 14259 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 14260 mSettings.setInstallerPackageName(pkgName, installerPackageName); 14261 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14262 //to update install status 14263 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14264 mSettings.writeLPr(); 14265 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14266 } 14267 14268 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14269 } 14270 14271 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 14272 try { 14273 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 14274 installPackageLI(args, res); 14275 } finally { 14276 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14277 } 14278 } 14279 14280 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 14281 final int installFlags = args.installFlags; 14282 final String installerPackageName = args.installerPackageName; 14283 final String volumeUuid = args.volumeUuid; 14284 final File tmpPackageFile = new File(args.getCodePath()); 14285 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 14286 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 14287 || (args.volumeUuid != null)); 14288 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 14289 boolean replace = false; 14290 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 14291 if (args.move != null) { 14292 // moving a complete application; perform an initial scan on the new install location 14293 scanFlags |= SCAN_INITIAL; 14294 } 14295 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 14296 scanFlags |= SCAN_DONT_KILL_APP; 14297 } 14298 14299 // Result object to be returned 14300 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14301 14302 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 14303 14304 // Sanity check 14305 if (ephemeral && (forwardLocked || onExternal)) { 14306 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 14307 + " external=" + onExternal); 14308 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14309 return; 14310 } 14311 14312 // Retrieve PackageSettings and parse package 14313 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 14314 | PackageParser.PARSE_ENFORCE_CODE 14315 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 14316 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 14317 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0); 14318 PackageParser pp = new PackageParser(); 14319 pp.setSeparateProcesses(mSeparateProcesses); 14320 pp.setDisplayMetrics(mMetrics); 14321 14322 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 14323 final PackageParser.Package pkg; 14324 try { 14325 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 14326 } catch (PackageParserException e) { 14327 res.setError("Failed parse during installPackageLI", e); 14328 return; 14329 } finally { 14330 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14331 } 14332 14333 // If we are installing a clustered package add results for the children 14334 if (pkg.childPackages != null) { 14335 synchronized (mPackages) { 14336 final int childCount = pkg.childPackages.size(); 14337 for (int i = 0; i < childCount; i++) { 14338 PackageParser.Package childPkg = pkg.childPackages.get(i); 14339 PackageInstalledInfo childRes = new PackageInstalledInfo(); 14340 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14341 childRes.pkg = childPkg; 14342 childRes.name = childPkg.packageName; 14343 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14344 if (childPs != null) { 14345 childRes.origUsers = childPs.queryInstalledUsers( 14346 sUserManager.getUserIds(), true); 14347 } 14348 if ((mPackages.containsKey(childPkg.packageName))) { 14349 childRes.removedInfo = new PackageRemovedInfo(); 14350 childRes.removedInfo.removedPackage = childPkg.packageName; 14351 } 14352 if (res.addedChildPackages == null) { 14353 res.addedChildPackages = new ArrayMap<>(); 14354 } 14355 res.addedChildPackages.put(childPkg.packageName, childRes); 14356 } 14357 } 14358 } 14359 14360 // If package doesn't declare API override, mark that we have an install 14361 // time CPU ABI override. 14362 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 14363 pkg.cpuAbiOverride = args.abiOverride; 14364 } 14365 14366 String pkgName = res.name = pkg.packageName; 14367 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 14368 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 14369 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 14370 return; 14371 } 14372 } 14373 14374 try { 14375 // either use what we've been given or parse directly from the APK 14376 if (args.certificates != null) { 14377 try { 14378 PackageParser.populateCertificates(pkg, args.certificates); 14379 } catch (PackageParserException e) { 14380 // there was something wrong with the certificates we were given; 14381 // try to pull them from the APK 14382 PackageParser.collectCertificates(pkg, parseFlags); 14383 } 14384 } else { 14385 PackageParser.collectCertificates(pkg, parseFlags); 14386 } 14387 } catch (PackageParserException e) { 14388 res.setError("Failed collect during installPackageLI", e); 14389 return; 14390 } 14391 14392 // Get rid of all references to package scan path via parser. 14393 pp = null; 14394 String oldCodePath = null; 14395 boolean systemApp = false; 14396 synchronized (mPackages) { 14397 // Check if installing already existing package 14398 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14399 String oldName = mSettings.mRenamedPackages.get(pkgName); 14400 if (pkg.mOriginalPackages != null 14401 && pkg.mOriginalPackages.contains(oldName) 14402 && mPackages.containsKey(oldName)) { 14403 // This package is derived from an original package, 14404 // and this device has been updating from that original 14405 // name. We must continue using the original name, so 14406 // rename the new package here. 14407 pkg.setPackageName(oldName); 14408 pkgName = pkg.packageName; 14409 replace = true; 14410 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 14411 + oldName + " pkgName=" + pkgName); 14412 } else if (mPackages.containsKey(pkgName)) { 14413 // This package, under its official name, already exists 14414 // on the device; we should replace it. 14415 replace = true; 14416 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 14417 } 14418 14419 // Child packages are installed through the parent package 14420 if (pkg.parentPackage != null) { 14421 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14422 "Package " + pkg.packageName + " is child of package " 14423 + pkg.parentPackage.parentPackage + ". Child packages " 14424 + "can be updated only through the parent package."); 14425 return; 14426 } 14427 14428 if (replace) { 14429 // Prevent apps opting out from runtime permissions 14430 PackageParser.Package oldPackage = mPackages.get(pkgName); 14431 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 14432 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 14433 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 14434 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 14435 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 14436 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 14437 + " doesn't support runtime permissions but the old" 14438 + " target SDK " + oldTargetSdk + " does."); 14439 return; 14440 } 14441 14442 // Prevent installing of child packages 14443 if (oldPackage.parentPackage != null) { 14444 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14445 "Package " + pkg.packageName + " is child of package " 14446 + oldPackage.parentPackage + ". Child packages " 14447 + "can be updated only through the parent package."); 14448 return; 14449 } 14450 } 14451 } 14452 14453 PackageSetting ps = mSettings.mPackages.get(pkgName); 14454 if (ps != null) { 14455 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 14456 14457 // Quick sanity check that we're signed correctly if updating; 14458 // we'll check this again later when scanning, but we want to 14459 // bail early here before tripping over redefined permissions. 14460 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14461 if (!checkUpgradeKeySetLP(ps, pkg)) { 14462 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 14463 + pkg.packageName + " upgrade keys do not match the " 14464 + "previously installed version"); 14465 return; 14466 } 14467 } else { 14468 try { 14469 verifySignaturesLP(ps, pkg); 14470 } catch (PackageManagerException e) { 14471 res.setError(e.error, e.getMessage()); 14472 return; 14473 } 14474 } 14475 14476 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 14477 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 14478 systemApp = (ps.pkg.applicationInfo.flags & 14479 ApplicationInfo.FLAG_SYSTEM) != 0; 14480 } 14481 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14482 } 14483 14484 // Check whether the newly-scanned package wants to define an already-defined perm 14485 int N = pkg.permissions.size(); 14486 for (int i = N-1; i >= 0; i--) { 14487 PackageParser.Permission perm = pkg.permissions.get(i); 14488 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 14489 if (bp != null) { 14490 // If the defining package is signed with our cert, it's okay. This 14491 // also includes the "updating the same package" case, of course. 14492 // "updating same package" could also involve key-rotation. 14493 final boolean sigsOk; 14494 if (bp.sourcePackage.equals(pkg.packageName) 14495 && (bp.packageSetting instanceof PackageSetting) 14496 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 14497 scanFlags))) { 14498 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 14499 } else { 14500 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 14501 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 14502 } 14503 if (!sigsOk) { 14504 // If the owning package is the system itself, we log but allow 14505 // install to proceed; we fail the install on all other permission 14506 // redefinitions. 14507 if (!bp.sourcePackage.equals("android")) { 14508 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 14509 + pkg.packageName + " attempting to redeclare permission " 14510 + perm.info.name + " already owned by " + bp.sourcePackage); 14511 res.origPermission = perm.info.name; 14512 res.origPackage = bp.sourcePackage; 14513 return; 14514 } else { 14515 Slog.w(TAG, "Package " + pkg.packageName 14516 + " attempting to redeclare system permission " 14517 + perm.info.name + "; ignoring new declaration"); 14518 pkg.permissions.remove(i); 14519 } 14520 } 14521 } 14522 } 14523 } 14524 14525 if (systemApp) { 14526 if (onExternal) { 14527 // Abort update; system app can't be replaced with app on sdcard 14528 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 14529 "Cannot install updates to system apps on sdcard"); 14530 return; 14531 } else if (ephemeral) { 14532 // Abort update; system app can't be replaced with an ephemeral app 14533 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 14534 "Cannot update a system app with an ephemeral app"); 14535 return; 14536 } 14537 } 14538 14539 if (args.move != null) { 14540 // We did an in-place move, so dex is ready to roll 14541 scanFlags |= SCAN_NO_DEX; 14542 scanFlags |= SCAN_MOVE; 14543 14544 synchronized (mPackages) { 14545 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14546 if (ps == null) { 14547 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 14548 "Missing settings for moved package " + pkgName); 14549 } 14550 14551 // We moved the entire application as-is, so bring over the 14552 // previously derived ABI information. 14553 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 14554 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 14555 } 14556 14557 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 14558 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 14559 scanFlags |= SCAN_NO_DEX; 14560 14561 try { 14562 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 14563 args.abiOverride : pkg.cpuAbiOverride); 14564 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 14565 true /* extract libs */); 14566 } catch (PackageManagerException pme) { 14567 Slog.e(TAG, "Error deriving application ABI", pme); 14568 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 14569 return; 14570 } 14571 14572 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 14573 // Do not run PackageDexOptimizer through the local performDexOpt 14574 // method because `pkg` is not in `mPackages` yet. 14575 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instructionSets */, 14576 false /* checkProfiles */, getCompilerFilterForReason(REASON_INSTALL)); 14577 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14578 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 14579 String msg = "Extracting package failed for " + pkgName; 14580 res.setError(INSTALL_FAILED_DEXOPT, msg); 14581 return; 14582 } 14583 14584 // Notify BackgroundDexOptService that the package has been changed. 14585 // If this is an update of a package which used to fail to compile, 14586 // BDOS will remove it from its blacklist. 14587 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 14588 } 14589 14590 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 14591 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 14592 return; 14593 } 14594 14595 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 14596 14597 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 14598 "installPackageLI")) { 14599 if (replace) { 14600 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 14601 installerPackageName, res); 14602 } else { 14603 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 14604 args.user, installerPackageName, volumeUuid, res); 14605 } 14606 } 14607 synchronized (mPackages) { 14608 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14609 if (ps != null) { 14610 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14611 } 14612 14613 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14614 for (int i = 0; i < childCount; i++) { 14615 PackageParser.Package childPkg = pkg.childPackages.get(i); 14616 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14617 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14618 if (childPs != null) { 14619 childRes.newUsers = childPs.queryInstalledUsers( 14620 sUserManager.getUserIds(), true); 14621 } 14622 } 14623 } 14624 } 14625 14626 private void startIntentFilterVerifications(int userId, boolean replacing, 14627 PackageParser.Package pkg) { 14628 if (mIntentFilterVerifierComponent == null) { 14629 Slog.w(TAG, "No IntentFilter verification will not be done as " 14630 + "there is no IntentFilterVerifier available!"); 14631 return; 14632 } 14633 14634 final int verifierUid = getPackageUid( 14635 mIntentFilterVerifierComponent.getPackageName(), 14636 MATCH_DEBUG_TRIAGED_MISSING, 14637 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 14638 14639 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14640 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 14641 mHandler.sendMessage(msg); 14642 14643 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14644 for (int i = 0; i < childCount; i++) { 14645 PackageParser.Package childPkg = pkg.childPackages.get(i); 14646 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14647 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 14648 mHandler.sendMessage(msg); 14649 } 14650 } 14651 14652 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 14653 PackageParser.Package pkg) { 14654 int size = pkg.activities.size(); 14655 if (size == 0) { 14656 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14657 "No activity, so no need to verify any IntentFilter!"); 14658 return; 14659 } 14660 14661 final boolean hasDomainURLs = hasDomainURLs(pkg); 14662 if (!hasDomainURLs) { 14663 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14664 "No domain URLs, so no need to verify any IntentFilter!"); 14665 return; 14666 } 14667 14668 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 14669 + " if any IntentFilter from the " + size 14670 + " Activities needs verification ..."); 14671 14672 int count = 0; 14673 final String packageName = pkg.packageName; 14674 14675 synchronized (mPackages) { 14676 // If this is a new install and we see that we've already run verification for this 14677 // package, we have nothing to do: it means the state was restored from backup. 14678 if (!replacing) { 14679 IntentFilterVerificationInfo ivi = 14680 mSettings.getIntentFilterVerificationLPr(packageName); 14681 if (ivi != null) { 14682 if (DEBUG_DOMAIN_VERIFICATION) { 14683 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 14684 + ivi.getStatusString()); 14685 } 14686 return; 14687 } 14688 } 14689 14690 // If any filters need to be verified, then all need to be. 14691 boolean needToVerify = false; 14692 for (PackageParser.Activity a : pkg.activities) { 14693 for (ActivityIntentInfo filter : a.intents) { 14694 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 14695 if (DEBUG_DOMAIN_VERIFICATION) { 14696 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 14697 } 14698 needToVerify = true; 14699 break; 14700 } 14701 } 14702 } 14703 14704 if (needToVerify) { 14705 final int verificationId = mIntentFilterVerificationToken++; 14706 for (PackageParser.Activity a : pkg.activities) { 14707 for (ActivityIntentInfo filter : a.intents) { 14708 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 14709 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14710 "Verification needed for IntentFilter:" + filter.toString()); 14711 mIntentFilterVerifier.addOneIntentFilterVerification( 14712 verifierUid, userId, verificationId, filter, packageName); 14713 count++; 14714 } 14715 } 14716 } 14717 } 14718 } 14719 14720 if (count > 0) { 14721 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 14722 + " IntentFilter verification" + (count > 1 ? "s" : "") 14723 + " for userId:" + userId); 14724 mIntentFilterVerifier.startVerifications(userId); 14725 } else { 14726 if (DEBUG_DOMAIN_VERIFICATION) { 14727 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 14728 } 14729 } 14730 } 14731 14732 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 14733 final ComponentName cn = filter.activity.getComponentName(); 14734 final String packageName = cn.getPackageName(); 14735 14736 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 14737 packageName); 14738 if (ivi == null) { 14739 return true; 14740 } 14741 int status = ivi.getStatus(); 14742 switch (status) { 14743 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 14744 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 14745 return true; 14746 14747 default: 14748 // Nothing to do 14749 return false; 14750 } 14751 } 14752 14753 private static boolean isMultiArch(ApplicationInfo info) { 14754 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 14755 } 14756 14757 private static boolean isExternal(PackageParser.Package pkg) { 14758 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 14759 } 14760 14761 private static boolean isExternal(PackageSetting ps) { 14762 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 14763 } 14764 14765 private static boolean isEphemeral(PackageParser.Package pkg) { 14766 return pkg.applicationInfo.isEphemeralApp(); 14767 } 14768 14769 private static boolean isEphemeral(PackageSetting ps) { 14770 return ps.pkg != null && isEphemeral(ps.pkg); 14771 } 14772 14773 private static boolean isSystemApp(PackageParser.Package pkg) { 14774 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 14775 } 14776 14777 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 14778 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14779 } 14780 14781 private static boolean hasDomainURLs(PackageParser.Package pkg) { 14782 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 14783 } 14784 14785 private static boolean isSystemApp(PackageSetting ps) { 14786 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 14787 } 14788 14789 private static boolean isUpdatedSystemApp(PackageSetting ps) { 14790 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 14791 } 14792 14793 private int packageFlagsToInstallFlags(PackageSetting ps) { 14794 int installFlags = 0; 14795 if (isEphemeral(ps)) { 14796 installFlags |= PackageManager.INSTALL_EPHEMERAL; 14797 } 14798 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 14799 // This existing package was an external ASEC install when we have 14800 // the external flag without a UUID 14801 installFlags |= PackageManager.INSTALL_EXTERNAL; 14802 } 14803 if (ps.isForwardLocked()) { 14804 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 14805 } 14806 return installFlags; 14807 } 14808 14809 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 14810 if (isExternal(pkg)) { 14811 if (TextUtils.isEmpty(pkg.volumeUuid)) { 14812 return StorageManager.UUID_PRIMARY_PHYSICAL; 14813 } else { 14814 return pkg.volumeUuid; 14815 } 14816 } else { 14817 return StorageManager.UUID_PRIVATE_INTERNAL; 14818 } 14819 } 14820 14821 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 14822 if (isExternal(pkg)) { 14823 if (TextUtils.isEmpty(pkg.volumeUuid)) { 14824 return mSettings.getExternalVersion(); 14825 } else { 14826 return mSettings.findOrCreateVersion(pkg.volumeUuid); 14827 } 14828 } else { 14829 return mSettings.getInternalVersion(); 14830 } 14831 } 14832 14833 private void deleteTempPackageFiles() { 14834 final FilenameFilter filter = new FilenameFilter() { 14835 public boolean accept(File dir, String name) { 14836 return name.startsWith("vmdl") && name.endsWith(".tmp"); 14837 } 14838 }; 14839 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 14840 file.delete(); 14841 } 14842 } 14843 14844 @Override 14845 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 14846 int flags) { 14847 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 14848 flags); 14849 } 14850 14851 @Override 14852 public void deletePackage(final String packageName, 14853 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 14854 mContext.enforceCallingOrSelfPermission( 14855 android.Manifest.permission.DELETE_PACKAGES, null); 14856 Preconditions.checkNotNull(packageName); 14857 Preconditions.checkNotNull(observer); 14858 final int uid = Binder.getCallingUid(); 14859 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 14860 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 14861 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 14862 mContext.enforceCallingOrSelfPermission( 14863 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 14864 "deletePackage for user " + userId); 14865 } 14866 14867 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 14868 try { 14869 observer.onPackageDeleted(packageName, 14870 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 14871 } catch (RemoteException re) { 14872 } 14873 return; 14874 } 14875 14876 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 14877 try { 14878 observer.onPackageDeleted(packageName, 14879 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 14880 } catch (RemoteException re) { 14881 } 14882 return; 14883 } 14884 14885 if (DEBUG_REMOVE) { 14886 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 14887 + " deleteAllUsers: " + deleteAllUsers ); 14888 } 14889 // Queue up an async operation since the package deletion may take a little while. 14890 mHandler.post(new Runnable() { 14891 public void run() { 14892 mHandler.removeCallbacks(this); 14893 int returnCode; 14894 if (!deleteAllUsers) { 14895 returnCode = deletePackageX(packageName, userId, deleteFlags); 14896 } else { 14897 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 14898 // If nobody is blocking uninstall, proceed with delete for all users 14899 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 14900 returnCode = deletePackageX(packageName, userId, deleteFlags); 14901 } else { 14902 // Otherwise uninstall individually for users with blockUninstalls=false 14903 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 14904 for (int userId : users) { 14905 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 14906 returnCode = deletePackageX(packageName, userId, userFlags); 14907 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 14908 Slog.w(TAG, "Package delete failed for user " + userId 14909 + ", returnCode " + returnCode); 14910 } 14911 } 14912 } 14913 // The app has only been marked uninstalled for certain users. 14914 // We still need to report that delete was blocked 14915 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 14916 } 14917 } 14918 try { 14919 observer.onPackageDeleted(packageName, returnCode, null); 14920 } catch (RemoteException e) { 14921 Log.i(TAG, "Observer no longer exists."); 14922 } //end catch 14923 } //end run 14924 }); 14925 } 14926 14927 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 14928 int[] result = EMPTY_INT_ARRAY; 14929 for (int userId : userIds) { 14930 if (getBlockUninstallForUser(packageName, userId)) { 14931 result = ArrayUtils.appendInt(result, userId); 14932 } 14933 } 14934 return result; 14935 } 14936 14937 @Override 14938 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 14939 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 14940 } 14941 14942 private boolean isPackageDeviceAdmin(String packageName, int userId) { 14943 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 14944 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 14945 try { 14946 if (dpm != null) { 14947 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 14948 /* callingUserOnly =*/ false); 14949 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 14950 : deviceOwnerComponentName.getPackageName(); 14951 // Does the package contains the device owner? 14952 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 14953 // this check is probably not needed, since DO should be registered as a device 14954 // admin on some user too. (Original bug for this: b/17657954) 14955 if (packageName.equals(deviceOwnerPackageName)) { 14956 return true; 14957 } 14958 // Does it contain a device admin for any user? 14959 int[] users; 14960 if (userId == UserHandle.USER_ALL) { 14961 users = sUserManager.getUserIds(); 14962 } else { 14963 users = new int[]{userId}; 14964 } 14965 for (int i = 0; i < users.length; ++i) { 14966 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 14967 return true; 14968 } 14969 } 14970 } 14971 } catch (RemoteException e) { 14972 } 14973 return false; 14974 } 14975 14976 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 14977 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 14978 } 14979 14980 /** 14981 * This method is an internal method that could be get invoked either 14982 * to delete an installed package or to clean up a failed installation. 14983 * After deleting an installed package, a broadcast is sent to notify any 14984 * listeners that the package has been removed. For cleaning up a failed 14985 * installation, the broadcast is not necessary since the package's 14986 * installation wouldn't have sent the initial broadcast either 14987 * The key steps in deleting a package are 14988 * deleting the package information in internal structures like mPackages, 14989 * deleting the packages base directories through installd 14990 * updating mSettings to reflect current status 14991 * persisting settings for later use 14992 * sending a broadcast if necessary 14993 */ 14994 private int deletePackageX(String packageName, int userId, int deleteFlags) { 14995 final PackageRemovedInfo info = new PackageRemovedInfo(); 14996 final boolean res; 14997 14998 final UserHandle removeForUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 14999 ? UserHandle.ALL : new UserHandle(userId); 15000 15001 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 15002 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 15003 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 15004 } 15005 15006 PackageSetting uninstalledPs = null; 15007 15008 // for the uninstall-updates case and restricted profiles, remember the per- 15009 // user handle installed state 15010 int[] allUsers; 15011 synchronized (mPackages) { 15012 uninstalledPs = mSettings.mPackages.get(packageName); 15013 if (uninstalledPs == null) { 15014 Slog.w(TAG, "Not removing non-existent package " + packageName); 15015 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15016 } 15017 allUsers = sUserManager.getUserIds(); 15018 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 15019 } 15020 15021 synchronized (mInstallLock) { 15022 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 15023 try (PackageFreezer freezer = freezePackageForDelete(packageName, deleteFlags, 15024 "deletePackageX")) { 15025 res = deletePackageLIF(packageName, removeForUser, true, allUsers, 15026 deleteFlags | REMOVE_CHATTY, info, true, null); 15027 } 15028 synchronized (mPackages) { 15029 if (res) { 15030 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 15031 } 15032 } 15033 } 15034 15035 if (res) { 15036 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 15037 info.sendPackageRemovedBroadcasts(killApp); 15038 info.sendSystemPackageUpdatedBroadcasts(); 15039 info.sendSystemPackageAppearedBroadcasts(); 15040 } 15041 // Force a gc here. 15042 Runtime.getRuntime().gc(); 15043 // Delete the resources here after sending the broadcast to let 15044 // other processes clean up before deleting resources. 15045 if (info.args != null) { 15046 synchronized (mInstallLock) { 15047 info.args.doPostDeleteLI(true); 15048 } 15049 } 15050 15051 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15052 } 15053 15054 class PackageRemovedInfo { 15055 String removedPackage; 15056 int uid = -1; 15057 int removedAppId = -1; 15058 int[] origUsers; 15059 int[] removedUsers = null; 15060 boolean isRemovedPackageSystemUpdate = false; 15061 boolean isUpdate; 15062 boolean dataRemoved; 15063 boolean removedForAllUsers; 15064 // Clean up resources deleted packages. 15065 InstallArgs args = null; 15066 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 15067 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 15068 15069 void sendPackageRemovedBroadcasts(boolean killApp) { 15070 sendPackageRemovedBroadcastInternal(killApp); 15071 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 15072 for (int i = 0; i < childCount; i++) { 15073 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15074 childInfo.sendPackageRemovedBroadcastInternal(killApp); 15075 } 15076 } 15077 15078 void sendSystemPackageUpdatedBroadcasts() { 15079 if (isRemovedPackageSystemUpdate) { 15080 sendSystemPackageUpdatedBroadcastsInternal(); 15081 final int childCount = (removedChildPackages != null) 15082 ? removedChildPackages.size() : 0; 15083 for (int i = 0; i < childCount; i++) { 15084 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15085 if (childInfo.isRemovedPackageSystemUpdate) { 15086 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 15087 } 15088 } 15089 } 15090 } 15091 15092 void sendSystemPackageAppearedBroadcasts() { 15093 final int packageCount = (appearedChildPackages != null) 15094 ? appearedChildPackages.size() : 0; 15095 for (int i = 0; i < packageCount; i++) { 15096 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 15097 for (int userId : installedInfo.newUsers) { 15098 sendPackageAddedForUser(installedInfo.name, true, 15099 UserHandle.getAppId(installedInfo.uid), userId); 15100 } 15101 } 15102 } 15103 15104 private void sendSystemPackageUpdatedBroadcastsInternal() { 15105 Bundle extras = new Bundle(2); 15106 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15107 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15108 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 15109 extras, 0, null, null, null); 15110 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 15111 extras, 0, null, null, null); 15112 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 15113 null, 0, removedPackage, null, null); 15114 } 15115 15116 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 15117 Bundle extras = new Bundle(2); 15118 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15119 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 15120 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 15121 if (isUpdate || isRemovedPackageSystemUpdate) { 15122 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15123 } 15124 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 15125 if (removedPackage != null) { 15126 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 15127 extras, 0, null, null, removedUsers); 15128 if (dataRemoved && !isRemovedPackageSystemUpdate) { 15129 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 15130 removedPackage, extras, 0, null, null, removedUsers); 15131 } 15132 } 15133 if (removedAppId >= 0) { 15134 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 15135 removedUsers); 15136 } 15137 } 15138 } 15139 15140 /* 15141 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 15142 * flag is not set, the data directory is removed as well. 15143 * make sure this flag is set for partially installed apps. If not its meaningless to 15144 * delete a partially installed application. 15145 */ 15146 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 15147 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 15148 String packageName = ps.name; 15149 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 15150 // Retrieve object to delete permissions for shared user later on 15151 final PackageParser.Package deletedPkg; 15152 final PackageSetting deletedPs; 15153 // reader 15154 synchronized (mPackages) { 15155 deletedPkg = mPackages.get(packageName); 15156 deletedPs = mSettings.mPackages.get(packageName); 15157 if (outInfo != null) { 15158 outInfo.removedPackage = packageName; 15159 outInfo.removedUsers = deletedPs != null 15160 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 15161 : null; 15162 } 15163 } 15164 15165 removePackageLI(ps, (flags & REMOVE_CHATTY) != 0); 15166 15167 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 15168 destroyAppDataLIF(deletedPkg, UserHandle.USER_ALL, 15169 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15170 destroyAppProfilesLIF(deletedPkg); 15171 if (outInfo != null) { 15172 outInfo.dataRemoved = true; 15173 } 15174 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 15175 } 15176 15177 // writer 15178 synchronized (mPackages) { 15179 if (deletedPs != null) { 15180 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 15181 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 15182 clearDefaultBrowserIfNeeded(packageName); 15183 if (outInfo != null) { 15184 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 15185 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 15186 } 15187 updatePermissionsLPw(deletedPs.name, null, 0); 15188 if (deletedPs.sharedUser != null) { 15189 // Remove permissions associated with package. Since runtime 15190 // permissions are per user we have to kill the removed package 15191 // or packages running under the shared user of the removed 15192 // package if revoking the permissions requested only by the removed 15193 // package is successful and this causes a change in gids. 15194 for (int userId : UserManagerService.getInstance().getUserIds()) { 15195 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 15196 userId); 15197 if (userIdToKill == UserHandle.USER_ALL 15198 || userIdToKill >= UserHandle.USER_SYSTEM) { 15199 // If gids changed for this user, kill all affected packages. 15200 mHandler.post(new Runnable() { 15201 @Override 15202 public void run() { 15203 // This has to happen with no lock held. 15204 killApplication(deletedPs.name, deletedPs.appId, 15205 KILL_APP_REASON_GIDS_CHANGED); 15206 } 15207 }); 15208 break; 15209 } 15210 } 15211 } 15212 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 15213 } 15214 // make sure to preserve per-user disabled state if this removal was just 15215 // a downgrade of a system app to the factory package 15216 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 15217 if (DEBUG_REMOVE) { 15218 Slog.d(TAG, "Propagating install state across downgrade"); 15219 } 15220 for (int userId : allUserHandles) { 15221 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15222 if (DEBUG_REMOVE) { 15223 Slog.d(TAG, " user " + userId + " => " + installed); 15224 } 15225 ps.setInstalled(installed, userId); 15226 } 15227 } 15228 } 15229 // can downgrade to reader 15230 if (writeSettings) { 15231 // Save settings now 15232 mSettings.writeLPr(); 15233 } 15234 } 15235 if (outInfo != null) { 15236 // A user ID was deleted here. Go through all users and remove it 15237 // from KeyStore. 15238 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 15239 } 15240 } 15241 15242 static boolean locationIsPrivileged(File path) { 15243 try { 15244 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 15245 .getCanonicalPath(); 15246 return path.getCanonicalPath().startsWith(privilegedAppDir); 15247 } catch (IOException e) { 15248 Slog.e(TAG, "Unable to access code path " + path); 15249 } 15250 return false; 15251 } 15252 15253 /* 15254 * Tries to delete system package. 15255 */ 15256 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 15257 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 15258 boolean writeSettings) { 15259 if (deletedPs.parentPackageName != null) { 15260 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 15261 return false; 15262 } 15263 15264 final boolean applyUserRestrictions 15265 = (allUserHandles != null) && (outInfo.origUsers != null); 15266 final PackageSetting disabledPs; 15267 // Confirm if the system package has been updated 15268 // An updated system app can be deleted. This will also have to restore 15269 // the system pkg from system partition 15270 // reader 15271 synchronized (mPackages) { 15272 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 15273 } 15274 15275 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 15276 + " disabledPs=" + disabledPs); 15277 15278 if (disabledPs == null) { 15279 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 15280 return false; 15281 } else if (DEBUG_REMOVE) { 15282 Slog.d(TAG, "Deleting system pkg from data partition"); 15283 } 15284 15285 if (DEBUG_REMOVE) { 15286 if (applyUserRestrictions) { 15287 Slog.d(TAG, "Remembering install states:"); 15288 for (int userId : allUserHandles) { 15289 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 15290 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 15291 } 15292 } 15293 } 15294 15295 // Delete the updated package 15296 outInfo.isRemovedPackageSystemUpdate = true; 15297 if (outInfo.removedChildPackages != null) { 15298 final int childCount = (deletedPs.childPackageNames != null) 15299 ? deletedPs.childPackageNames.size() : 0; 15300 for (int i = 0; i < childCount; i++) { 15301 String childPackageName = deletedPs.childPackageNames.get(i); 15302 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 15303 .contains(childPackageName)) { 15304 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15305 childPackageName); 15306 if (childInfo != null) { 15307 childInfo.isRemovedPackageSystemUpdate = true; 15308 } 15309 } 15310 } 15311 } 15312 15313 if (disabledPs.versionCode < deletedPs.versionCode) { 15314 // Delete data for downgrades 15315 flags &= ~PackageManager.DELETE_KEEP_DATA; 15316 } else { 15317 // Preserve data by setting flag 15318 flags |= PackageManager.DELETE_KEEP_DATA; 15319 } 15320 15321 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 15322 outInfo, writeSettings, disabledPs.pkg); 15323 if (!ret) { 15324 return false; 15325 } 15326 15327 // writer 15328 synchronized (mPackages) { 15329 // Reinstate the old system package 15330 enableSystemPackageLPw(disabledPs.pkg); 15331 // Remove any native libraries from the upgraded package. 15332 removeNativeBinariesLI(deletedPs); 15333 } 15334 15335 // Install the system package 15336 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 15337 int parseFlags = mDefParseFlags 15338 | PackageParser.PARSE_MUST_BE_APK 15339 | PackageParser.PARSE_IS_SYSTEM 15340 | PackageParser.PARSE_IS_SYSTEM_DIR; 15341 if (locationIsPrivileged(disabledPs.codePath)) { 15342 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 15343 } 15344 15345 final PackageParser.Package newPkg; 15346 try { 15347 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 15348 } catch (PackageManagerException e) { 15349 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 15350 + e.getMessage()); 15351 return false; 15352 } 15353 15354 prepareAppDataAfterInstallLIF(newPkg); 15355 15356 // writer 15357 synchronized (mPackages) { 15358 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 15359 15360 // Propagate the permissions state as we do not want to drop on the floor 15361 // runtime permissions. The update permissions method below will take 15362 // care of removing obsolete permissions and grant install permissions. 15363 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 15364 updatePermissionsLPw(newPkg.packageName, newPkg, 15365 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 15366 15367 if (applyUserRestrictions) { 15368 if (DEBUG_REMOVE) { 15369 Slog.d(TAG, "Propagating install state across reinstall"); 15370 } 15371 for (int userId : allUserHandles) { 15372 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15373 if (DEBUG_REMOVE) { 15374 Slog.d(TAG, " user " + userId + " => " + installed); 15375 } 15376 ps.setInstalled(installed, userId); 15377 15378 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 15379 } 15380 // Regardless of writeSettings we need to ensure that this restriction 15381 // state propagation is persisted 15382 mSettings.writeAllUsersPackageRestrictionsLPr(); 15383 } 15384 // can downgrade to reader here 15385 if (writeSettings) { 15386 mSettings.writeLPr(); 15387 } 15388 } 15389 return true; 15390 } 15391 15392 private boolean deleteInstalledPackageLIF(PackageSetting ps, 15393 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 15394 PackageRemovedInfo outInfo, boolean writeSettings, 15395 PackageParser.Package replacingPackage) { 15396 synchronized (mPackages) { 15397 if (outInfo != null) { 15398 outInfo.uid = ps.appId; 15399 } 15400 15401 if (outInfo != null && outInfo.removedChildPackages != null) { 15402 final int childCount = (ps.childPackageNames != null) 15403 ? ps.childPackageNames.size() : 0; 15404 for (int i = 0; i < childCount; i++) { 15405 String childPackageName = ps.childPackageNames.get(i); 15406 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 15407 if (childPs == null) { 15408 return false; 15409 } 15410 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15411 childPackageName); 15412 if (childInfo != null) { 15413 childInfo.uid = childPs.appId; 15414 } 15415 } 15416 } 15417 } 15418 15419 // Delete package data from internal structures and also remove data if flag is set 15420 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 15421 15422 // Delete the child packages data 15423 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 15424 for (int i = 0; i < childCount; i++) { 15425 PackageSetting childPs; 15426 synchronized (mPackages) { 15427 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 15428 } 15429 if (childPs != null) { 15430 PackageRemovedInfo childOutInfo = (outInfo != null 15431 && outInfo.removedChildPackages != null) 15432 ? outInfo.removedChildPackages.get(childPs.name) : null; 15433 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 15434 && (replacingPackage != null 15435 && !replacingPackage.hasChildPackage(childPs.name)) 15436 ? flags & ~DELETE_KEEP_DATA : flags; 15437 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 15438 deleteFlags, writeSettings); 15439 } 15440 } 15441 15442 // Delete application code and resources only for parent packages 15443 if (ps.parentPackageName == null) { 15444 if (deleteCodeAndResources && (outInfo != null)) { 15445 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 15446 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 15447 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 15448 } 15449 } 15450 15451 return true; 15452 } 15453 15454 @Override 15455 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 15456 int userId) { 15457 mContext.enforceCallingOrSelfPermission( 15458 android.Manifest.permission.DELETE_PACKAGES, null); 15459 synchronized (mPackages) { 15460 PackageSetting ps = mSettings.mPackages.get(packageName); 15461 if (ps == null) { 15462 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 15463 return false; 15464 } 15465 if (!ps.getInstalled(userId)) { 15466 // Can't block uninstall for an app that is not installed or enabled. 15467 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 15468 return false; 15469 } 15470 ps.setBlockUninstall(blockUninstall, userId); 15471 mSettings.writePackageRestrictionsLPr(userId); 15472 } 15473 return true; 15474 } 15475 15476 @Override 15477 public boolean getBlockUninstallForUser(String packageName, int userId) { 15478 synchronized (mPackages) { 15479 PackageSetting ps = mSettings.mPackages.get(packageName); 15480 if (ps == null) { 15481 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 15482 return false; 15483 } 15484 return ps.getBlockUninstall(userId); 15485 } 15486 } 15487 15488 @Override 15489 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 15490 int callingUid = Binder.getCallingUid(); 15491 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 15492 throw new SecurityException( 15493 "setRequiredForSystemUser can only be run by the system or root"); 15494 } 15495 synchronized (mPackages) { 15496 PackageSetting ps = mSettings.mPackages.get(packageName); 15497 if (ps == null) { 15498 Log.w(TAG, "Package doesn't exist: " + packageName); 15499 return false; 15500 } 15501 if (systemUserApp) { 15502 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15503 } else { 15504 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15505 } 15506 mSettings.writeLPr(); 15507 } 15508 return true; 15509 } 15510 15511 /* 15512 * This method handles package deletion in general 15513 */ 15514 private boolean deletePackageLIF(String packageName, UserHandle user, 15515 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 15516 PackageRemovedInfo outInfo, boolean writeSettings, 15517 PackageParser.Package replacingPackage) { 15518 if (packageName == null) { 15519 Slog.w(TAG, "Attempt to delete null packageName."); 15520 return false; 15521 } 15522 15523 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 15524 15525 PackageSetting ps; 15526 15527 synchronized (mPackages) { 15528 ps = mSettings.mPackages.get(packageName); 15529 if (ps == null) { 15530 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 15531 return false; 15532 } 15533 15534 if (ps.parentPackageName != null && (!isSystemApp(ps) 15535 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 15536 if (DEBUG_REMOVE) { 15537 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 15538 + ((user == null) ? UserHandle.USER_ALL : user)); 15539 } 15540 final int removedUserId = (user != null) ? user.getIdentifier() 15541 : UserHandle.USER_ALL; 15542 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 15543 return false; 15544 } 15545 markPackageUninstalledForUserLPw(ps, user); 15546 scheduleWritePackageRestrictionsLocked(user); 15547 return true; 15548 } 15549 } 15550 15551 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 15552 && user.getIdentifier() != UserHandle.USER_ALL)) { 15553 // The caller is asking that the package only be deleted for a single 15554 // user. To do this, we just mark its uninstalled state and delete 15555 // its data. If this is a system app, we only allow this to happen if 15556 // they have set the special DELETE_SYSTEM_APP which requests different 15557 // semantics than normal for uninstalling system apps. 15558 markPackageUninstalledForUserLPw(ps, user); 15559 15560 if (!isSystemApp(ps)) { 15561 // Do not uninstall the APK if an app should be cached 15562 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 15563 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 15564 // Other user still have this package installed, so all 15565 // we need to do is clear this user's data and save that 15566 // it is uninstalled. 15567 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 15568 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 15569 return false; 15570 } 15571 scheduleWritePackageRestrictionsLocked(user); 15572 return true; 15573 } else { 15574 // We need to set it back to 'installed' so the uninstall 15575 // broadcasts will be sent correctly. 15576 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 15577 ps.setInstalled(true, user.getIdentifier()); 15578 } 15579 } else { 15580 // This is a system app, so we assume that the 15581 // other users still have this package installed, so all 15582 // we need to do is clear this user's data and save that 15583 // it is uninstalled. 15584 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 15585 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 15586 return false; 15587 } 15588 scheduleWritePackageRestrictionsLocked(user); 15589 return true; 15590 } 15591 } 15592 15593 // If we are deleting a composite package for all users, keep track 15594 // of result for each child. 15595 if (ps.childPackageNames != null && outInfo != null) { 15596 synchronized (mPackages) { 15597 final int childCount = ps.childPackageNames.size(); 15598 outInfo.removedChildPackages = new ArrayMap<>(childCount); 15599 for (int i = 0; i < childCount; i++) { 15600 String childPackageName = ps.childPackageNames.get(i); 15601 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 15602 childInfo.removedPackage = childPackageName; 15603 outInfo.removedChildPackages.put(childPackageName, childInfo); 15604 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 15605 if (childPs != null) { 15606 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 15607 } 15608 } 15609 } 15610 } 15611 15612 boolean ret = false; 15613 if (isSystemApp(ps)) { 15614 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 15615 // When an updated system application is deleted we delete the existing resources 15616 // as well and fall back to existing code in system partition 15617 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 15618 } else { 15619 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 15620 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 15621 outInfo, writeSettings, replacingPackage); 15622 } 15623 15624 // Take a note whether we deleted the package for all users 15625 if (outInfo != null) { 15626 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 15627 if (outInfo.removedChildPackages != null) { 15628 synchronized (mPackages) { 15629 final int childCount = outInfo.removedChildPackages.size(); 15630 for (int i = 0; i < childCount; i++) { 15631 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 15632 if (childInfo != null) { 15633 childInfo.removedForAllUsers = mPackages.get( 15634 childInfo.removedPackage) == null; 15635 } 15636 } 15637 } 15638 } 15639 // If we uninstalled an update to a system app there may be some 15640 // child packages that appeared as they are declared in the system 15641 // app but were not declared in the update. 15642 if (isSystemApp(ps)) { 15643 synchronized (mPackages) { 15644 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 15645 final int childCount = (updatedPs.childPackageNames != null) 15646 ? updatedPs.childPackageNames.size() : 0; 15647 for (int i = 0; i < childCount; i++) { 15648 String childPackageName = updatedPs.childPackageNames.get(i); 15649 if (outInfo.removedChildPackages == null 15650 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 15651 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 15652 if (childPs == null) { 15653 continue; 15654 } 15655 PackageInstalledInfo installRes = new PackageInstalledInfo(); 15656 installRes.name = childPackageName; 15657 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 15658 installRes.pkg = mPackages.get(childPackageName); 15659 installRes.uid = childPs.pkg.applicationInfo.uid; 15660 if (outInfo.appearedChildPackages == null) { 15661 outInfo.appearedChildPackages = new ArrayMap<>(); 15662 } 15663 outInfo.appearedChildPackages.put(childPackageName, installRes); 15664 } 15665 } 15666 } 15667 } 15668 } 15669 15670 return ret; 15671 } 15672 15673 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 15674 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 15675 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 15676 for (int nextUserId : userIds) { 15677 if (DEBUG_REMOVE) { 15678 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 15679 } 15680 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 15681 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 15682 false /*hidden*/, false /*suspended*/, null, null, null, 15683 false /*blockUninstall*/, 15684 ps.readUserState(nextUserId).domainVerificationStatus, 0); 15685 } 15686 } 15687 15688 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 15689 PackageRemovedInfo outInfo) { 15690 final PackageParser.Package pkg; 15691 synchronized (mPackages) { 15692 pkg = mPackages.get(ps.name); 15693 } 15694 15695 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 15696 : new int[] {userId}; 15697 for (int nextUserId : userIds) { 15698 if (DEBUG_REMOVE) { 15699 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 15700 + nextUserId); 15701 } 15702 15703 destroyAppDataLIF(pkg, userId, 15704 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15705 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 15706 schedulePackageCleaning(ps.name, nextUserId, false); 15707 synchronized (mPackages) { 15708 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 15709 scheduleWritePackageRestrictionsLocked(nextUserId); 15710 } 15711 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 15712 } 15713 } 15714 15715 if (outInfo != null) { 15716 outInfo.removedPackage = ps.name; 15717 outInfo.removedAppId = ps.appId; 15718 outInfo.removedUsers = userIds; 15719 } 15720 15721 return true; 15722 } 15723 15724 private final class ClearStorageConnection implements ServiceConnection { 15725 IMediaContainerService mContainerService; 15726 15727 @Override 15728 public void onServiceConnected(ComponentName name, IBinder service) { 15729 synchronized (this) { 15730 mContainerService = IMediaContainerService.Stub.asInterface(service); 15731 notifyAll(); 15732 } 15733 } 15734 15735 @Override 15736 public void onServiceDisconnected(ComponentName name) { 15737 } 15738 } 15739 15740 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 15741 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 15742 15743 final boolean mounted; 15744 if (Environment.isExternalStorageEmulated()) { 15745 mounted = true; 15746 } else { 15747 final String status = Environment.getExternalStorageState(); 15748 15749 mounted = status.equals(Environment.MEDIA_MOUNTED) 15750 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 15751 } 15752 15753 if (!mounted) { 15754 return; 15755 } 15756 15757 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 15758 int[] users; 15759 if (userId == UserHandle.USER_ALL) { 15760 users = sUserManager.getUserIds(); 15761 } else { 15762 users = new int[] { userId }; 15763 } 15764 final ClearStorageConnection conn = new ClearStorageConnection(); 15765 if (mContext.bindServiceAsUser( 15766 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 15767 try { 15768 for (int curUser : users) { 15769 long timeout = SystemClock.uptimeMillis() + 5000; 15770 synchronized (conn) { 15771 long now = SystemClock.uptimeMillis(); 15772 while (conn.mContainerService == null && now < timeout) { 15773 try { 15774 conn.wait(timeout - now); 15775 } catch (InterruptedException e) { 15776 } 15777 } 15778 } 15779 if (conn.mContainerService == null) { 15780 return; 15781 } 15782 15783 final UserEnvironment userEnv = new UserEnvironment(curUser); 15784 clearDirectory(conn.mContainerService, 15785 userEnv.buildExternalStorageAppCacheDirs(packageName)); 15786 if (allData) { 15787 clearDirectory(conn.mContainerService, 15788 userEnv.buildExternalStorageAppDataDirs(packageName)); 15789 clearDirectory(conn.mContainerService, 15790 userEnv.buildExternalStorageAppMediaDirs(packageName)); 15791 } 15792 } 15793 } finally { 15794 mContext.unbindService(conn); 15795 } 15796 } 15797 } 15798 15799 @Override 15800 public void clearApplicationProfileData(String packageName) { 15801 enforceSystemOrRoot("Only the system can clear all profile data"); 15802 15803 final PackageParser.Package pkg; 15804 synchronized (mPackages) { 15805 pkg = mPackages.get(packageName); 15806 } 15807 15808 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 15809 synchronized (mInstallLock) { 15810 clearAppProfilesLIF(pkg); 15811 } 15812 } 15813 } 15814 15815 @Override 15816 public void clearApplicationUserData(final String packageName, 15817 final IPackageDataObserver observer, final int userId) { 15818 mContext.enforceCallingOrSelfPermission( 15819 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 15820 15821 enforceCrossUserPermission(Binder.getCallingUid(), userId, 15822 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 15823 15824 final DevicePolicyManagerInternal dpmi = LocalServices 15825 .getService(DevicePolicyManagerInternal.class); 15826 if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) { 15827 throw new SecurityException("Cannot clear data for a device owner or a profile owner"); 15828 } 15829 // Queue up an async operation since the package deletion may take a little while. 15830 mHandler.post(new Runnable() { 15831 public void run() { 15832 mHandler.removeCallbacks(this); 15833 final boolean succeeded; 15834 try (PackageFreezer freezer = freezePackage(packageName, 15835 "clearApplicationUserData")) { 15836 synchronized (mInstallLock) { 15837 succeeded = clearApplicationUserDataLIF(packageName, userId); 15838 } 15839 clearExternalStorageDataSync(packageName, userId, true); 15840 } 15841 if (succeeded) { 15842 // invoke DeviceStorageMonitor's update method to clear any notifications 15843 DeviceStorageMonitorInternal dsm = LocalServices 15844 .getService(DeviceStorageMonitorInternal.class); 15845 if (dsm != null) { 15846 dsm.checkMemory(); 15847 } 15848 } 15849 if(observer != null) { 15850 try { 15851 observer.onRemoveCompleted(packageName, succeeded); 15852 } catch (RemoteException e) { 15853 Log.i(TAG, "Observer no longer exists."); 15854 } 15855 } //end if observer 15856 } //end run 15857 }); 15858 } 15859 15860 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 15861 if (packageName == null) { 15862 Slog.w(TAG, "Attempt to delete null packageName."); 15863 return false; 15864 } 15865 15866 // Try finding details about the requested package 15867 PackageParser.Package pkg; 15868 synchronized (mPackages) { 15869 pkg = mPackages.get(packageName); 15870 if (pkg == null) { 15871 final PackageSetting ps = mSettings.mPackages.get(packageName); 15872 if (ps != null) { 15873 pkg = ps.pkg; 15874 } 15875 } 15876 15877 if (pkg == null) { 15878 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 15879 return false; 15880 } 15881 15882 PackageSetting ps = (PackageSetting) pkg.mExtras; 15883 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 15884 } 15885 15886 clearAppDataLIF(pkg, userId, 15887 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15888 15889 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 15890 removeKeystoreDataIfNeeded(userId, appId); 15891 15892 final UserManager um = mContext.getSystemService(UserManager.class); 15893 final int flags; 15894 if (um.isUserUnlocked(userId)) { 15895 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 15896 } else if (um.isUserRunning(userId)) { 15897 flags = StorageManager.FLAG_STORAGE_DE; 15898 } else { 15899 flags = 0; 15900 } 15901 prepareAppDataContentsLIF(pkg, userId, flags); 15902 15903 return true; 15904 } 15905 15906 /** 15907 * Reverts user permission state changes (permissions and flags) in 15908 * all packages for a given user. 15909 * 15910 * @param userId The device user for which to do a reset. 15911 */ 15912 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 15913 final int packageCount = mPackages.size(); 15914 for (int i = 0; i < packageCount; i++) { 15915 PackageParser.Package pkg = mPackages.valueAt(i); 15916 PackageSetting ps = (PackageSetting) pkg.mExtras; 15917 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 15918 } 15919 } 15920 15921 /** 15922 * Reverts user permission state changes (permissions and flags). 15923 * 15924 * @param ps The package for which to reset. 15925 * @param userId The device user for which to do a reset. 15926 */ 15927 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 15928 final PackageSetting ps, final int userId) { 15929 if (ps.pkg == null) { 15930 return; 15931 } 15932 15933 // These are flags that can change base on user actions. 15934 final int userSettableMask = FLAG_PERMISSION_USER_SET 15935 | FLAG_PERMISSION_USER_FIXED 15936 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 15937 | FLAG_PERMISSION_REVIEW_REQUIRED; 15938 15939 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 15940 | FLAG_PERMISSION_POLICY_FIXED; 15941 15942 boolean writeInstallPermissions = false; 15943 boolean writeRuntimePermissions = false; 15944 15945 final int permissionCount = ps.pkg.requestedPermissions.size(); 15946 for (int i = 0; i < permissionCount; i++) { 15947 String permission = ps.pkg.requestedPermissions.get(i); 15948 15949 BasePermission bp = mSettings.mPermissions.get(permission); 15950 if (bp == null) { 15951 continue; 15952 } 15953 15954 // If shared user we just reset the state to which only this app contributed. 15955 if (ps.sharedUser != null) { 15956 boolean used = false; 15957 final int packageCount = ps.sharedUser.packages.size(); 15958 for (int j = 0; j < packageCount; j++) { 15959 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 15960 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 15961 && pkg.pkg.requestedPermissions.contains(permission)) { 15962 used = true; 15963 break; 15964 } 15965 } 15966 if (used) { 15967 continue; 15968 } 15969 } 15970 15971 PermissionsState permissionsState = ps.getPermissionsState(); 15972 15973 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 15974 15975 // Always clear the user settable flags. 15976 final boolean hasInstallState = permissionsState.getInstallPermissionState( 15977 bp.name) != null; 15978 // If permission review is enabled and this is a legacy app, mark the 15979 // permission as requiring a review as this is the initial state. 15980 int flags = 0; 15981 if (Build.PERMISSIONS_REVIEW_REQUIRED 15982 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 15983 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 15984 } 15985 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 15986 if (hasInstallState) { 15987 writeInstallPermissions = true; 15988 } else { 15989 writeRuntimePermissions = true; 15990 } 15991 } 15992 15993 // Below is only runtime permission handling. 15994 if (!bp.isRuntime()) { 15995 continue; 15996 } 15997 15998 // Never clobber system or policy. 15999 if ((oldFlags & policyOrSystemFlags) != 0) { 16000 continue; 16001 } 16002 16003 // If this permission was granted by default, make sure it is. 16004 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 16005 if (permissionsState.grantRuntimePermission(bp, userId) 16006 != PERMISSION_OPERATION_FAILURE) { 16007 writeRuntimePermissions = true; 16008 } 16009 // If permission review is enabled the permissions for a legacy apps 16010 // are represented as constantly granted runtime ones, so don't revoke. 16011 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 16012 // Otherwise, reset the permission. 16013 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 16014 switch (revokeResult) { 16015 case PERMISSION_OPERATION_SUCCESS: 16016 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 16017 writeRuntimePermissions = true; 16018 final int appId = ps.appId; 16019 mHandler.post(new Runnable() { 16020 @Override 16021 public void run() { 16022 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 16023 } 16024 }); 16025 } break; 16026 } 16027 } 16028 } 16029 16030 // Synchronously write as we are taking permissions away. 16031 if (writeRuntimePermissions) { 16032 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 16033 } 16034 16035 // Synchronously write as we are taking permissions away. 16036 if (writeInstallPermissions) { 16037 mSettings.writeLPr(); 16038 } 16039 } 16040 16041 /** 16042 * Remove entries from the keystore daemon. Will only remove it if the 16043 * {@code appId} is valid. 16044 */ 16045 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 16046 if (appId < 0) { 16047 return; 16048 } 16049 16050 final KeyStore keyStore = KeyStore.getInstance(); 16051 if (keyStore != null) { 16052 if (userId == UserHandle.USER_ALL) { 16053 for (final int individual : sUserManager.getUserIds()) { 16054 keyStore.clearUid(UserHandle.getUid(individual, appId)); 16055 } 16056 } else { 16057 keyStore.clearUid(UserHandle.getUid(userId, appId)); 16058 } 16059 } else { 16060 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 16061 } 16062 } 16063 16064 @Override 16065 public void deleteApplicationCacheFiles(final String packageName, 16066 final IPackageDataObserver observer) { 16067 final int userId = UserHandle.getCallingUserId(); 16068 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 16069 } 16070 16071 @Override 16072 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 16073 final IPackageDataObserver observer) { 16074 mContext.enforceCallingOrSelfPermission( 16075 android.Manifest.permission.DELETE_CACHE_FILES, null); 16076 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16077 /* requireFullPermission= */ true, /* checkShell= */ false, 16078 "delete application cache files"); 16079 16080 final PackageParser.Package pkg; 16081 synchronized (mPackages) { 16082 pkg = mPackages.get(packageName); 16083 } 16084 16085 // Queue up an async operation since the package deletion may take a little while. 16086 mHandler.post(new Runnable() { 16087 public void run() { 16088 synchronized (mInstallLock) { 16089 final int flags = StorageManager.FLAG_STORAGE_DE 16090 | StorageManager.FLAG_STORAGE_CE; 16091 // We're only clearing cache files, so we don't care if the 16092 // app is unfrozen and still able to run 16093 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 16094 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16095 } 16096 clearExternalStorageDataSync(packageName, userId, false); 16097 if (observer != null) { 16098 try { 16099 observer.onRemoveCompleted(packageName, true); 16100 } catch (RemoteException e) { 16101 Log.i(TAG, "Observer no longer exists."); 16102 } 16103 } 16104 } 16105 }); 16106 } 16107 16108 @Override 16109 public void getPackageSizeInfo(final String packageName, int userHandle, 16110 final IPackageStatsObserver observer) { 16111 mContext.enforceCallingOrSelfPermission( 16112 android.Manifest.permission.GET_PACKAGE_SIZE, null); 16113 if (packageName == null) { 16114 throw new IllegalArgumentException("Attempt to get size of null packageName"); 16115 } 16116 16117 PackageStats stats = new PackageStats(packageName, userHandle); 16118 16119 /* 16120 * Queue up an async operation since the package measurement may take a 16121 * little while. 16122 */ 16123 Message msg = mHandler.obtainMessage(INIT_COPY); 16124 msg.obj = new MeasureParams(stats, observer); 16125 mHandler.sendMessage(msg); 16126 } 16127 16128 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 16129 final PackageSetting ps; 16130 synchronized (mPackages) { 16131 ps = mSettings.mPackages.get(packageName); 16132 if (ps == null) { 16133 Slog.w(TAG, "Failed to find settings for " + packageName); 16134 return false; 16135 } 16136 } 16137 try { 16138 mInstaller.getAppSize(ps.volumeUuid, packageName, userId, 16139 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 16140 ps.getCeDataInode(userId), ps.codePathString, stats); 16141 } catch (InstallerException e) { 16142 Slog.w(TAG, String.valueOf(e)); 16143 return false; 16144 } 16145 16146 // For now, ignore code size of packages on system partition 16147 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 16148 stats.codeSize = 0; 16149 } 16150 16151 return true; 16152 } 16153 16154 private int getUidTargetSdkVersionLockedLPr(int uid) { 16155 Object obj = mSettings.getUserIdLPr(uid); 16156 if (obj instanceof SharedUserSetting) { 16157 final SharedUserSetting sus = (SharedUserSetting) obj; 16158 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 16159 final Iterator<PackageSetting> it = sus.packages.iterator(); 16160 while (it.hasNext()) { 16161 final PackageSetting ps = it.next(); 16162 if (ps.pkg != null) { 16163 int v = ps.pkg.applicationInfo.targetSdkVersion; 16164 if (v < vers) vers = v; 16165 } 16166 } 16167 return vers; 16168 } else if (obj instanceof PackageSetting) { 16169 final PackageSetting ps = (PackageSetting) obj; 16170 if (ps.pkg != null) { 16171 return ps.pkg.applicationInfo.targetSdkVersion; 16172 } 16173 } 16174 return Build.VERSION_CODES.CUR_DEVELOPMENT; 16175 } 16176 16177 @Override 16178 public void addPreferredActivity(IntentFilter filter, int match, 16179 ComponentName[] set, ComponentName activity, int userId) { 16180 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16181 "Adding preferred"); 16182 } 16183 16184 private void addPreferredActivityInternal(IntentFilter filter, int match, 16185 ComponentName[] set, ComponentName activity, boolean always, int userId, 16186 String opname) { 16187 // writer 16188 int callingUid = Binder.getCallingUid(); 16189 enforceCrossUserPermission(callingUid, userId, 16190 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 16191 if (filter.countActions() == 0) { 16192 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16193 return; 16194 } 16195 synchronized (mPackages) { 16196 if (mContext.checkCallingOrSelfPermission( 16197 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16198 != PackageManager.PERMISSION_GRANTED) { 16199 if (getUidTargetSdkVersionLockedLPr(callingUid) 16200 < Build.VERSION_CODES.FROYO) { 16201 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 16202 + callingUid); 16203 return; 16204 } 16205 mContext.enforceCallingOrSelfPermission( 16206 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16207 } 16208 16209 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 16210 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 16211 + userId + ":"); 16212 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16213 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 16214 scheduleWritePackageRestrictionsLocked(userId); 16215 } 16216 } 16217 16218 @Override 16219 public void replacePreferredActivity(IntentFilter filter, int match, 16220 ComponentName[] set, ComponentName activity, int userId) { 16221 if (filter.countActions() != 1) { 16222 throw new IllegalArgumentException( 16223 "replacePreferredActivity expects filter to have only 1 action."); 16224 } 16225 if (filter.countDataAuthorities() != 0 16226 || filter.countDataPaths() != 0 16227 || filter.countDataSchemes() > 1 16228 || filter.countDataTypes() != 0) { 16229 throw new IllegalArgumentException( 16230 "replacePreferredActivity expects filter to have no data authorities, " + 16231 "paths, or types; and at most one scheme."); 16232 } 16233 16234 final int callingUid = Binder.getCallingUid(); 16235 enforceCrossUserPermission(callingUid, userId, 16236 true /* requireFullPermission */, false /* checkShell */, 16237 "replace preferred activity"); 16238 synchronized (mPackages) { 16239 if (mContext.checkCallingOrSelfPermission( 16240 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16241 != PackageManager.PERMISSION_GRANTED) { 16242 if (getUidTargetSdkVersionLockedLPr(callingUid) 16243 < Build.VERSION_CODES.FROYO) { 16244 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 16245 + Binder.getCallingUid()); 16246 return; 16247 } 16248 mContext.enforceCallingOrSelfPermission( 16249 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16250 } 16251 16252 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16253 if (pir != null) { 16254 // Get all of the existing entries that exactly match this filter. 16255 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 16256 if (existing != null && existing.size() == 1) { 16257 PreferredActivity cur = existing.get(0); 16258 if (DEBUG_PREFERRED) { 16259 Slog.i(TAG, "Checking replace of preferred:"); 16260 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16261 if (!cur.mPref.mAlways) { 16262 Slog.i(TAG, " -- CUR; not mAlways!"); 16263 } else { 16264 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 16265 Slog.i(TAG, " -- CUR: mSet=" 16266 + Arrays.toString(cur.mPref.mSetComponents)); 16267 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 16268 Slog.i(TAG, " -- NEW: mMatch=" 16269 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 16270 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 16271 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 16272 } 16273 } 16274 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 16275 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 16276 && cur.mPref.sameSet(set)) { 16277 // Setting the preferred activity to what it happens to be already 16278 if (DEBUG_PREFERRED) { 16279 Slog.i(TAG, "Replacing with same preferred activity " 16280 + cur.mPref.mShortComponent + " for user " 16281 + userId + ":"); 16282 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16283 } 16284 return; 16285 } 16286 } 16287 16288 if (existing != null) { 16289 if (DEBUG_PREFERRED) { 16290 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 16291 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16292 } 16293 for (int i = 0; i < existing.size(); i++) { 16294 PreferredActivity pa = existing.get(i); 16295 if (DEBUG_PREFERRED) { 16296 Slog.i(TAG, "Removing existing preferred activity " 16297 + pa.mPref.mComponent + ":"); 16298 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 16299 } 16300 pir.removeFilter(pa); 16301 } 16302 } 16303 } 16304 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16305 "Replacing preferred"); 16306 } 16307 } 16308 16309 @Override 16310 public void clearPackagePreferredActivities(String packageName) { 16311 final int uid = Binder.getCallingUid(); 16312 // writer 16313 synchronized (mPackages) { 16314 PackageParser.Package pkg = mPackages.get(packageName); 16315 if (pkg == null || pkg.applicationInfo.uid != uid) { 16316 if (mContext.checkCallingOrSelfPermission( 16317 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16318 != PackageManager.PERMISSION_GRANTED) { 16319 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 16320 < Build.VERSION_CODES.FROYO) { 16321 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 16322 + Binder.getCallingUid()); 16323 return; 16324 } 16325 mContext.enforceCallingOrSelfPermission( 16326 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16327 } 16328 } 16329 16330 int user = UserHandle.getCallingUserId(); 16331 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 16332 scheduleWritePackageRestrictionsLocked(user); 16333 } 16334 } 16335 } 16336 16337 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16338 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 16339 ArrayList<PreferredActivity> removed = null; 16340 boolean changed = false; 16341 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16342 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 16343 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16344 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 16345 continue; 16346 } 16347 Iterator<PreferredActivity> it = pir.filterIterator(); 16348 while (it.hasNext()) { 16349 PreferredActivity pa = it.next(); 16350 // Mark entry for removal only if it matches the package name 16351 // and the entry is of type "always". 16352 if (packageName == null || 16353 (pa.mPref.mComponent.getPackageName().equals(packageName) 16354 && pa.mPref.mAlways)) { 16355 if (removed == null) { 16356 removed = new ArrayList<PreferredActivity>(); 16357 } 16358 removed.add(pa); 16359 } 16360 } 16361 if (removed != null) { 16362 for (int j=0; j<removed.size(); j++) { 16363 PreferredActivity pa = removed.get(j); 16364 pir.removeFilter(pa); 16365 } 16366 changed = true; 16367 } 16368 } 16369 return changed; 16370 } 16371 16372 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16373 private void clearIntentFilterVerificationsLPw(int userId) { 16374 final int packageCount = mPackages.size(); 16375 for (int i = 0; i < packageCount; i++) { 16376 PackageParser.Package pkg = mPackages.valueAt(i); 16377 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 16378 } 16379 } 16380 16381 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16382 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 16383 if (userId == UserHandle.USER_ALL) { 16384 if (mSettings.removeIntentFilterVerificationLPw(packageName, 16385 sUserManager.getUserIds())) { 16386 for (int oneUserId : sUserManager.getUserIds()) { 16387 scheduleWritePackageRestrictionsLocked(oneUserId); 16388 } 16389 } 16390 } else { 16391 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 16392 scheduleWritePackageRestrictionsLocked(userId); 16393 } 16394 } 16395 } 16396 16397 void clearDefaultBrowserIfNeeded(String packageName) { 16398 for (int oneUserId : sUserManager.getUserIds()) { 16399 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 16400 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 16401 if (packageName.equals(defaultBrowserPackageName)) { 16402 setDefaultBrowserPackageName(null, oneUserId); 16403 } 16404 } 16405 } 16406 16407 @Override 16408 public void resetApplicationPreferences(int userId) { 16409 mContext.enforceCallingOrSelfPermission( 16410 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16411 // writer 16412 synchronized (mPackages) { 16413 final long identity = Binder.clearCallingIdentity(); 16414 try { 16415 clearPackagePreferredActivitiesLPw(null, userId); 16416 mSettings.applyDefaultPreferredAppsLPw(this, userId); 16417 // TODO: We have to reset the default SMS and Phone. This requires 16418 // significant refactoring to keep all default apps in the package 16419 // manager (cleaner but more work) or have the services provide 16420 // callbacks to the package manager to request a default app reset. 16421 applyFactoryDefaultBrowserLPw(userId); 16422 clearIntentFilterVerificationsLPw(userId); 16423 primeDomainVerificationsLPw(userId); 16424 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 16425 scheduleWritePackageRestrictionsLocked(userId); 16426 } finally { 16427 Binder.restoreCallingIdentity(identity); 16428 } 16429 } 16430 } 16431 16432 @Override 16433 public int getPreferredActivities(List<IntentFilter> outFilters, 16434 List<ComponentName> outActivities, String packageName) { 16435 16436 int num = 0; 16437 final int userId = UserHandle.getCallingUserId(); 16438 // reader 16439 synchronized (mPackages) { 16440 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16441 if (pir != null) { 16442 final Iterator<PreferredActivity> it = pir.filterIterator(); 16443 while (it.hasNext()) { 16444 final PreferredActivity pa = it.next(); 16445 if (packageName == null 16446 || (pa.mPref.mComponent.getPackageName().equals(packageName) 16447 && pa.mPref.mAlways)) { 16448 if (outFilters != null) { 16449 outFilters.add(new IntentFilter(pa)); 16450 } 16451 if (outActivities != null) { 16452 outActivities.add(pa.mPref.mComponent); 16453 } 16454 } 16455 } 16456 } 16457 } 16458 16459 return num; 16460 } 16461 16462 @Override 16463 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 16464 int userId) { 16465 int callingUid = Binder.getCallingUid(); 16466 if (callingUid != Process.SYSTEM_UID) { 16467 throw new SecurityException( 16468 "addPersistentPreferredActivity can only be run by the system"); 16469 } 16470 if (filter.countActions() == 0) { 16471 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16472 return; 16473 } 16474 synchronized (mPackages) { 16475 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 16476 ":"); 16477 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16478 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 16479 new PersistentPreferredActivity(filter, activity)); 16480 scheduleWritePackageRestrictionsLocked(userId); 16481 } 16482 } 16483 16484 @Override 16485 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 16486 int callingUid = Binder.getCallingUid(); 16487 if (callingUid != Process.SYSTEM_UID) { 16488 throw new SecurityException( 16489 "clearPackagePersistentPreferredActivities can only be run by the system"); 16490 } 16491 ArrayList<PersistentPreferredActivity> removed = null; 16492 boolean changed = false; 16493 synchronized (mPackages) { 16494 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 16495 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 16496 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 16497 .valueAt(i); 16498 if (userId != thisUserId) { 16499 continue; 16500 } 16501 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 16502 while (it.hasNext()) { 16503 PersistentPreferredActivity ppa = it.next(); 16504 // Mark entry for removal only if it matches the package name. 16505 if (ppa.mComponent.getPackageName().equals(packageName)) { 16506 if (removed == null) { 16507 removed = new ArrayList<PersistentPreferredActivity>(); 16508 } 16509 removed.add(ppa); 16510 } 16511 } 16512 if (removed != null) { 16513 for (int j=0; j<removed.size(); j++) { 16514 PersistentPreferredActivity ppa = removed.get(j); 16515 ppir.removeFilter(ppa); 16516 } 16517 changed = true; 16518 } 16519 } 16520 16521 if (changed) { 16522 scheduleWritePackageRestrictionsLocked(userId); 16523 } 16524 } 16525 } 16526 16527 /** 16528 * Common machinery for picking apart a restored XML blob and passing 16529 * it to a caller-supplied functor to be applied to the running system. 16530 */ 16531 private void restoreFromXml(XmlPullParser parser, int userId, 16532 String expectedStartTag, BlobXmlRestorer functor) 16533 throws IOException, XmlPullParserException { 16534 int type; 16535 while ((type = parser.next()) != XmlPullParser.START_TAG 16536 && type != XmlPullParser.END_DOCUMENT) { 16537 } 16538 if (type != XmlPullParser.START_TAG) { 16539 // oops didn't find a start tag?! 16540 if (DEBUG_BACKUP) { 16541 Slog.e(TAG, "Didn't find start tag during restore"); 16542 } 16543 return; 16544 } 16545Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 16546 // this is supposed to be TAG_PREFERRED_BACKUP 16547 if (!expectedStartTag.equals(parser.getName())) { 16548 if (DEBUG_BACKUP) { 16549 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 16550 } 16551 return; 16552 } 16553 16554 // skip interfering stuff, then we're aligned with the backing implementation 16555 while ((type = parser.next()) == XmlPullParser.TEXT) { } 16556Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 16557 functor.apply(parser, userId); 16558 } 16559 16560 private interface BlobXmlRestorer { 16561 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 16562 } 16563 16564 /** 16565 * Non-Binder method, support for the backup/restore mechanism: write the 16566 * full set of preferred activities in its canonical XML format. Returns the 16567 * XML output as a byte array, or null if there is none. 16568 */ 16569 @Override 16570 public byte[] getPreferredActivityBackup(int userId) { 16571 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16572 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 16573 } 16574 16575 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16576 try { 16577 final XmlSerializer serializer = new FastXmlSerializer(); 16578 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16579 serializer.startDocument(null, true); 16580 serializer.startTag(null, TAG_PREFERRED_BACKUP); 16581 16582 synchronized (mPackages) { 16583 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 16584 } 16585 16586 serializer.endTag(null, TAG_PREFERRED_BACKUP); 16587 serializer.endDocument(); 16588 serializer.flush(); 16589 } catch (Exception e) { 16590 if (DEBUG_BACKUP) { 16591 Slog.e(TAG, "Unable to write preferred activities for backup", e); 16592 } 16593 return null; 16594 } 16595 16596 return dataStream.toByteArray(); 16597 } 16598 16599 @Override 16600 public void restorePreferredActivities(byte[] backup, int userId) { 16601 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16602 throw new SecurityException("Only the system may call restorePreferredActivities()"); 16603 } 16604 16605 try { 16606 final XmlPullParser parser = Xml.newPullParser(); 16607 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16608 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 16609 new BlobXmlRestorer() { 16610 @Override 16611 public void apply(XmlPullParser parser, int userId) 16612 throws XmlPullParserException, IOException { 16613 synchronized (mPackages) { 16614 mSettings.readPreferredActivitiesLPw(parser, userId); 16615 } 16616 } 16617 } ); 16618 } catch (Exception e) { 16619 if (DEBUG_BACKUP) { 16620 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16621 } 16622 } 16623 } 16624 16625 /** 16626 * Non-Binder method, support for the backup/restore mechanism: write the 16627 * default browser (etc) settings in its canonical XML format. Returns the default 16628 * browser XML representation as a byte array, or null if there is none. 16629 */ 16630 @Override 16631 public byte[] getDefaultAppsBackup(int userId) { 16632 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16633 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 16634 } 16635 16636 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16637 try { 16638 final XmlSerializer serializer = new FastXmlSerializer(); 16639 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16640 serializer.startDocument(null, true); 16641 serializer.startTag(null, TAG_DEFAULT_APPS); 16642 16643 synchronized (mPackages) { 16644 mSettings.writeDefaultAppsLPr(serializer, userId); 16645 } 16646 16647 serializer.endTag(null, TAG_DEFAULT_APPS); 16648 serializer.endDocument(); 16649 serializer.flush(); 16650 } catch (Exception e) { 16651 if (DEBUG_BACKUP) { 16652 Slog.e(TAG, "Unable to write default apps for backup", e); 16653 } 16654 return null; 16655 } 16656 16657 return dataStream.toByteArray(); 16658 } 16659 16660 @Override 16661 public void restoreDefaultApps(byte[] backup, int userId) { 16662 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16663 throw new SecurityException("Only the system may call restoreDefaultApps()"); 16664 } 16665 16666 try { 16667 final XmlPullParser parser = Xml.newPullParser(); 16668 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16669 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 16670 new BlobXmlRestorer() { 16671 @Override 16672 public void apply(XmlPullParser parser, int userId) 16673 throws XmlPullParserException, IOException { 16674 synchronized (mPackages) { 16675 mSettings.readDefaultAppsLPw(parser, userId); 16676 } 16677 } 16678 } ); 16679 } catch (Exception e) { 16680 if (DEBUG_BACKUP) { 16681 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 16682 } 16683 } 16684 } 16685 16686 @Override 16687 public byte[] getIntentFilterVerificationBackup(int userId) { 16688 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16689 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 16690 } 16691 16692 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16693 try { 16694 final XmlSerializer serializer = new FastXmlSerializer(); 16695 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16696 serializer.startDocument(null, true); 16697 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 16698 16699 synchronized (mPackages) { 16700 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 16701 } 16702 16703 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 16704 serializer.endDocument(); 16705 serializer.flush(); 16706 } catch (Exception e) { 16707 if (DEBUG_BACKUP) { 16708 Slog.e(TAG, "Unable to write default apps for backup", e); 16709 } 16710 return null; 16711 } 16712 16713 return dataStream.toByteArray(); 16714 } 16715 16716 @Override 16717 public void restoreIntentFilterVerification(byte[] backup, int userId) { 16718 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16719 throw new SecurityException("Only the system may call restorePreferredActivities()"); 16720 } 16721 16722 try { 16723 final XmlPullParser parser = Xml.newPullParser(); 16724 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16725 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 16726 new BlobXmlRestorer() { 16727 @Override 16728 public void apply(XmlPullParser parser, int userId) 16729 throws XmlPullParserException, IOException { 16730 synchronized (mPackages) { 16731 mSettings.readAllDomainVerificationsLPr(parser, userId); 16732 mSettings.writeLPr(); 16733 } 16734 } 16735 } ); 16736 } catch (Exception e) { 16737 if (DEBUG_BACKUP) { 16738 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16739 } 16740 } 16741 } 16742 16743 @Override 16744 public byte[] getPermissionGrantBackup(int userId) { 16745 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16746 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 16747 } 16748 16749 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16750 try { 16751 final XmlSerializer serializer = new FastXmlSerializer(); 16752 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16753 serializer.startDocument(null, true); 16754 serializer.startTag(null, TAG_PERMISSION_BACKUP); 16755 16756 synchronized (mPackages) { 16757 serializeRuntimePermissionGrantsLPr(serializer, userId); 16758 } 16759 16760 serializer.endTag(null, TAG_PERMISSION_BACKUP); 16761 serializer.endDocument(); 16762 serializer.flush(); 16763 } catch (Exception e) { 16764 if (DEBUG_BACKUP) { 16765 Slog.e(TAG, "Unable to write default apps for backup", e); 16766 } 16767 return null; 16768 } 16769 16770 return dataStream.toByteArray(); 16771 } 16772 16773 @Override 16774 public void restorePermissionGrants(byte[] backup, int userId) { 16775 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16776 throw new SecurityException("Only the system may call restorePermissionGrants()"); 16777 } 16778 16779 try { 16780 final XmlPullParser parser = Xml.newPullParser(); 16781 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16782 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 16783 new BlobXmlRestorer() { 16784 @Override 16785 public void apply(XmlPullParser parser, int userId) 16786 throws XmlPullParserException, IOException { 16787 synchronized (mPackages) { 16788 processRestoredPermissionGrantsLPr(parser, userId); 16789 } 16790 } 16791 } ); 16792 } catch (Exception e) { 16793 if (DEBUG_BACKUP) { 16794 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16795 } 16796 } 16797 } 16798 16799 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 16800 throws IOException { 16801 serializer.startTag(null, TAG_ALL_GRANTS); 16802 16803 final int N = mSettings.mPackages.size(); 16804 for (int i = 0; i < N; i++) { 16805 final PackageSetting ps = mSettings.mPackages.valueAt(i); 16806 boolean pkgGrantsKnown = false; 16807 16808 PermissionsState packagePerms = ps.getPermissionsState(); 16809 16810 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 16811 final int grantFlags = state.getFlags(); 16812 // only look at grants that are not system/policy fixed 16813 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 16814 final boolean isGranted = state.isGranted(); 16815 // And only back up the user-twiddled state bits 16816 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 16817 final String packageName = mSettings.mPackages.keyAt(i); 16818 if (!pkgGrantsKnown) { 16819 serializer.startTag(null, TAG_GRANT); 16820 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 16821 pkgGrantsKnown = true; 16822 } 16823 16824 final boolean userSet = 16825 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 16826 final boolean userFixed = 16827 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 16828 final boolean revoke = 16829 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 16830 16831 serializer.startTag(null, TAG_PERMISSION); 16832 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 16833 if (isGranted) { 16834 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 16835 } 16836 if (userSet) { 16837 serializer.attribute(null, ATTR_USER_SET, "true"); 16838 } 16839 if (userFixed) { 16840 serializer.attribute(null, ATTR_USER_FIXED, "true"); 16841 } 16842 if (revoke) { 16843 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 16844 } 16845 serializer.endTag(null, TAG_PERMISSION); 16846 } 16847 } 16848 } 16849 16850 if (pkgGrantsKnown) { 16851 serializer.endTag(null, TAG_GRANT); 16852 } 16853 } 16854 16855 serializer.endTag(null, TAG_ALL_GRANTS); 16856 } 16857 16858 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 16859 throws XmlPullParserException, IOException { 16860 String pkgName = null; 16861 int outerDepth = parser.getDepth(); 16862 int type; 16863 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 16864 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 16865 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 16866 continue; 16867 } 16868 16869 final String tagName = parser.getName(); 16870 if (tagName.equals(TAG_GRANT)) { 16871 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 16872 if (DEBUG_BACKUP) { 16873 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 16874 } 16875 } else if (tagName.equals(TAG_PERMISSION)) { 16876 16877 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 16878 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 16879 16880 int newFlagSet = 0; 16881 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 16882 newFlagSet |= FLAG_PERMISSION_USER_SET; 16883 } 16884 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 16885 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 16886 } 16887 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 16888 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 16889 } 16890 if (DEBUG_BACKUP) { 16891 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 16892 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 16893 } 16894 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16895 if (ps != null) { 16896 // Already installed so we apply the grant immediately 16897 if (DEBUG_BACKUP) { 16898 Slog.v(TAG, " + already installed; applying"); 16899 } 16900 PermissionsState perms = ps.getPermissionsState(); 16901 BasePermission bp = mSettings.mPermissions.get(permName); 16902 if (bp != null) { 16903 if (isGranted) { 16904 perms.grantRuntimePermission(bp, userId); 16905 } 16906 if (newFlagSet != 0) { 16907 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 16908 } 16909 } 16910 } else { 16911 // Need to wait for post-restore install to apply the grant 16912 if (DEBUG_BACKUP) { 16913 Slog.v(TAG, " - not yet installed; saving for later"); 16914 } 16915 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 16916 isGranted, newFlagSet, userId); 16917 } 16918 } else { 16919 PackageManagerService.reportSettingsProblem(Log.WARN, 16920 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 16921 XmlUtils.skipCurrentTag(parser); 16922 } 16923 } 16924 16925 scheduleWriteSettingsLocked(); 16926 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 16927 } 16928 16929 @Override 16930 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 16931 int sourceUserId, int targetUserId, int flags) { 16932 mContext.enforceCallingOrSelfPermission( 16933 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 16934 int callingUid = Binder.getCallingUid(); 16935 enforceOwnerRights(ownerPackage, callingUid); 16936 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 16937 if (intentFilter.countActions() == 0) { 16938 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 16939 return; 16940 } 16941 synchronized (mPackages) { 16942 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 16943 ownerPackage, targetUserId, flags); 16944 CrossProfileIntentResolver resolver = 16945 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 16946 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 16947 // We have all those whose filter is equal. Now checking if the rest is equal as well. 16948 if (existing != null) { 16949 int size = existing.size(); 16950 for (int i = 0; i < size; i++) { 16951 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 16952 return; 16953 } 16954 } 16955 } 16956 resolver.addFilter(newFilter); 16957 scheduleWritePackageRestrictionsLocked(sourceUserId); 16958 } 16959 } 16960 16961 @Override 16962 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 16963 mContext.enforceCallingOrSelfPermission( 16964 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 16965 int callingUid = Binder.getCallingUid(); 16966 enforceOwnerRights(ownerPackage, callingUid); 16967 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 16968 synchronized (mPackages) { 16969 CrossProfileIntentResolver resolver = 16970 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 16971 ArraySet<CrossProfileIntentFilter> set = 16972 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 16973 for (CrossProfileIntentFilter filter : set) { 16974 if (filter.getOwnerPackage().equals(ownerPackage)) { 16975 resolver.removeFilter(filter); 16976 } 16977 } 16978 scheduleWritePackageRestrictionsLocked(sourceUserId); 16979 } 16980 } 16981 16982 // Enforcing that callingUid is owning pkg on userId 16983 private void enforceOwnerRights(String pkg, int callingUid) { 16984 // The system owns everything. 16985 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 16986 return; 16987 } 16988 int callingUserId = UserHandle.getUserId(callingUid); 16989 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 16990 if (pi == null) { 16991 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 16992 + callingUserId); 16993 } 16994 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 16995 throw new SecurityException("Calling uid " + callingUid 16996 + " does not own package " + pkg); 16997 } 16998 } 16999 17000 @Override 17001 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 17002 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 17003 } 17004 17005 private Intent getHomeIntent() { 17006 Intent intent = new Intent(Intent.ACTION_MAIN); 17007 intent.addCategory(Intent.CATEGORY_HOME); 17008 return intent; 17009 } 17010 17011 private IntentFilter getHomeFilter() { 17012 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 17013 filter.addCategory(Intent.CATEGORY_HOME); 17014 filter.addCategory(Intent.CATEGORY_DEFAULT); 17015 return filter; 17016 } 17017 17018 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 17019 int userId) { 17020 Intent intent = getHomeIntent(); 17021 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 17022 PackageManager.GET_META_DATA, userId); 17023 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 17024 true, false, false, userId); 17025 17026 allHomeCandidates.clear(); 17027 if (list != null) { 17028 for (ResolveInfo ri : list) { 17029 allHomeCandidates.add(ri); 17030 } 17031 } 17032 return (preferred == null || preferred.activityInfo == null) 17033 ? null 17034 : new ComponentName(preferred.activityInfo.packageName, 17035 preferred.activityInfo.name); 17036 } 17037 17038 @Override 17039 public void setHomeActivity(ComponentName comp, int userId) { 17040 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 17041 getHomeActivitiesAsUser(homeActivities, userId); 17042 17043 boolean found = false; 17044 17045 final int size = homeActivities.size(); 17046 final ComponentName[] set = new ComponentName[size]; 17047 for (int i = 0; i < size; i++) { 17048 final ResolveInfo candidate = homeActivities.get(i); 17049 final ActivityInfo info = candidate.activityInfo; 17050 final ComponentName activityName = new ComponentName(info.packageName, info.name); 17051 set[i] = activityName; 17052 if (!found && activityName.equals(comp)) { 17053 found = true; 17054 } 17055 } 17056 if (!found) { 17057 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 17058 + userId); 17059 } 17060 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 17061 set, comp, userId); 17062 } 17063 17064 private @Nullable String getSetupWizardPackageName() { 17065 final Intent intent = new Intent(Intent.ACTION_MAIN); 17066 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 17067 17068 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 17069 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 17070 | MATCH_DISABLED_COMPONENTS, 17071 UserHandle.myUserId()); 17072 if (matches.size() == 1) { 17073 return matches.get(0).getComponentInfo().packageName; 17074 } else { 17075 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 17076 + ": matches=" + matches); 17077 return null; 17078 } 17079 } 17080 17081 @Override 17082 public void setApplicationEnabledSetting(String appPackageName, 17083 int newState, int flags, int userId, String callingPackage) { 17084 if (!sUserManager.exists(userId)) return; 17085 if (callingPackage == null) { 17086 callingPackage = Integer.toString(Binder.getCallingUid()); 17087 } 17088 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 17089 } 17090 17091 @Override 17092 public void setComponentEnabledSetting(ComponentName componentName, 17093 int newState, int flags, int userId) { 17094 if (!sUserManager.exists(userId)) return; 17095 setEnabledSetting(componentName.getPackageName(), 17096 componentName.getClassName(), newState, flags, userId, null); 17097 } 17098 17099 private void setEnabledSetting(final String packageName, String className, int newState, 17100 final int flags, int userId, String callingPackage) { 17101 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 17102 || newState == COMPONENT_ENABLED_STATE_ENABLED 17103 || newState == COMPONENT_ENABLED_STATE_DISABLED 17104 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17105 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 17106 throw new IllegalArgumentException("Invalid new component state: " 17107 + newState); 17108 } 17109 PackageSetting pkgSetting; 17110 final int uid = Binder.getCallingUid(); 17111 final int permission; 17112 if (uid == Process.SYSTEM_UID) { 17113 permission = PackageManager.PERMISSION_GRANTED; 17114 } else { 17115 permission = mContext.checkCallingOrSelfPermission( 17116 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17117 } 17118 enforceCrossUserPermission(uid, userId, 17119 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 17120 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17121 boolean sendNow = false; 17122 boolean isApp = (className == null); 17123 String componentName = isApp ? packageName : className; 17124 int packageUid = -1; 17125 ArrayList<String> components; 17126 17127 // writer 17128 synchronized (mPackages) { 17129 pkgSetting = mSettings.mPackages.get(packageName); 17130 if (pkgSetting == null) { 17131 if (className == null) { 17132 throw new IllegalArgumentException("Unknown package: " + packageName); 17133 } 17134 throw new IllegalArgumentException( 17135 "Unknown component: " + packageName + "/" + className); 17136 } 17137 // Allow root and verify that userId is not being specified by a different user 17138 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 17139 throw new SecurityException( 17140 "Permission Denial: attempt to change component state from pid=" 17141 + Binder.getCallingPid() 17142 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 17143 } 17144 if (className == null) { 17145 // We're dealing with an application/package level state change 17146 if (pkgSetting.getEnabled(userId) == newState) { 17147 // Nothing to do 17148 return; 17149 } 17150 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 17151 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 17152 // Don't care about who enables an app. 17153 callingPackage = null; 17154 } 17155 pkgSetting.setEnabled(newState, userId, callingPackage); 17156 // pkgSetting.pkg.mSetEnabled = newState; 17157 } else { 17158 // We're dealing with a component level state change 17159 // First, verify that this is a valid class name. 17160 PackageParser.Package pkg = pkgSetting.pkg; 17161 if (pkg == null || !pkg.hasComponentClassName(className)) { 17162 if (pkg != null && 17163 pkg.applicationInfo.targetSdkVersion >= 17164 Build.VERSION_CODES.JELLY_BEAN) { 17165 throw new IllegalArgumentException("Component class " + className 17166 + " does not exist in " + packageName); 17167 } else { 17168 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 17169 + className + " does not exist in " + packageName); 17170 } 17171 } 17172 switch (newState) { 17173 case COMPONENT_ENABLED_STATE_ENABLED: 17174 if (!pkgSetting.enableComponentLPw(className, userId)) { 17175 return; 17176 } 17177 break; 17178 case COMPONENT_ENABLED_STATE_DISABLED: 17179 if (!pkgSetting.disableComponentLPw(className, userId)) { 17180 return; 17181 } 17182 break; 17183 case COMPONENT_ENABLED_STATE_DEFAULT: 17184 if (!pkgSetting.restoreComponentLPw(className, userId)) { 17185 return; 17186 } 17187 break; 17188 default: 17189 Slog.e(TAG, "Invalid new component state: " + newState); 17190 return; 17191 } 17192 } 17193 scheduleWritePackageRestrictionsLocked(userId); 17194 components = mPendingBroadcasts.get(userId, packageName); 17195 final boolean newPackage = components == null; 17196 if (newPackage) { 17197 components = new ArrayList<String>(); 17198 } 17199 if (!components.contains(componentName)) { 17200 components.add(componentName); 17201 } 17202 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 17203 sendNow = true; 17204 // Purge entry from pending broadcast list if another one exists already 17205 // since we are sending one right away. 17206 mPendingBroadcasts.remove(userId, packageName); 17207 } else { 17208 if (newPackage) { 17209 mPendingBroadcasts.put(userId, packageName, components); 17210 } 17211 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 17212 // Schedule a message 17213 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 17214 } 17215 } 17216 } 17217 17218 long callingId = Binder.clearCallingIdentity(); 17219 try { 17220 if (sendNow) { 17221 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 17222 sendPackageChangedBroadcast(packageName, 17223 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 17224 } 17225 } finally { 17226 Binder.restoreCallingIdentity(callingId); 17227 } 17228 } 17229 17230 @Override 17231 public void flushPackageRestrictionsAsUser(int userId) { 17232 if (!sUserManager.exists(userId)) { 17233 return; 17234 } 17235 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 17236 false /* checkShell */, "flushPackageRestrictions"); 17237 synchronized (mPackages) { 17238 mSettings.writePackageRestrictionsLPr(userId); 17239 mDirtyUsers.remove(userId); 17240 if (mDirtyUsers.isEmpty()) { 17241 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 17242 } 17243 } 17244 } 17245 17246 private void sendPackageChangedBroadcast(String packageName, 17247 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 17248 if (DEBUG_INSTALL) 17249 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 17250 + componentNames); 17251 Bundle extras = new Bundle(4); 17252 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 17253 String nameList[] = new String[componentNames.size()]; 17254 componentNames.toArray(nameList); 17255 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 17256 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 17257 extras.putInt(Intent.EXTRA_UID, packageUid); 17258 // If this is not reporting a change of the overall package, then only send it 17259 // to registered receivers. We don't want to launch a swath of apps for every 17260 // little component state change. 17261 final int flags = !componentNames.contains(packageName) 17262 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 17263 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 17264 new int[] {UserHandle.getUserId(packageUid)}); 17265 } 17266 17267 @Override 17268 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 17269 if (!sUserManager.exists(userId)) return; 17270 final int uid = Binder.getCallingUid(); 17271 final int permission = mContext.checkCallingOrSelfPermission( 17272 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17273 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17274 enforceCrossUserPermission(uid, userId, 17275 true /* requireFullPermission */, true /* checkShell */, "stop package"); 17276 // writer 17277 synchronized (mPackages) { 17278 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 17279 allowedByPermission, uid, userId)) { 17280 scheduleWritePackageRestrictionsLocked(userId); 17281 } 17282 } 17283 } 17284 17285 @Override 17286 public String getInstallerPackageName(String packageName) { 17287 // reader 17288 synchronized (mPackages) { 17289 return mSettings.getInstallerPackageNameLPr(packageName); 17290 } 17291 } 17292 17293 @Override 17294 public int getApplicationEnabledSetting(String packageName, int userId) { 17295 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17296 int uid = Binder.getCallingUid(); 17297 enforceCrossUserPermission(uid, userId, 17298 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 17299 // reader 17300 synchronized (mPackages) { 17301 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 17302 } 17303 } 17304 17305 @Override 17306 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 17307 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17308 int uid = Binder.getCallingUid(); 17309 enforceCrossUserPermission(uid, userId, 17310 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 17311 // reader 17312 synchronized (mPackages) { 17313 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 17314 } 17315 } 17316 17317 @Override 17318 public void enterSafeMode() { 17319 enforceSystemOrRoot("Only the system can request entering safe mode"); 17320 17321 if (!mSystemReady) { 17322 mSafeMode = true; 17323 } 17324 } 17325 17326 @Override 17327 public void systemReady() { 17328 mSystemReady = true; 17329 17330 // Read the compatibilty setting when the system is ready. 17331 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 17332 mContext.getContentResolver(), 17333 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 17334 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 17335 if (DEBUG_SETTINGS) { 17336 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 17337 } 17338 17339 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 17340 17341 synchronized (mPackages) { 17342 // Verify that all of the preferred activity components actually 17343 // exist. It is possible for applications to be updated and at 17344 // that point remove a previously declared activity component that 17345 // had been set as a preferred activity. We try to clean this up 17346 // the next time we encounter that preferred activity, but it is 17347 // possible for the user flow to never be able to return to that 17348 // situation so here we do a sanity check to make sure we haven't 17349 // left any junk around. 17350 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 17351 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17352 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17353 removed.clear(); 17354 for (PreferredActivity pa : pir.filterSet()) { 17355 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 17356 removed.add(pa); 17357 } 17358 } 17359 if (removed.size() > 0) { 17360 for (int r=0; r<removed.size(); r++) { 17361 PreferredActivity pa = removed.get(r); 17362 Slog.w(TAG, "Removing dangling preferred activity: " 17363 + pa.mPref.mComponent); 17364 pir.removeFilter(pa); 17365 } 17366 mSettings.writePackageRestrictionsLPr( 17367 mSettings.mPreferredActivities.keyAt(i)); 17368 } 17369 } 17370 17371 for (int userId : UserManagerService.getInstance().getUserIds()) { 17372 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 17373 grantPermissionsUserIds = ArrayUtils.appendInt( 17374 grantPermissionsUserIds, userId); 17375 } 17376 } 17377 } 17378 sUserManager.systemReady(); 17379 17380 // If we upgraded grant all default permissions before kicking off. 17381 for (int userId : grantPermissionsUserIds) { 17382 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 17383 } 17384 17385 // Kick off any messages waiting for system ready 17386 if (mPostSystemReadyMessages != null) { 17387 for (Message msg : mPostSystemReadyMessages) { 17388 msg.sendToTarget(); 17389 } 17390 mPostSystemReadyMessages = null; 17391 } 17392 17393 // Watch for external volumes that come and go over time 17394 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17395 storage.registerListener(mStorageListener); 17396 17397 mInstallerService.systemReady(); 17398 mPackageDexOptimizer.systemReady(); 17399 17400 MountServiceInternal mountServiceInternal = LocalServices.getService( 17401 MountServiceInternal.class); 17402 mountServiceInternal.addExternalStoragePolicy( 17403 new MountServiceInternal.ExternalStorageMountPolicy() { 17404 @Override 17405 public int getMountMode(int uid, String packageName) { 17406 if (Process.isIsolated(uid)) { 17407 return Zygote.MOUNT_EXTERNAL_NONE; 17408 } 17409 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 17410 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17411 } 17412 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17413 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17414 } 17415 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17416 return Zygote.MOUNT_EXTERNAL_READ; 17417 } 17418 return Zygote.MOUNT_EXTERNAL_WRITE; 17419 } 17420 17421 @Override 17422 public boolean hasExternalStorage(int uid, String packageName) { 17423 return true; 17424 } 17425 }); 17426 17427 // Now that we're mostly running, clean up stale users and apps 17428 reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 17429 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 17430 } 17431 17432 @Override 17433 public boolean isSafeMode() { 17434 return mSafeMode; 17435 } 17436 17437 @Override 17438 public boolean hasSystemUidErrors() { 17439 return mHasSystemUidErrors; 17440 } 17441 17442 static String arrayToString(int[] array) { 17443 StringBuffer buf = new StringBuffer(128); 17444 buf.append('['); 17445 if (array != null) { 17446 for (int i=0; i<array.length; i++) { 17447 if (i > 0) buf.append(", "); 17448 buf.append(array[i]); 17449 } 17450 } 17451 buf.append(']'); 17452 return buf.toString(); 17453 } 17454 17455 static class DumpState { 17456 public static final int DUMP_LIBS = 1 << 0; 17457 public static final int DUMP_FEATURES = 1 << 1; 17458 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 17459 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 17460 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 17461 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 17462 public static final int DUMP_PERMISSIONS = 1 << 6; 17463 public static final int DUMP_PACKAGES = 1 << 7; 17464 public static final int DUMP_SHARED_USERS = 1 << 8; 17465 public static final int DUMP_MESSAGES = 1 << 9; 17466 public static final int DUMP_PROVIDERS = 1 << 10; 17467 public static final int DUMP_VERIFIERS = 1 << 11; 17468 public static final int DUMP_PREFERRED = 1 << 12; 17469 public static final int DUMP_PREFERRED_XML = 1 << 13; 17470 public static final int DUMP_KEYSETS = 1 << 14; 17471 public static final int DUMP_VERSION = 1 << 15; 17472 public static final int DUMP_INSTALLS = 1 << 16; 17473 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 17474 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 17475 public static final int DUMP_FROZEN = 1 << 19; 17476 17477 public static final int OPTION_SHOW_FILTERS = 1 << 0; 17478 17479 private int mTypes; 17480 17481 private int mOptions; 17482 17483 private boolean mTitlePrinted; 17484 17485 private SharedUserSetting mSharedUser; 17486 17487 public boolean isDumping(int type) { 17488 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 17489 return true; 17490 } 17491 17492 return (mTypes & type) != 0; 17493 } 17494 17495 public void setDump(int type) { 17496 mTypes |= type; 17497 } 17498 17499 public boolean isOptionEnabled(int option) { 17500 return (mOptions & option) != 0; 17501 } 17502 17503 public void setOptionEnabled(int option) { 17504 mOptions |= option; 17505 } 17506 17507 public boolean onTitlePrinted() { 17508 final boolean printed = mTitlePrinted; 17509 mTitlePrinted = true; 17510 return printed; 17511 } 17512 17513 public boolean getTitlePrinted() { 17514 return mTitlePrinted; 17515 } 17516 17517 public void setTitlePrinted(boolean enabled) { 17518 mTitlePrinted = enabled; 17519 } 17520 17521 public SharedUserSetting getSharedUser() { 17522 return mSharedUser; 17523 } 17524 17525 public void setSharedUser(SharedUserSetting user) { 17526 mSharedUser = user; 17527 } 17528 } 17529 17530 @Override 17531 public void onShellCommand(FileDescriptor in, FileDescriptor out, 17532 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 17533 (new PackageManagerShellCommand(this)).exec( 17534 this, in, out, err, args, resultReceiver); 17535 } 17536 17537 @Override 17538 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 17539 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 17540 != PackageManager.PERMISSION_GRANTED) { 17541 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 17542 + Binder.getCallingPid() 17543 + ", uid=" + Binder.getCallingUid() 17544 + " without permission " 17545 + android.Manifest.permission.DUMP); 17546 return; 17547 } 17548 17549 DumpState dumpState = new DumpState(); 17550 boolean fullPreferred = false; 17551 boolean checkin = false; 17552 17553 String packageName = null; 17554 ArraySet<String> permissionNames = null; 17555 17556 int opti = 0; 17557 while (opti < args.length) { 17558 String opt = args[opti]; 17559 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 17560 break; 17561 } 17562 opti++; 17563 17564 if ("-a".equals(opt)) { 17565 // Right now we only know how to print all. 17566 } else if ("-h".equals(opt)) { 17567 pw.println("Package manager dump options:"); 17568 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 17569 pw.println(" --checkin: dump for a checkin"); 17570 pw.println(" -f: print details of intent filters"); 17571 pw.println(" -h: print this help"); 17572 pw.println(" cmd may be one of:"); 17573 pw.println(" l[ibraries]: list known shared libraries"); 17574 pw.println(" f[eatures]: list device features"); 17575 pw.println(" k[eysets]: print known keysets"); 17576 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 17577 pw.println(" perm[issions]: dump permissions"); 17578 pw.println(" permission [name ...]: dump declaration and use of given permission"); 17579 pw.println(" pref[erred]: print preferred package settings"); 17580 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 17581 pw.println(" prov[iders]: dump content providers"); 17582 pw.println(" p[ackages]: dump installed packages"); 17583 pw.println(" s[hared-users]: dump shared user IDs"); 17584 pw.println(" m[essages]: print collected runtime messages"); 17585 pw.println(" v[erifiers]: print package verifier info"); 17586 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 17587 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 17588 pw.println(" version: print database version info"); 17589 pw.println(" write: write current settings now"); 17590 pw.println(" installs: details about install sessions"); 17591 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 17592 pw.println(" <package.name>: info about given package"); 17593 return; 17594 } else if ("--checkin".equals(opt)) { 17595 checkin = true; 17596 } else if ("-f".equals(opt)) { 17597 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 17598 } else { 17599 pw.println("Unknown argument: " + opt + "; use -h for help"); 17600 } 17601 } 17602 17603 // Is the caller requesting to dump a particular piece of data? 17604 if (opti < args.length) { 17605 String cmd = args[opti]; 17606 opti++; 17607 // Is this a package name? 17608 if ("android".equals(cmd) || cmd.contains(".")) { 17609 packageName = cmd; 17610 // When dumping a single package, we always dump all of its 17611 // filter information since the amount of data will be reasonable. 17612 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 17613 } else if ("check-permission".equals(cmd)) { 17614 if (opti >= args.length) { 17615 pw.println("Error: check-permission missing permission argument"); 17616 return; 17617 } 17618 String perm = args[opti]; 17619 opti++; 17620 if (opti >= args.length) { 17621 pw.println("Error: check-permission missing package argument"); 17622 return; 17623 } 17624 String pkg = args[opti]; 17625 opti++; 17626 int user = UserHandle.getUserId(Binder.getCallingUid()); 17627 if (opti < args.length) { 17628 try { 17629 user = Integer.parseInt(args[opti]); 17630 } catch (NumberFormatException e) { 17631 pw.println("Error: check-permission user argument is not a number: " 17632 + args[opti]); 17633 return; 17634 } 17635 } 17636 pw.println(checkPermission(perm, pkg, user)); 17637 return; 17638 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 17639 dumpState.setDump(DumpState.DUMP_LIBS); 17640 } else if ("f".equals(cmd) || "features".equals(cmd)) { 17641 dumpState.setDump(DumpState.DUMP_FEATURES); 17642 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 17643 if (opti >= args.length) { 17644 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 17645 | DumpState.DUMP_SERVICE_RESOLVERS 17646 | DumpState.DUMP_RECEIVER_RESOLVERS 17647 | DumpState.DUMP_CONTENT_RESOLVERS); 17648 } else { 17649 while (opti < args.length) { 17650 String name = args[opti]; 17651 if ("a".equals(name) || "activity".equals(name)) { 17652 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 17653 } else if ("s".equals(name) || "service".equals(name)) { 17654 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 17655 } else if ("r".equals(name) || "receiver".equals(name)) { 17656 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 17657 } else if ("c".equals(name) || "content".equals(name)) { 17658 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 17659 } else { 17660 pw.println("Error: unknown resolver table type: " + name); 17661 return; 17662 } 17663 opti++; 17664 } 17665 } 17666 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 17667 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 17668 } else if ("permission".equals(cmd)) { 17669 if (opti >= args.length) { 17670 pw.println("Error: permission requires permission name"); 17671 return; 17672 } 17673 permissionNames = new ArraySet<>(); 17674 while (opti < args.length) { 17675 permissionNames.add(args[opti]); 17676 opti++; 17677 } 17678 dumpState.setDump(DumpState.DUMP_PERMISSIONS 17679 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 17680 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 17681 dumpState.setDump(DumpState.DUMP_PREFERRED); 17682 } else if ("preferred-xml".equals(cmd)) { 17683 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 17684 if (opti < args.length && "--full".equals(args[opti])) { 17685 fullPreferred = true; 17686 opti++; 17687 } 17688 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 17689 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 17690 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 17691 dumpState.setDump(DumpState.DUMP_PACKAGES); 17692 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 17693 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 17694 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 17695 dumpState.setDump(DumpState.DUMP_PROVIDERS); 17696 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 17697 dumpState.setDump(DumpState.DUMP_MESSAGES); 17698 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 17699 dumpState.setDump(DumpState.DUMP_VERIFIERS); 17700 } else if ("i".equals(cmd) || "ifv".equals(cmd) 17701 || "intent-filter-verifiers".equals(cmd)) { 17702 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 17703 } else if ("version".equals(cmd)) { 17704 dumpState.setDump(DumpState.DUMP_VERSION); 17705 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 17706 dumpState.setDump(DumpState.DUMP_KEYSETS); 17707 } else if ("installs".equals(cmd)) { 17708 dumpState.setDump(DumpState.DUMP_INSTALLS); 17709 } else if ("frozen".equals(cmd)) { 17710 dumpState.setDump(DumpState.DUMP_FROZEN); 17711 } else if ("write".equals(cmd)) { 17712 synchronized (mPackages) { 17713 mSettings.writeLPr(); 17714 pw.println("Settings written."); 17715 return; 17716 } 17717 } 17718 } 17719 17720 if (checkin) { 17721 pw.println("vers,1"); 17722 } 17723 17724 // reader 17725 synchronized (mPackages) { 17726 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 17727 if (!checkin) { 17728 if (dumpState.onTitlePrinted()) 17729 pw.println(); 17730 pw.println("Database versions:"); 17731 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 17732 } 17733 } 17734 17735 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 17736 if (!checkin) { 17737 if (dumpState.onTitlePrinted()) 17738 pw.println(); 17739 pw.println("Verifiers:"); 17740 pw.print(" Required: "); 17741 pw.print(mRequiredVerifierPackage); 17742 pw.print(" (uid="); 17743 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 17744 UserHandle.USER_SYSTEM)); 17745 pw.println(")"); 17746 } else if (mRequiredVerifierPackage != null) { 17747 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 17748 pw.print(","); 17749 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 17750 UserHandle.USER_SYSTEM)); 17751 } 17752 } 17753 17754 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 17755 packageName == null) { 17756 if (mIntentFilterVerifierComponent != null) { 17757 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 17758 if (!checkin) { 17759 if (dumpState.onTitlePrinted()) 17760 pw.println(); 17761 pw.println("Intent Filter Verifier:"); 17762 pw.print(" Using: "); 17763 pw.print(verifierPackageName); 17764 pw.print(" (uid="); 17765 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 17766 UserHandle.USER_SYSTEM)); 17767 pw.println(")"); 17768 } else if (verifierPackageName != null) { 17769 pw.print("ifv,"); pw.print(verifierPackageName); 17770 pw.print(","); 17771 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 17772 UserHandle.USER_SYSTEM)); 17773 } 17774 } else { 17775 pw.println(); 17776 pw.println("No Intent Filter Verifier available!"); 17777 } 17778 } 17779 17780 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 17781 boolean printedHeader = false; 17782 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 17783 while (it.hasNext()) { 17784 String name = it.next(); 17785 SharedLibraryEntry ent = mSharedLibraries.get(name); 17786 if (!checkin) { 17787 if (!printedHeader) { 17788 if (dumpState.onTitlePrinted()) 17789 pw.println(); 17790 pw.println("Libraries:"); 17791 printedHeader = true; 17792 } 17793 pw.print(" "); 17794 } else { 17795 pw.print("lib,"); 17796 } 17797 pw.print(name); 17798 if (!checkin) { 17799 pw.print(" -> "); 17800 } 17801 if (ent.path != null) { 17802 if (!checkin) { 17803 pw.print("(jar) "); 17804 pw.print(ent.path); 17805 } else { 17806 pw.print(",jar,"); 17807 pw.print(ent.path); 17808 } 17809 } else { 17810 if (!checkin) { 17811 pw.print("(apk) "); 17812 pw.print(ent.apk); 17813 } else { 17814 pw.print(",apk,"); 17815 pw.print(ent.apk); 17816 } 17817 } 17818 pw.println(); 17819 } 17820 } 17821 17822 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 17823 if (dumpState.onTitlePrinted()) 17824 pw.println(); 17825 if (!checkin) { 17826 pw.println("Features:"); 17827 } 17828 17829 for (FeatureInfo feat : mAvailableFeatures.values()) { 17830 if (checkin) { 17831 pw.print("feat,"); 17832 pw.print(feat.name); 17833 pw.print(","); 17834 pw.println(feat.version); 17835 } else { 17836 pw.print(" "); 17837 pw.print(feat.name); 17838 if (feat.version > 0) { 17839 pw.print(" version="); 17840 pw.print(feat.version); 17841 } 17842 pw.println(); 17843 } 17844 } 17845 } 17846 17847 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 17848 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 17849 : "Activity Resolver Table:", " ", packageName, 17850 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17851 dumpState.setTitlePrinted(true); 17852 } 17853 } 17854 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 17855 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 17856 : "Receiver Resolver Table:", " ", packageName, 17857 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17858 dumpState.setTitlePrinted(true); 17859 } 17860 } 17861 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 17862 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 17863 : "Service Resolver Table:", " ", packageName, 17864 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17865 dumpState.setTitlePrinted(true); 17866 } 17867 } 17868 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 17869 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 17870 : "Provider Resolver Table:", " ", packageName, 17871 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17872 dumpState.setTitlePrinted(true); 17873 } 17874 } 17875 17876 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 17877 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17878 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17879 int user = mSettings.mPreferredActivities.keyAt(i); 17880 if (pir.dump(pw, 17881 dumpState.getTitlePrinted() 17882 ? "\nPreferred Activities User " + user + ":" 17883 : "Preferred Activities User " + user + ":", " ", 17884 packageName, true, false)) { 17885 dumpState.setTitlePrinted(true); 17886 } 17887 } 17888 } 17889 17890 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 17891 pw.flush(); 17892 FileOutputStream fout = new FileOutputStream(fd); 17893 BufferedOutputStream str = new BufferedOutputStream(fout); 17894 XmlSerializer serializer = new FastXmlSerializer(); 17895 try { 17896 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 17897 serializer.startDocument(null, true); 17898 serializer.setFeature( 17899 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 17900 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 17901 serializer.endDocument(); 17902 serializer.flush(); 17903 } catch (IllegalArgumentException e) { 17904 pw.println("Failed writing: " + e); 17905 } catch (IllegalStateException e) { 17906 pw.println("Failed writing: " + e); 17907 } catch (IOException e) { 17908 pw.println("Failed writing: " + e); 17909 } 17910 } 17911 17912 if (!checkin 17913 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 17914 && packageName == null) { 17915 pw.println(); 17916 int count = mSettings.mPackages.size(); 17917 if (count == 0) { 17918 pw.println("No applications!"); 17919 pw.println(); 17920 } else { 17921 final String prefix = " "; 17922 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 17923 if (allPackageSettings.size() == 0) { 17924 pw.println("No domain preferred apps!"); 17925 pw.println(); 17926 } else { 17927 pw.println("App verification status:"); 17928 pw.println(); 17929 count = 0; 17930 for (PackageSetting ps : allPackageSettings) { 17931 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 17932 if (ivi == null || ivi.getPackageName() == null) continue; 17933 pw.println(prefix + "Package: " + ivi.getPackageName()); 17934 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 17935 pw.println(prefix + "Status: " + ivi.getStatusString()); 17936 pw.println(); 17937 count++; 17938 } 17939 if (count == 0) { 17940 pw.println(prefix + "No app verification established."); 17941 pw.println(); 17942 } 17943 for (int userId : sUserManager.getUserIds()) { 17944 pw.println("App linkages for user " + userId + ":"); 17945 pw.println(); 17946 count = 0; 17947 for (PackageSetting ps : allPackageSettings) { 17948 final long status = ps.getDomainVerificationStatusForUser(userId); 17949 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 17950 continue; 17951 } 17952 pw.println(prefix + "Package: " + ps.name); 17953 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 17954 String statusStr = IntentFilterVerificationInfo. 17955 getStatusStringFromValue(status); 17956 pw.println(prefix + "Status: " + statusStr); 17957 pw.println(); 17958 count++; 17959 } 17960 if (count == 0) { 17961 pw.println(prefix + "No configured app linkages."); 17962 pw.println(); 17963 } 17964 } 17965 } 17966 } 17967 } 17968 17969 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 17970 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 17971 if (packageName == null && permissionNames == null) { 17972 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 17973 if (iperm == 0) { 17974 if (dumpState.onTitlePrinted()) 17975 pw.println(); 17976 pw.println("AppOp Permissions:"); 17977 } 17978 pw.print(" AppOp Permission "); 17979 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 17980 pw.println(":"); 17981 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 17982 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 17983 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 17984 } 17985 } 17986 } 17987 } 17988 17989 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 17990 boolean printedSomething = false; 17991 for (PackageParser.Provider p : mProviders.mProviders.values()) { 17992 if (packageName != null && !packageName.equals(p.info.packageName)) { 17993 continue; 17994 } 17995 if (!printedSomething) { 17996 if (dumpState.onTitlePrinted()) 17997 pw.println(); 17998 pw.println("Registered ContentProviders:"); 17999 printedSomething = true; 18000 } 18001 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 18002 pw.print(" "); pw.println(p.toString()); 18003 } 18004 printedSomething = false; 18005 for (Map.Entry<String, PackageParser.Provider> entry : 18006 mProvidersByAuthority.entrySet()) { 18007 PackageParser.Provider p = entry.getValue(); 18008 if (packageName != null && !packageName.equals(p.info.packageName)) { 18009 continue; 18010 } 18011 if (!printedSomething) { 18012 if (dumpState.onTitlePrinted()) 18013 pw.println(); 18014 pw.println("ContentProvider Authorities:"); 18015 printedSomething = true; 18016 } 18017 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 18018 pw.print(" "); pw.println(p.toString()); 18019 if (p.info != null && p.info.applicationInfo != null) { 18020 final String appInfo = p.info.applicationInfo.toString(); 18021 pw.print(" applicationInfo="); pw.println(appInfo); 18022 } 18023 } 18024 } 18025 18026 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 18027 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 18028 } 18029 18030 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 18031 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 18032 } 18033 18034 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 18035 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 18036 } 18037 18038 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 18039 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 18040 } 18041 18042 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 18043 // XXX should handle packageName != null by dumping only install data that 18044 // the given package is involved with. 18045 if (dumpState.onTitlePrinted()) pw.println(); 18046 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 18047 } 18048 18049 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 18050 // XXX should handle packageName != null by dumping only install data that 18051 // the given package is involved with. 18052 if (dumpState.onTitlePrinted()) pw.println(); 18053 18054 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18055 ipw.println(); 18056 ipw.println("Frozen packages:"); 18057 ipw.increaseIndent(); 18058 if (mFrozenPackages.size() == 0) { 18059 ipw.println("(none)"); 18060 } else { 18061 for (int i = 0; i < mFrozenPackages.size(); i++) { 18062 ipw.println(mFrozenPackages.valueAt(i)); 18063 } 18064 } 18065 ipw.decreaseIndent(); 18066 } 18067 18068 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 18069 if (dumpState.onTitlePrinted()) pw.println(); 18070 mSettings.dumpReadMessagesLPr(pw, dumpState); 18071 18072 pw.println(); 18073 pw.println("Package warning messages:"); 18074 BufferedReader in = null; 18075 String line = null; 18076 try { 18077 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18078 while ((line = in.readLine()) != null) { 18079 if (line.contains("ignored: updated version")) continue; 18080 pw.println(line); 18081 } 18082 } catch (IOException ignored) { 18083 } finally { 18084 IoUtils.closeQuietly(in); 18085 } 18086 } 18087 18088 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 18089 BufferedReader in = null; 18090 String line = null; 18091 try { 18092 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18093 while ((line = in.readLine()) != null) { 18094 if (line.contains("ignored: updated version")) continue; 18095 pw.print("msg,"); 18096 pw.println(line); 18097 } 18098 } catch (IOException ignored) { 18099 } finally { 18100 IoUtils.closeQuietly(in); 18101 } 18102 } 18103 } 18104 } 18105 18106 private String dumpDomainString(String packageName) { 18107 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 18108 .getList(); 18109 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 18110 18111 ArraySet<String> result = new ArraySet<>(); 18112 if (iviList.size() > 0) { 18113 for (IntentFilterVerificationInfo ivi : iviList) { 18114 for (String host : ivi.getDomains()) { 18115 result.add(host); 18116 } 18117 } 18118 } 18119 if (filters != null && filters.size() > 0) { 18120 for (IntentFilter filter : filters) { 18121 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 18122 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 18123 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 18124 result.addAll(filter.getHostsList()); 18125 } 18126 } 18127 } 18128 18129 StringBuilder sb = new StringBuilder(result.size() * 16); 18130 for (String domain : result) { 18131 if (sb.length() > 0) sb.append(" "); 18132 sb.append(domain); 18133 } 18134 return sb.toString(); 18135 } 18136 18137 // ------- apps on sdcard specific code ------- 18138 static final boolean DEBUG_SD_INSTALL = false; 18139 18140 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 18141 18142 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 18143 18144 private boolean mMediaMounted = false; 18145 18146 static String getEncryptKey() { 18147 try { 18148 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 18149 SD_ENCRYPTION_KEYSTORE_NAME); 18150 if (sdEncKey == null) { 18151 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 18152 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 18153 if (sdEncKey == null) { 18154 Slog.e(TAG, "Failed to create encryption keys"); 18155 return null; 18156 } 18157 } 18158 return sdEncKey; 18159 } catch (NoSuchAlgorithmException nsae) { 18160 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 18161 return null; 18162 } catch (IOException ioe) { 18163 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 18164 return null; 18165 } 18166 } 18167 18168 /* 18169 * Update media status on PackageManager. 18170 */ 18171 @Override 18172 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 18173 int callingUid = Binder.getCallingUid(); 18174 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 18175 throw new SecurityException("Media status can only be updated by the system"); 18176 } 18177 // reader; this apparently protects mMediaMounted, but should probably 18178 // be a different lock in that case. 18179 synchronized (mPackages) { 18180 Log.i(TAG, "Updating external media status from " 18181 + (mMediaMounted ? "mounted" : "unmounted") + " to " 18182 + (mediaStatus ? "mounted" : "unmounted")); 18183 if (DEBUG_SD_INSTALL) 18184 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 18185 + ", mMediaMounted=" + mMediaMounted); 18186 if (mediaStatus == mMediaMounted) { 18187 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 18188 : 0, -1); 18189 mHandler.sendMessage(msg); 18190 return; 18191 } 18192 mMediaMounted = mediaStatus; 18193 } 18194 // Queue up an async operation since the package installation may take a 18195 // little while. 18196 mHandler.post(new Runnable() { 18197 public void run() { 18198 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 18199 } 18200 }); 18201 } 18202 18203 /** 18204 * Called by MountService when the initial ASECs to scan are available. 18205 * Should block until all the ASEC containers are finished being scanned. 18206 */ 18207 public void scanAvailableAsecs() { 18208 updateExternalMediaStatusInner(true, false, false); 18209 } 18210 18211 /* 18212 * Collect information of applications on external media, map them against 18213 * existing containers and update information based on current mount status. 18214 * Please note that we always have to report status if reportStatus has been 18215 * set to true especially when unloading packages. 18216 */ 18217 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 18218 boolean externalStorage) { 18219 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 18220 int[] uidArr = EmptyArray.INT; 18221 18222 final String[] list = PackageHelper.getSecureContainerList(); 18223 if (ArrayUtils.isEmpty(list)) { 18224 Log.i(TAG, "No secure containers found"); 18225 } else { 18226 // Process list of secure containers and categorize them 18227 // as active or stale based on their package internal state. 18228 18229 // reader 18230 synchronized (mPackages) { 18231 for (String cid : list) { 18232 // Leave stages untouched for now; installer service owns them 18233 if (PackageInstallerService.isStageName(cid)) continue; 18234 18235 if (DEBUG_SD_INSTALL) 18236 Log.i(TAG, "Processing container " + cid); 18237 String pkgName = getAsecPackageName(cid); 18238 if (pkgName == null) { 18239 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 18240 continue; 18241 } 18242 if (DEBUG_SD_INSTALL) 18243 Log.i(TAG, "Looking for pkg : " + pkgName); 18244 18245 final PackageSetting ps = mSettings.mPackages.get(pkgName); 18246 if (ps == null) { 18247 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 18248 continue; 18249 } 18250 18251 /* 18252 * Skip packages that are not external if we're unmounting 18253 * external storage. 18254 */ 18255 if (externalStorage && !isMounted && !isExternal(ps)) { 18256 continue; 18257 } 18258 18259 final AsecInstallArgs args = new AsecInstallArgs(cid, 18260 getAppDexInstructionSets(ps), ps.isForwardLocked()); 18261 // The package status is changed only if the code path 18262 // matches between settings and the container id. 18263 if (ps.codePathString != null 18264 && ps.codePathString.startsWith(args.getCodePath())) { 18265 if (DEBUG_SD_INSTALL) { 18266 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 18267 + " at code path: " + ps.codePathString); 18268 } 18269 18270 // We do have a valid package installed on sdcard 18271 processCids.put(args, ps.codePathString); 18272 final int uid = ps.appId; 18273 if (uid != -1) { 18274 uidArr = ArrayUtils.appendInt(uidArr, uid); 18275 } 18276 } else { 18277 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 18278 + ps.codePathString); 18279 } 18280 } 18281 } 18282 18283 Arrays.sort(uidArr); 18284 } 18285 18286 // Process packages with valid entries. 18287 if (isMounted) { 18288 if (DEBUG_SD_INSTALL) 18289 Log.i(TAG, "Loading packages"); 18290 loadMediaPackages(processCids, uidArr, externalStorage); 18291 startCleaningPackages(); 18292 mInstallerService.onSecureContainersAvailable(); 18293 } else { 18294 if (DEBUG_SD_INSTALL) 18295 Log.i(TAG, "Unloading packages"); 18296 unloadMediaPackages(processCids, uidArr, reportStatus); 18297 } 18298 } 18299 18300 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18301 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 18302 final int size = infos.size(); 18303 final String[] packageNames = new String[size]; 18304 final int[] packageUids = new int[size]; 18305 for (int i = 0; i < size; i++) { 18306 final ApplicationInfo info = infos.get(i); 18307 packageNames[i] = info.packageName; 18308 packageUids[i] = info.uid; 18309 } 18310 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 18311 finishedReceiver); 18312 } 18313 18314 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18315 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18316 sendResourcesChangedBroadcast(mediaStatus, replacing, 18317 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 18318 } 18319 18320 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18321 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18322 int size = pkgList.length; 18323 if (size > 0) { 18324 // Send broadcasts here 18325 Bundle extras = new Bundle(); 18326 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 18327 if (uidArr != null) { 18328 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 18329 } 18330 if (replacing) { 18331 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 18332 } 18333 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 18334 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 18335 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 18336 } 18337 } 18338 18339 /* 18340 * Look at potentially valid container ids from processCids If package 18341 * information doesn't match the one on record or package scanning fails, 18342 * the cid is added to list of removeCids. We currently don't delete stale 18343 * containers. 18344 */ 18345 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 18346 boolean externalStorage) { 18347 ArrayList<String> pkgList = new ArrayList<String>(); 18348 Set<AsecInstallArgs> keys = processCids.keySet(); 18349 18350 for (AsecInstallArgs args : keys) { 18351 String codePath = processCids.get(args); 18352 if (DEBUG_SD_INSTALL) 18353 Log.i(TAG, "Loading container : " + args.cid); 18354 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 18355 try { 18356 // Make sure there are no container errors first. 18357 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 18358 Slog.e(TAG, "Failed to mount cid : " + args.cid 18359 + " when installing from sdcard"); 18360 continue; 18361 } 18362 // Check code path here. 18363 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 18364 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 18365 + " does not match one in settings " + codePath); 18366 continue; 18367 } 18368 // Parse package 18369 int parseFlags = mDefParseFlags; 18370 if (args.isExternalAsec()) { 18371 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 18372 } 18373 if (args.isFwdLocked()) { 18374 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 18375 } 18376 18377 synchronized (mInstallLock) { 18378 PackageParser.Package pkg = null; 18379 try { 18380 // Sadly we don't know the package name yet to freeze it 18381 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 18382 SCAN_IGNORE_FROZEN, 0, null); 18383 } catch (PackageManagerException e) { 18384 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 18385 } 18386 // Scan the package 18387 if (pkg != null) { 18388 /* 18389 * TODO why is the lock being held? doPostInstall is 18390 * called in other places without the lock. This needs 18391 * to be straightened out. 18392 */ 18393 // writer 18394 synchronized (mPackages) { 18395 retCode = PackageManager.INSTALL_SUCCEEDED; 18396 pkgList.add(pkg.packageName); 18397 // Post process args 18398 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 18399 pkg.applicationInfo.uid); 18400 } 18401 } else { 18402 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 18403 } 18404 } 18405 18406 } finally { 18407 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 18408 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 18409 } 18410 } 18411 } 18412 // writer 18413 synchronized (mPackages) { 18414 // If the platform SDK has changed since the last time we booted, 18415 // we need to re-grant app permission to catch any new ones that 18416 // appear. This is really a hack, and means that apps can in some 18417 // cases get permissions that the user didn't initially explicitly 18418 // allow... it would be nice to have some better way to handle 18419 // this situation. 18420 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 18421 : mSettings.getInternalVersion(); 18422 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 18423 : StorageManager.UUID_PRIVATE_INTERNAL; 18424 18425 int updateFlags = UPDATE_PERMISSIONS_ALL; 18426 if (ver.sdkVersion != mSdkVersion) { 18427 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 18428 + mSdkVersion + "; regranting permissions for external"); 18429 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 18430 } 18431 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 18432 18433 // Yay, everything is now upgraded 18434 ver.forceCurrent(); 18435 18436 // can downgrade to reader 18437 // Persist settings 18438 mSettings.writeLPr(); 18439 } 18440 // Send a broadcast to let everyone know we are done processing 18441 if (pkgList.size() > 0) { 18442 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 18443 } 18444 } 18445 18446 /* 18447 * Utility method to unload a list of specified containers 18448 */ 18449 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 18450 // Just unmount all valid containers. 18451 for (AsecInstallArgs arg : cidArgs) { 18452 synchronized (mInstallLock) { 18453 arg.doPostDeleteLI(false); 18454 } 18455 } 18456 } 18457 18458 /* 18459 * Unload packages mounted on external media. This involves deleting package 18460 * data from internal structures, sending broadcasts about disabled packages, 18461 * gc'ing to free up references, unmounting all secure containers 18462 * corresponding to packages on external media, and posting a 18463 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 18464 * that we always have to post this message if status has been requested no 18465 * matter what. 18466 */ 18467 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 18468 final boolean reportStatus) { 18469 if (DEBUG_SD_INSTALL) 18470 Log.i(TAG, "unloading media packages"); 18471 ArrayList<String> pkgList = new ArrayList<String>(); 18472 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 18473 final Set<AsecInstallArgs> keys = processCids.keySet(); 18474 for (AsecInstallArgs args : keys) { 18475 String pkgName = args.getPackageName(); 18476 if (DEBUG_SD_INSTALL) 18477 Log.i(TAG, "Trying to unload pkg : " + pkgName); 18478 // Delete package internally 18479 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 18480 synchronized (mInstallLock) { 18481 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 18482 final boolean res; 18483 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 18484 "unloadMediaPackages")) { 18485 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 18486 null); 18487 } 18488 if (res) { 18489 pkgList.add(pkgName); 18490 } else { 18491 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 18492 failedList.add(args); 18493 } 18494 } 18495 } 18496 18497 // reader 18498 synchronized (mPackages) { 18499 // We didn't update the settings after removing each package; 18500 // write them now for all packages. 18501 mSettings.writeLPr(); 18502 } 18503 18504 // We have to absolutely send UPDATED_MEDIA_STATUS only 18505 // after confirming that all the receivers processed the ordered 18506 // broadcast when packages get disabled, force a gc to clean things up. 18507 // and unload all the containers. 18508 if (pkgList.size() > 0) { 18509 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 18510 new IIntentReceiver.Stub() { 18511 public void performReceive(Intent intent, int resultCode, String data, 18512 Bundle extras, boolean ordered, boolean sticky, 18513 int sendingUser) throws RemoteException { 18514 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 18515 reportStatus ? 1 : 0, 1, keys); 18516 mHandler.sendMessage(msg); 18517 } 18518 }); 18519 } else { 18520 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 18521 keys); 18522 mHandler.sendMessage(msg); 18523 } 18524 } 18525 18526 private void loadPrivatePackages(final VolumeInfo vol) { 18527 mHandler.post(new Runnable() { 18528 @Override 18529 public void run() { 18530 loadPrivatePackagesInner(vol); 18531 } 18532 }); 18533 } 18534 18535 private void loadPrivatePackagesInner(VolumeInfo vol) { 18536 final String volumeUuid = vol.fsUuid; 18537 if (TextUtils.isEmpty(volumeUuid)) { 18538 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 18539 return; 18540 } 18541 18542 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 18543 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 18544 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 18545 18546 final VersionInfo ver; 18547 final List<PackageSetting> packages; 18548 synchronized (mPackages) { 18549 ver = mSettings.findOrCreateVersion(volumeUuid); 18550 packages = mSettings.getVolumePackagesLPr(volumeUuid); 18551 } 18552 18553 for (PackageSetting ps : packages) { 18554 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 18555 synchronized (mInstallLock) { 18556 final PackageParser.Package pkg; 18557 try { 18558 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 18559 loaded.add(pkg.applicationInfo); 18560 18561 } catch (PackageManagerException e) { 18562 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 18563 } 18564 18565 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 18566 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 18567 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 18568 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 18569 } 18570 } 18571 } 18572 18573 // Reconcile app data for all started/unlocked users 18574 final StorageManager sm = mContext.getSystemService(StorageManager.class); 18575 final UserManager um = mContext.getSystemService(UserManager.class); 18576 for (UserInfo user : um.getUsers()) { 18577 final int flags; 18578 if (um.isUserUnlocked(user.id)) { 18579 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18580 } else if (um.isUserRunning(user.id)) { 18581 flags = StorageManager.FLAG_STORAGE_DE; 18582 } else { 18583 continue; 18584 } 18585 18586 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 18587 synchronized (mInstallLock) { 18588 reconcileAppsDataLI(volumeUuid, user.id, flags); 18589 } 18590 } 18591 18592 synchronized (mPackages) { 18593 int updateFlags = UPDATE_PERMISSIONS_ALL; 18594 if (ver.sdkVersion != mSdkVersion) { 18595 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 18596 + mSdkVersion + "; regranting permissions for " + volumeUuid); 18597 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 18598 } 18599 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 18600 18601 // Yay, everything is now upgraded 18602 ver.forceCurrent(); 18603 18604 mSettings.writeLPr(); 18605 } 18606 18607 for (PackageFreezer freezer : freezers) { 18608 freezer.close(); 18609 } 18610 18611 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 18612 sendResourcesChangedBroadcast(true, false, loaded, null); 18613 } 18614 18615 private void unloadPrivatePackages(final VolumeInfo vol) { 18616 mHandler.post(new Runnable() { 18617 @Override 18618 public void run() { 18619 unloadPrivatePackagesInner(vol); 18620 } 18621 }); 18622 } 18623 18624 private void unloadPrivatePackagesInner(VolumeInfo vol) { 18625 final String volumeUuid = vol.fsUuid; 18626 if (TextUtils.isEmpty(volumeUuid)) { 18627 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 18628 return; 18629 } 18630 18631 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 18632 synchronized (mInstallLock) { 18633 synchronized (mPackages) { 18634 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 18635 for (PackageSetting ps : packages) { 18636 if (ps.pkg == null) continue; 18637 18638 final ApplicationInfo info = ps.pkg.applicationInfo; 18639 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 18640 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 18641 18642 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 18643 "unloadPrivatePackagesInner")) { 18644 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 18645 false, null)) { 18646 unloaded.add(info); 18647 } else { 18648 Slog.w(TAG, "Failed to unload " + ps.codePath); 18649 } 18650 } 18651 } 18652 18653 mSettings.writeLPr(); 18654 } 18655 } 18656 18657 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 18658 sendResourcesChangedBroadcast(false, false, unloaded, null); 18659 } 18660 18661 /** 18662 * Prepare storage areas for given user on all mounted devices. 18663 */ 18664 void prepareUserData(int userId, int userSerial, int flags) { 18665 synchronized (mInstallLock) { 18666 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18667 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 18668 final String volumeUuid = vol.getFsUuid(); 18669 prepareUserDataLI(volumeUuid, userId, userSerial, flags, true); 18670 } 18671 } 18672 } 18673 18674 private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags, 18675 boolean allowRecover) { 18676 // Prepare storage and verify that serial numbers are consistent; if 18677 // there's a mismatch we need to destroy to avoid leaking data 18678 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18679 try { 18680 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags); 18681 18682 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) { 18683 UserManagerService.enforceSerialNumber( 18684 Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial); 18685 } 18686 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) { 18687 UserManagerService.enforceSerialNumber( 18688 Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial); 18689 } 18690 18691 synchronized (mInstallLock) { 18692 mInstaller.createUserData(volumeUuid, userId, userSerial, flags); 18693 } 18694 } catch (Exception e) { 18695 logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid 18696 + " because we failed to prepare: " + e); 18697 destroyUserDataLI(volumeUuid, userId, flags); 18698 18699 if (allowRecover) { 18700 // Try one last time; if we fail again we're really in trouble 18701 prepareUserDataLI(volumeUuid, userId, userSerial, flags, false); 18702 } 18703 } 18704 } 18705 18706 /** 18707 * Destroy storage areas for given user on all mounted devices. 18708 */ 18709 void destroyUserData(int userId, int flags) { 18710 synchronized (mInstallLock) { 18711 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18712 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 18713 final String volumeUuid = vol.getFsUuid(); 18714 destroyUserDataLI(volumeUuid, userId, flags); 18715 } 18716 } 18717 } 18718 18719 private void destroyUserDataLI(String volumeUuid, int userId, int flags) { 18720 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18721 try { 18722 // Clean up app data, profile data, and media data 18723 mInstaller.destroyUserData(volumeUuid, userId, flags); 18724 18725 // Clean up system data 18726 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 18727 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 18728 FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId)); 18729 FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId)); 18730 } 18731 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18732 FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId)); 18733 } 18734 } 18735 18736 // Data with special labels is now gone, so finish the job 18737 storage.destroyUserStorage(volumeUuid, userId, flags); 18738 18739 } catch (Exception e) { 18740 logCriticalInfo(Log.WARN, 18741 "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e); 18742 } 18743 } 18744 18745 /** 18746 * Examine all users present on given mounted volume, and destroy data 18747 * belonging to users that are no longer valid, or whose user ID has been 18748 * recycled. 18749 */ 18750 private void reconcileUsers(String volumeUuid) { 18751 final List<File> files = new ArrayList<>(); 18752 Collections.addAll(files, FileUtils 18753 .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid))); 18754 Collections.addAll(files, FileUtils 18755 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid))); 18756 for (File file : files) { 18757 if (!file.isDirectory()) continue; 18758 18759 final int userId; 18760 final UserInfo info; 18761 try { 18762 userId = Integer.parseInt(file.getName()); 18763 info = sUserManager.getUserInfo(userId); 18764 } catch (NumberFormatException e) { 18765 Slog.w(TAG, "Invalid user directory " + file); 18766 continue; 18767 } 18768 18769 boolean destroyUser = false; 18770 if (info == null) { 18771 logCriticalInfo(Log.WARN, "Destroying user directory " + file 18772 + " because no matching user was found"); 18773 destroyUser = true; 18774 } else if (!mOnlyCore) { 18775 try { 18776 UserManagerService.enforceSerialNumber(file, info.serialNumber); 18777 } catch (IOException e) { 18778 logCriticalInfo(Log.WARN, "Destroying user directory " + file 18779 + " because we failed to enforce serial number: " + e); 18780 destroyUser = true; 18781 } 18782 } 18783 18784 if (destroyUser) { 18785 synchronized (mInstallLock) { 18786 destroyUserDataLI(volumeUuid, userId, 18787 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18788 } 18789 } 18790 } 18791 } 18792 18793 private void assertPackageKnown(String volumeUuid, String packageName) 18794 throws PackageManagerException { 18795 synchronized (mPackages) { 18796 final PackageSetting ps = mSettings.mPackages.get(packageName); 18797 if (ps == null) { 18798 throw new PackageManagerException("Package " + packageName + " is unknown"); 18799 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 18800 throw new PackageManagerException( 18801 "Package " + packageName + " found on unknown volume " + volumeUuid 18802 + "; expected volume " + ps.volumeUuid); 18803 } 18804 } 18805 } 18806 18807 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 18808 throws PackageManagerException { 18809 synchronized (mPackages) { 18810 final PackageSetting ps = mSettings.mPackages.get(packageName); 18811 if (ps == null) { 18812 throw new PackageManagerException("Package " + packageName + " is unknown"); 18813 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 18814 throw new PackageManagerException( 18815 "Package " + packageName + " found on unknown volume " + volumeUuid 18816 + "; expected volume " + ps.volumeUuid); 18817 } else if (!ps.getInstalled(userId)) { 18818 throw new PackageManagerException( 18819 "Package " + packageName + " not installed for user " + userId); 18820 } 18821 } 18822 } 18823 18824 /** 18825 * Examine all apps present on given mounted volume, and destroy apps that 18826 * aren't expected, either due to uninstallation or reinstallation on 18827 * another volume. 18828 */ 18829 private void reconcileApps(String volumeUuid) { 18830 final File[] files = FileUtils 18831 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 18832 for (File file : files) { 18833 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 18834 && !PackageInstallerService.isStageName(file.getName()); 18835 if (!isPackage) { 18836 // Ignore entries which are not packages 18837 continue; 18838 } 18839 18840 try { 18841 final PackageLite pkg = PackageParser.parsePackageLite(file, 18842 PackageParser.PARSE_MUST_BE_APK); 18843 assertPackageKnown(volumeUuid, pkg.packageName); 18844 18845 } catch (PackageParserException | PackageManagerException e) { 18846 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 18847 synchronized (mInstallLock) { 18848 removeCodePathLI(file); 18849 } 18850 } 18851 } 18852 } 18853 18854 /** 18855 * Reconcile all app data for the given user. 18856 * <p> 18857 * Verifies that directories exist and that ownership and labeling is 18858 * correct for all installed apps on all mounted volumes. 18859 */ 18860 void reconcileAppsData(int userId, int flags) { 18861 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18862 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 18863 final String volumeUuid = vol.getFsUuid(); 18864 synchronized (mInstallLock) { 18865 reconcileAppsDataLI(volumeUuid, userId, flags); 18866 } 18867 } 18868 } 18869 18870 /** 18871 * Reconcile all app data on given mounted volume. 18872 * <p> 18873 * Destroys app data that isn't expected, either due to uninstallation or 18874 * reinstallation on another volume. 18875 * <p> 18876 * Verifies that directories exist and that ownership and labeling is 18877 * correct for all installed apps. 18878 */ 18879 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) { 18880 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 18881 + Integer.toHexString(flags)); 18882 18883 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 18884 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 18885 18886 boolean restoreconNeeded = false; 18887 18888 // First look for stale data that doesn't belong, and check if things 18889 // have changed since we did our last restorecon 18890 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18891 if (!isUserKeyUnlocked(userId)) { 18892 throw new RuntimeException( 18893 "Yikes, someone asked us to reconcile CE storage while " + userId 18894 + " was still locked; this would have caused massive data loss!"); 18895 } 18896 18897 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 18898 18899 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 18900 for (File file : files) { 18901 final String packageName = file.getName(); 18902 try { 18903 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 18904 } catch (PackageManagerException e) { 18905 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 18906 try { 18907 mInstaller.destroyAppData(volumeUuid, packageName, userId, 18908 StorageManager.FLAG_STORAGE_CE, 0); 18909 } catch (InstallerException e2) { 18910 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 18911 } 18912 } 18913 } 18914 } 18915 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 18916 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 18917 18918 final File[] files = FileUtils.listFilesOrEmpty(deDir); 18919 for (File file : files) { 18920 final String packageName = file.getName(); 18921 try { 18922 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 18923 } catch (PackageManagerException e) { 18924 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 18925 try { 18926 mInstaller.destroyAppData(volumeUuid, packageName, userId, 18927 StorageManager.FLAG_STORAGE_DE, 0); 18928 } catch (InstallerException e2) { 18929 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 18930 } 18931 } 18932 } 18933 } 18934 18935 // Ensure that data directories are ready to roll for all packages 18936 // installed for this volume and user 18937 final List<PackageSetting> packages; 18938 synchronized (mPackages) { 18939 packages = mSettings.getVolumePackagesLPr(volumeUuid); 18940 } 18941 int preparedCount = 0; 18942 for (PackageSetting ps : packages) { 18943 final String packageName = ps.name; 18944 if (ps.pkg == null) { 18945 Slog.w(TAG, "Odd, missing scanned package " + packageName); 18946 // TODO: might be due to legacy ASEC apps; we should circle back 18947 // and reconcile again once they're scanned 18948 continue; 18949 } 18950 18951 if (ps.getInstalled(userId)) { 18952 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 18953 18954 if (maybeMigrateAppDataLIF(ps.pkg, userId)) { 18955 // We may have just shuffled around app data directories, so 18956 // prepare them one more time 18957 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 18958 } 18959 18960 preparedCount++; 18961 } 18962 } 18963 18964 if (restoreconNeeded) { 18965 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18966 SELinuxMMAC.setRestoreconDone(ceDir); 18967 } 18968 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 18969 SELinuxMMAC.setRestoreconDone(deDir); 18970 } 18971 } 18972 18973 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 18974 + " packages; restoreconNeeded was " + restoreconNeeded); 18975 } 18976 18977 /** 18978 * Prepare app data for the given app just after it was installed or 18979 * upgraded. This method carefully only touches users that it's installed 18980 * for, and it forces a restorecon to handle any seinfo changes. 18981 * <p> 18982 * Verifies that directories exist and that ownership and labeling is 18983 * correct for all installed apps. If there is an ownership mismatch, it 18984 * will try recovering system apps by wiping data; third-party app data is 18985 * left intact. 18986 * <p> 18987 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 18988 */ 18989 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 18990 final PackageSetting ps; 18991 synchronized (mPackages) { 18992 ps = mSettings.mPackages.get(pkg.packageName); 18993 mSettings.writeKernelMappingLPr(ps); 18994 } 18995 18996 final UserManager um = mContext.getSystemService(UserManager.class); 18997 for (UserInfo user : um.getUsers()) { 18998 final int flags; 18999 if (um.isUserUnlocked(user.id)) { 19000 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19001 } else if (um.isUserRunning(user.id)) { 19002 flags = StorageManager.FLAG_STORAGE_DE; 19003 } else { 19004 continue; 19005 } 19006 19007 if (ps.getInstalled(user.id)) { 19008 // Whenever an app changes, force a restorecon of its data 19009 // TODO: when user data is locked, mark that we're still dirty 19010 prepareAppDataLIF(pkg, user.id, flags, true); 19011 } 19012 } 19013 } 19014 19015 /** 19016 * Prepare app data for the given app. 19017 * <p> 19018 * Verifies that directories exist and that ownership and labeling is 19019 * correct for all installed apps. If there is an ownership mismatch, this 19020 * will try recovering system apps by wiping data; third-party app data is 19021 * left intact. 19022 */ 19023 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags, 19024 boolean restoreconNeeded) { 19025 if (pkg == null) { 19026 Slog.wtf(TAG, "Package was null!", new Throwable()); 19027 return; 19028 } 19029 prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded); 19030 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19031 for (int i = 0; i < childCount; i++) { 19032 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded); 19033 } 19034 } 19035 19036 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags, 19037 boolean restoreconNeeded) { 19038 if (DEBUG_APP_DATA) { 19039 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 19040 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 19041 } 19042 19043 final String volumeUuid = pkg.volumeUuid; 19044 final String packageName = pkg.packageName; 19045 final ApplicationInfo app = pkg.applicationInfo; 19046 final int appId = UserHandle.getAppId(app.uid); 19047 19048 Preconditions.checkNotNull(app.seinfo); 19049 19050 try { 19051 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19052 appId, app.seinfo, app.targetSdkVersion); 19053 } catch (InstallerException e) { 19054 if (app.isSystemApp()) { 19055 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 19056 + ", but trying to recover: " + e); 19057 destroyAppDataLeafLIF(pkg, userId, flags); 19058 try { 19059 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19060 appId, app.seinfo, app.targetSdkVersion); 19061 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 19062 } catch (InstallerException e2) { 19063 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 19064 } 19065 } else { 19066 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 19067 } 19068 } 19069 19070 if (restoreconNeeded) { 19071 try { 19072 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, 19073 app.seinfo); 19074 } catch (InstallerException e) { 19075 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 19076 } 19077 } 19078 19079 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19080 try { 19081 // CE storage is unlocked right now, so read out the inode and 19082 // remember for use later when it's locked 19083 // TODO: mark this structure as dirty so we persist it! 19084 final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId, 19085 StorageManager.FLAG_STORAGE_CE); 19086 synchronized (mPackages) { 19087 final PackageSetting ps = mSettings.mPackages.get(packageName); 19088 if (ps != null) { 19089 ps.setCeDataInode(ceDataInode, userId); 19090 } 19091 } 19092 } catch (InstallerException e) { 19093 Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e); 19094 } 19095 } 19096 19097 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19098 } 19099 19100 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 19101 if (pkg == null) { 19102 Slog.wtf(TAG, "Package was null!", new Throwable()); 19103 return; 19104 } 19105 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19106 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19107 for (int i = 0; i < childCount; i++) { 19108 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 19109 } 19110 } 19111 19112 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 19113 final String volumeUuid = pkg.volumeUuid; 19114 final String packageName = pkg.packageName; 19115 final ApplicationInfo app = pkg.applicationInfo; 19116 19117 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19118 // Create a native library symlink only if we have native libraries 19119 // and if the native libraries are 32 bit libraries. We do not provide 19120 // this symlink for 64 bit libraries. 19121 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 19122 final String nativeLibPath = app.nativeLibraryDir; 19123 try { 19124 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 19125 nativeLibPath, userId); 19126 } catch (InstallerException e) { 19127 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 19128 } 19129 } 19130 } 19131 } 19132 19133 /** 19134 * For system apps on non-FBE devices, this method migrates any existing 19135 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 19136 * requested by the app. 19137 */ 19138 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 19139 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 19140 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 19141 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 19142 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 19143 try { 19144 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 19145 storageTarget); 19146 } catch (InstallerException e) { 19147 logCriticalInfo(Log.WARN, 19148 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 19149 } 19150 return true; 19151 } else { 19152 return false; 19153 } 19154 } 19155 19156 public PackageFreezer freezePackage(String packageName, String killReason) { 19157 return new PackageFreezer(packageName, killReason); 19158 } 19159 19160 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 19161 String killReason) { 19162 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 19163 return new PackageFreezer(); 19164 } else { 19165 return freezePackage(packageName, killReason); 19166 } 19167 } 19168 19169 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 19170 String killReason) { 19171 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 19172 return new PackageFreezer(); 19173 } else { 19174 return freezePackage(packageName, killReason); 19175 } 19176 } 19177 19178 /** 19179 * Class that freezes and kills the given package upon creation, and 19180 * unfreezes it upon closing. This is typically used when doing surgery on 19181 * app code/data to prevent the app from running while you're working. 19182 */ 19183 private class PackageFreezer implements AutoCloseable { 19184 private final String mPackageName; 19185 private final PackageFreezer[] mChildren; 19186 19187 private final boolean mWeFroze; 19188 19189 private final AtomicBoolean mClosed = new AtomicBoolean(); 19190 private final CloseGuard mCloseGuard = CloseGuard.get(); 19191 19192 /** 19193 * Create and return a stub freezer that doesn't actually do anything, 19194 * typically used when someone requested 19195 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 19196 * {@link PackageManager#DELETE_DONT_KILL_APP}. 19197 */ 19198 public PackageFreezer() { 19199 mPackageName = null; 19200 mChildren = null; 19201 mWeFroze = false; 19202 mCloseGuard.open("close"); 19203 } 19204 19205 public PackageFreezer(String packageName, String killReason) { 19206 synchronized (mPackages) { 19207 mPackageName = packageName; 19208 mWeFroze = mFrozenPackages.add(mPackageName); 19209 19210 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 19211 if (ps != null) { 19212 killApplication(ps.name, ps.appId, killReason); 19213 } 19214 19215 final PackageParser.Package p = mPackages.get(packageName); 19216 if (p != null && p.childPackages != null) { 19217 final int N = p.childPackages.size(); 19218 mChildren = new PackageFreezer[N]; 19219 for (int i = 0; i < N; i++) { 19220 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 19221 killReason); 19222 } 19223 } else { 19224 mChildren = null; 19225 } 19226 } 19227 mCloseGuard.open("close"); 19228 } 19229 19230 @Override 19231 protected void finalize() throws Throwable { 19232 try { 19233 mCloseGuard.warnIfOpen(); 19234 close(); 19235 } finally { 19236 super.finalize(); 19237 } 19238 } 19239 19240 @Override 19241 public void close() { 19242 mCloseGuard.close(); 19243 if (mClosed.compareAndSet(false, true)) { 19244 synchronized (mPackages) { 19245 if (mWeFroze) { 19246 mFrozenPackages.remove(mPackageName); 19247 } 19248 19249 if (mChildren != null) { 19250 for (PackageFreezer freezer : mChildren) { 19251 freezer.close(); 19252 } 19253 } 19254 } 19255 } 19256 } 19257 } 19258 19259 /** 19260 * Verify that given package is currently frozen. 19261 */ 19262 private void checkPackageFrozen(String packageName) { 19263 synchronized (mPackages) { 19264 if (!mFrozenPackages.contains(packageName)) { 19265 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 19266 } 19267 } 19268 } 19269 19270 @Override 19271 public int movePackage(final String packageName, final String volumeUuid) { 19272 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19273 19274 final int moveId = mNextMoveId.getAndIncrement(); 19275 mHandler.post(new Runnable() { 19276 @Override 19277 public void run() { 19278 try { 19279 movePackageInternal(packageName, volumeUuid, moveId); 19280 } catch (PackageManagerException e) { 19281 Slog.w(TAG, "Failed to move " + packageName, e); 19282 mMoveCallbacks.notifyStatusChanged(moveId, 19283 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19284 } 19285 } 19286 }); 19287 return moveId; 19288 } 19289 19290 private void movePackageInternal(final String packageName, final String volumeUuid, 19291 final int moveId) throws PackageManagerException { 19292 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 19293 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19294 final PackageManager pm = mContext.getPackageManager(); 19295 19296 final boolean currentAsec; 19297 final String currentVolumeUuid; 19298 final File codeFile; 19299 final String installerPackageName; 19300 final String packageAbiOverride; 19301 final int appId; 19302 final String seinfo; 19303 final String label; 19304 final int targetSdkVersion; 19305 final PackageFreezer freezer; 19306 19307 // reader 19308 synchronized (mPackages) { 19309 final PackageParser.Package pkg = mPackages.get(packageName); 19310 final PackageSetting ps = mSettings.mPackages.get(packageName); 19311 if (pkg == null || ps == null) { 19312 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 19313 } 19314 19315 if (pkg.applicationInfo.isSystemApp()) { 19316 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 19317 "Cannot move system application"); 19318 } 19319 19320 if (pkg.applicationInfo.isExternalAsec()) { 19321 currentAsec = true; 19322 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 19323 } else if (pkg.applicationInfo.isForwardLocked()) { 19324 currentAsec = true; 19325 currentVolumeUuid = "forward_locked"; 19326 } else { 19327 currentAsec = false; 19328 currentVolumeUuid = ps.volumeUuid; 19329 19330 final File probe = new File(pkg.codePath); 19331 final File probeOat = new File(probe, "oat"); 19332 if (!probe.isDirectory() || !probeOat.isDirectory()) { 19333 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19334 "Move only supported for modern cluster style installs"); 19335 } 19336 } 19337 19338 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 19339 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19340 "Package already moved to " + volumeUuid); 19341 } 19342 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 19343 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 19344 "Device admin cannot be moved"); 19345 } 19346 19347 if (mFrozenPackages.contains(packageName)) { 19348 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 19349 "Failed to move already frozen package"); 19350 } 19351 19352 codeFile = new File(pkg.codePath); 19353 installerPackageName = ps.installerPackageName; 19354 packageAbiOverride = ps.cpuAbiOverrideString; 19355 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 19356 seinfo = pkg.applicationInfo.seinfo; 19357 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 19358 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 19359 freezer = new PackageFreezer(packageName, "movePackageInternal"); 19360 } 19361 19362 final Bundle extras = new Bundle(); 19363 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 19364 extras.putString(Intent.EXTRA_TITLE, label); 19365 mMoveCallbacks.notifyCreated(moveId, extras); 19366 19367 int installFlags; 19368 final boolean moveCompleteApp; 19369 final File measurePath; 19370 19371 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 19372 installFlags = INSTALL_INTERNAL; 19373 moveCompleteApp = !currentAsec; 19374 measurePath = Environment.getDataAppDirectory(volumeUuid); 19375 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 19376 installFlags = INSTALL_EXTERNAL; 19377 moveCompleteApp = false; 19378 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 19379 } else { 19380 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 19381 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 19382 || !volume.isMountedWritable()) { 19383 freezer.close(); 19384 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19385 "Move location not mounted private volume"); 19386 } 19387 19388 Preconditions.checkState(!currentAsec); 19389 19390 installFlags = INSTALL_INTERNAL; 19391 moveCompleteApp = true; 19392 measurePath = Environment.getDataAppDirectory(volumeUuid); 19393 } 19394 19395 final PackageStats stats = new PackageStats(null, -1); 19396 synchronized (mInstaller) { 19397 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 19398 freezer.close(); 19399 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19400 "Failed to measure package size"); 19401 } 19402 } 19403 19404 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 19405 + stats.dataSize); 19406 19407 final long startFreeBytes = measurePath.getFreeSpace(); 19408 final long sizeBytes; 19409 if (moveCompleteApp) { 19410 sizeBytes = stats.codeSize + stats.dataSize; 19411 } else { 19412 sizeBytes = stats.codeSize; 19413 } 19414 19415 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 19416 freezer.close(); 19417 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19418 "Not enough free space to move"); 19419 } 19420 19421 mMoveCallbacks.notifyStatusChanged(moveId, 10); 19422 19423 final CountDownLatch installedLatch = new CountDownLatch(1); 19424 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 19425 @Override 19426 public void onUserActionRequired(Intent intent) throws RemoteException { 19427 throw new IllegalStateException(); 19428 } 19429 19430 @Override 19431 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 19432 Bundle extras) throws RemoteException { 19433 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 19434 + PackageManager.installStatusToString(returnCode, msg)); 19435 19436 installedLatch.countDown(); 19437 freezer.close(); 19438 19439 final int status = PackageManager.installStatusToPublicStatus(returnCode); 19440 switch (status) { 19441 case PackageInstaller.STATUS_SUCCESS: 19442 mMoveCallbacks.notifyStatusChanged(moveId, 19443 PackageManager.MOVE_SUCCEEDED); 19444 break; 19445 case PackageInstaller.STATUS_FAILURE_STORAGE: 19446 mMoveCallbacks.notifyStatusChanged(moveId, 19447 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 19448 break; 19449 default: 19450 mMoveCallbacks.notifyStatusChanged(moveId, 19451 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19452 break; 19453 } 19454 } 19455 }; 19456 19457 final MoveInfo move; 19458 if (moveCompleteApp) { 19459 // Kick off a thread to report progress estimates 19460 new Thread() { 19461 @Override 19462 public void run() { 19463 while (true) { 19464 try { 19465 if (installedLatch.await(1, TimeUnit.SECONDS)) { 19466 break; 19467 } 19468 } catch (InterruptedException ignored) { 19469 } 19470 19471 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 19472 final int progress = 10 + (int) MathUtils.constrain( 19473 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 19474 mMoveCallbacks.notifyStatusChanged(moveId, progress); 19475 } 19476 } 19477 }.start(); 19478 19479 final String dataAppName = codeFile.getName(); 19480 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 19481 dataAppName, appId, seinfo, targetSdkVersion); 19482 } else { 19483 move = null; 19484 } 19485 19486 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 19487 19488 final Message msg = mHandler.obtainMessage(INIT_COPY); 19489 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 19490 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 19491 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 19492 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/); 19493 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 19494 msg.obj = params; 19495 19496 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 19497 System.identityHashCode(msg.obj)); 19498 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 19499 System.identityHashCode(msg.obj)); 19500 19501 mHandler.sendMessage(msg); 19502 } 19503 19504 @Override 19505 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 19506 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19507 19508 final int realMoveId = mNextMoveId.getAndIncrement(); 19509 final Bundle extras = new Bundle(); 19510 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 19511 mMoveCallbacks.notifyCreated(realMoveId, extras); 19512 19513 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 19514 @Override 19515 public void onCreated(int moveId, Bundle extras) { 19516 // Ignored 19517 } 19518 19519 @Override 19520 public void onStatusChanged(int moveId, int status, long estMillis) { 19521 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 19522 } 19523 }; 19524 19525 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19526 storage.setPrimaryStorageUuid(volumeUuid, callback); 19527 return realMoveId; 19528 } 19529 19530 @Override 19531 public int getMoveStatus(int moveId) { 19532 mContext.enforceCallingOrSelfPermission( 19533 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19534 return mMoveCallbacks.mLastStatus.get(moveId); 19535 } 19536 19537 @Override 19538 public void registerMoveCallback(IPackageMoveObserver callback) { 19539 mContext.enforceCallingOrSelfPermission( 19540 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19541 mMoveCallbacks.register(callback); 19542 } 19543 19544 @Override 19545 public void unregisterMoveCallback(IPackageMoveObserver callback) { 19546 mContext.enforceCallingOrSelfPermission( 19547 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19548 mMoveCallbacks.unregister(callback); 19549 } 19550 19551 @Override 19552 public boolean setInstallLocation(int loc) { 19553 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 19554 null); 19555 if (getInstallLocation() == loc) { 19556 return true; 19557 } 19558 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 19559 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 19560 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 19561 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 19562 return true; 19563 } 19564 return false; 19565 } 19566 19567 @Override 19568 public int getInstallLocation() { 19569 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 19570 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 19571 PackageHelper.APP_INSTALL_AUTO); 19572 } 19573 19574 /** Called by UserManagerService */ 19575 void cleanUpUser(UserManagerService userManager, int userHandle) { 19576 synchronized (mPackages) { 19577 mDirtyUsers.remove(userHandle); 19578 mUserNeedsBadging.delete(userHandle); 19579 mSettings.removeUserLPw(userHandle); 19580 mPendingBroadcasts.remove(userHandle); 19581 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 19582 removeUnusedPackagesLPw(userManager, userHandle); 19583 } 19584 } 19585 19586 /** 19587 * We're removing userHandle and would like to remove any downloaded packages 19588 * that are no longer in use by any other user. 19589 * @param userHandle the user being removed 19590 */ 19591 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 19592 final boolean DEBUG_CLEAN_APKS = false; 19593 int [] users = userManager.getUserIds(); 19594 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 19595 while (psit.hasNext()) { 19596 PackageSetting ps = psit.next(); 19597 if (ps.pkg == null) { 19598 continue; 19599 } 19600 final String packageName = ps.pkg.packageName; 19601 // Skip over if system app 19602 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 19603 continue; 19604 } 19605 if (DEBUG_CLEAN_APKS) { 19606 Slog.i(TAG, "Checking package " + packageName); 19607 } 19608 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 19609 if (keep) { 19610 if (DEBUG_CLEAN_APKS) { 19611 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 19612 } 19613 } else { 19614 for (int i = 0; i < users.length; i++) { 19615 if (users[i] != userHandle && ps.getInstalled(users[i])) { 19616 keep = true; 19617 if (DEBUG_CLEAN_APKS) { 19618 Slog.i(TAG, " Keeping package " + packageName + " for user " 19619 + users[i]); 19620 } 19621 break; 19622 } 19623 } 19624 } 19625 if (!keep) { 19626 if (DEBUG_CLEAN_APKS) { 19627 Slog.i(TAG, " Removing package " + packageName); 19628 } 19629 mHandler.post(new Runnable() { 19630 public void run() { 19631 deletePackageX(packageName, userHandle, 0); 19632 } //end run 19633 }); 19634 } 19635 } 19636 } 19637 19638 /** Called by UserManagerService */ 19639 void createNewUser(int userHandle) { 19640 synchronized (mInstallLock) { 19641 mSettings.createNewUserLI(this, mInstaller, userHandle); 19642 } 19643 synchronized (mPackages) { 19644 applyFactoryDefaultBrowserLPw(userHandle); 19645 primeDomainVerificationsLPw(userHandle); 19646 } 19647 } 19648 19649 void newUserCreated(final int userHandle) { 19650 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 19651 // If permission review for legacy apps is required, we represent 19652 // dagerous permissions for such apps as always granted runtime 19653 // permissions to keep per user flag state whether review is needed. 19654 // Hence, if a new user is added we have to propagate dangerous 19655 // permission grants for these legacy apps. 19656 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 19657 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 19658 | UPDATE_PERMISSIONS_REPLACE_ALL); 19659 } 19660 } 19661 19662 @Override 19663 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 19664 mContext.enforceCallingOrSelfPermission( 19665 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 19666 "Only package verification agents can read the verifier device identity"); 19667 19668 synchronized (mPackages) { 19669 return mSettings.getVerifierDeviceIdentityLPw(); 19670 } 19671 } 19672 19673 @Override 19674 public void setPermissionEnforced(String permission, boolean enforced) { 19675 // TODO: Now that we no longer change GID for storage, this should to away. 19676 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 19677 "setPermissionEnforced"); 19678 if (READ_EXTERNAL_STORAGE.equals(permission)) { 19679 synchronized (mPackages) { 19680 if (mSettings.mReadExternalStorageEnforced == null 19681 || mSettings.mReadExternalStorageEnforced != enforced) { 19682 mSettings.mReadExternalStorageEnforced = enforced; 19683 mSettings.writeLPr(); 19684 } 19685 } 19686 // kill any non-foreground processes so we restart them and 19687 // grant/revoke the GID. 19688 final IActivityManager am = ActivityManagerNative.getDefault(); 19689 if (am != null) { 19690 final long token = Binder.clearCallingIdentity(); 19691 try { 19692 am.killProcessesBelowForeground("setPermissionEnforcement"); 19693 } catch (RemoteException e) { 19694 } finally { 19695 Binder.restoreCallingIdentity(token); 19696 } 19697 } 19698 } else { 19699 throw new IllegalArgumentException("No selective enforcement for " + permission); 19700 } 19701 } 19702 19703 @Override 19704 @Deprecated 19705 public boolean isPermissionEnforced(String permission) { 19706 return true; 19707 } 19708 19709 @Override 19710 public boolean isStorageLow() { 19711 final long token = Binder.clearCallingIdentity(); 19712 try { 19713 final DeviceStorageMonitorInternal 19714 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 19715 if (dsm != null) { 19716 return dsm.isMemoryLow(); 19717 } else { 19718 return false; 19719 } 19720 } finally { 19721 Binder.restoreCallingIdentity(token); 19722 } 19723 } 19724 19725 @Override 19726 public IPackageInstaller getPackageInstaller() { 19727 return mInstallerService; 19728 } 19729 19730 private boolean userNeedsBadging(int userId) { 19731 int index = mUserNeedsBadging.indexOfKey(userId); 19732 if (index < 0) { 19733 final UserInfo userInfo; 19734 final long token = Binder.clearCallingIdentity(); 19735 try { 19736 userInfo = sUserManager.getUserInfo(userId); 19737 } finally { 19738 Binder.restoreCallingIdentity(token); 19739 } 19740 final boolean b; 19741 if (userInfo != null && userInfo.isManagedProfile()) { 19742 b = true; 19743 } else { 19744 b = false; 19745 } 19746 mUserNeedsBadging.put(userId, b); 19747 return b; 19748 } 19749 return mUserNeedsBadging.valueAt(index); 19750 } 19751 19752 @Override 19753 public KeySet getKeySetByAlias(String packageName, String alias) { 19754 if (packageName == null || alias == null) { 19755 return null; 19756 } 19757 synchronized(mPackages) { 19758 final PackageParser.Package pkg = mPackages.get(packageName); 19759 if (pkg == null) { 19760 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19761 throw new IllegalArgumentException("Unknown package: " + packageName); 19762 } 19763 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19764 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 19765 } 19766 } 19767 19768 @Override 19769 public KeySet getSigningKeySet(String packageName) { 19770 if (packageName == null) { 19771 return null; 19772 } 19773 synchronized(mPackages) { 19774 final PackageParser.Package pkg = mPackages.get(packageName); 19775 if (pkg == null) { 19776 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19777 throw new IllegalArgumentException("Unknown package: " + packageName); 19778 } 19779 if (pkg.applicationInfo.uid != Binder.getCallingUid() 19780 && Process.SYSTEM_UID != Binder.getCallingUid()) { 19781 throw new SecurityException("May not access signing KeySet of other apps."); 19782 } 19783 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19784 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 19785 } 19786 } 19787 19788 @Override 19789 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 19790 if (packageName == null || ks == null) { 19791 return false; 19792 } 19793 synchronized(mPackages) { 19794 final PackageParser.Package pkg = mPackages.get(packageName); 19795 if (pkg == null) { 19796 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19797 throw new IllegalArgumentException("Unknown package: " + packageName); 19798 } 19799 IBinder ksh = ks.getToken(); 19800 if (ksh instanceof KeySetHandle) { 19801 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19802 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 19803 } 19804 return false; 19805 } 19806 } 19807 19808 @Override 19809 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 19810 if (packageName == null || ks == null) { 19811 return false; 19812 } 19813 synchronized(mPackages) { 19814 final PackageParser.Package pkg = mPackages.get(packageName); 19815 if (pkg == null) { 19816 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19817 throw new IllegalArgumentException("Unknown package: " + packageName); 19818 } 19819 IBinder ksh = ks.getToken(); 19820 if (ksh instanceof KeySetHandle) { 19821 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19822 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 19823 } 19824 return false; 19825 } 19826 } 19827 19828 private void deletePackageIfUnusedLPr(final String packageName) { 19829 PackageSetting ps = mSettings.mPackages.get(packageName); 19830 if (ps == null) { 19831 return; 19832 } 19833 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 19834 // TODO Implement atomic delete if package is unused 19835 // It is currently possible that the package will be deleted even if it is installed 19836 // after this method returns. 19837 mHandler.post(new Runnable() { 19838 public void run() { 19839 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 19840 } 19841 }); 19842 } 19843 } 19844 19845 /** 19846 * Check and throw if the given before/after packages would be considered a 19847 * downgrade. 19848 */ 19849 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 19850 throws PackageManagerException { 19851 if (after.versionCode < before.mVersionCode) { 19852 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 19853 "Update version code " + after.versionCode + " is older than current " 19854 + before.mVersionCode); 19855 } else if (after.versionCode == before.mVersionCode) { 19856 if (after.baseRevisionCode < before.baseRevisionCode) { 19857 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 19858 "Update base revision code " + after.baseRevisionCode 19859 + " is older than current " + before.baseRevisionCode); 19860 } 19861 19862 if (!ArrayUtils.isEmpty(after.splitNames)) { 19863 for (int i = 0; i < after.splitNames.length; i++) { 19864 final String splitName = after.splitNames[i]; 19865 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 19866 if (j != -1) { 19867 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 19868 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 19869 "Update split " + splitName + " revision code " 19870 + after.splitRevisionCodes[i] + " is older than current " 19871 + before.splitRevisionCodes[j]); 19872 } 19873 } 19874 } 19875 } 19876 } 19877 } 19878 19879 private static class MoveCallbacks extends Handler { 19880 private static final int MSG_CREATED = 1; 19881 private static final int MSG_STATUS_CHANGED = 2; 19882 19883 private final RemoteCallbackList<IPackageMoveObserver> 19884 mCallbacks = new RemoteCallbackList<>(); 19885 19886 private final SparseIntArray mLastStatus = new SparseIntArray(); 19887 19888 public MoveCallbacks(Looper looper) { 19889 super(looper); 19890 } 19891 19892 public void register(IPackageMoveObserver callback) { 19893 mCallbacks.register(callback); 19894 } 19895 19896 public void unregister(IPackageMoveObserver callback) { 19897 mCallbacks.unregister(callback); 19898 } 19899 19900 @Override 19901 public void handleMessage(Message msg) { 19902 final SomeArgs args = (SomeArgs) msg.obj; 19903 final int n = mCallbacks.beginBroadcast(); 19904 for (int i = 0; i < n; i++) { 19905 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 19906 try { 19907 invokeCallback(callback, msg.what, args); 19908 } catch (RemoteException ignored) { 19909 } 19910 } 19911 mCallbacks.finishBroadcast(); 19912 args.recycle(); 19913 } 19914 19915 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 19916 throws RemoteException { 19917 switch (what) { 19918 case MSG_CREATED: { 19919 callback.onCreated(args.argi1, (Bundle) args.arg2); 19920 break; 19921 } 19922 case MSG_STATUS_CHANGED: { 19923 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 19924 break; 19925 } 19926 } 19927 } 19928 19929 private void notifyCreated(int moveId, Bundle extras) { 19930 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 19931 19932 final SomeArgs args = SomeArgs.obtain(); 19933 args.argi1 = moveId; 19934 args.arg2 = extras; 19935 obtainMessage(MSG_CREATED, args).sendToTarget(); 19936 } 19937 19938 private void notifyStatusChanged(int moveId, int status) { 19939 notifyStatusChanged(moveId, status, -1); 19940 } 19941 19942 private void notifyStatusChanged(int moveId, int status, long estMillis) { 19943 Slog.v(TAG, "Move " + moveId + " status " + status); 19944 19945 final SomeArgs args = SomeArgs.obtain(); 19946 args.argi1 = moveId; 19947 args.argi2 = status; 19948 args.arg3 = estMillis; 19949 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 19950 19951 synchronized (mLastStatus) { 19952 mLastStatus.put(moveId, status); 19953 } 19954 } 19955 } 19956 19957 private final static class OnPermissionChangeListeners extends Handler { 19958 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 19959 19960 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 19961 new RemoteCallbackList<>(); 19962 19963 public OnPermissionChangeListeners(Looper looper) { 19964 super(looper); 19965 } 19966 19967 @Override 19968 public void handleMessage(Message msg) { 19969 switch (msg.what) { 19970 case MSG_ON_PERMISSIONS_CHANGED: { 19971 final int uid = msg.arg1; 19972 handleOnPermissionsChanged(uid); 19973 } break; 19974 } 19975 } 19976 19977 public void addListenerLocked(IOnPermissionsChangeListener listener) { 19978 mPermissionListeners.register(listener); 19979 19980 } 19981 19982 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 19983 mPermissionListeners.unregister(listener); 19984 } 19985 19986 public void onPermissionsChanged(int uid) { 19987 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 19988 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 19989 } 19990 } 19991 19992 private void handleOnPermissionsChanged(int uid) { 19993 final int count = mPermissionListeners.beginBroadcast(); 19994 try { 19995 for (int i = 0; i < count; i++) { 19996 IOnPermissionsChangeListener callback = mPermissionListeners 19997 .getBroadcastItem(i); 19998 try { 19999 callback.onPermissionsChanged(uid); 20000 } catch (RemoteException e) { 20001 Log.e(TAG, "Permission listener is dead", e); 20002 } 20003 } 20004 } finally { 20005 mPermissionListeners.finishBroadcast(); 20006 } 20007 } 20008 } 20009 20010 private class PackageManagerInternalImpl extends PackageManagerInternal { 20011 @Override 20012 public void setLocationPackagesProvider(PackagesProvider provider) { 20013 synchronized (mPackages) { 20014 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 20015 } 20016 } 20017 20018 @Override 20019 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 20020 synchronized (mPackages) { 20021 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 20022 } 20023 } 20024 20025 @Override 20026 public void setSmsAppPackagesProvider(PackagesProvider provider) { 20027 synchronized (mPackages) { 20028 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 20029 } 20030 } 20031 20032 @Override 20033 public void setDialerAppPackagesProvider(PackagesProvider provider) { 20034 synchronized (mPackages) { 20035 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 20036 } 20037 } 20038 20039 @Override 20040 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 20041 synchronized (mPackages) { 20042 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 20043 } 20044 } 20045 20046 @Override 20047 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 20048 synchronized (mPackages) { 20049 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 20050 } 20051 } 20052 20053 @Override 20054 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 20055 synchronized (mPackages) { 20056 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 20057 packageName, userId); 20058 } 20059 } 20060 20061 @Override 20062 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 20063 synchronized (mPackages) { 20064 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 20065 packageName, userId); 20066 } 20067 } 20068 20069 @Override 20070 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 20071 synchronized (mPackages) { 20072 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 20073 packageName, userId); 20074 } 20075 } 20076 20077 @Override 20078 public void setKeepUninstalledPackages(final List<String> packageList) { 20079 Preconditions.checkNotNull(packageList); 20080 List<String> removedFromList = null; 20081 synchronized (mPackages) { 20082 if (mKeepUninstalledPackages != null) { 20083 final int packagesCount = mKeepUninstalledPackages.size(); 20084 for (int i = 0; i < packagesCount; i++) { 20085 String oldPackage = mKeepUninstalledPackages.get(i); 20086 if (packageList != null && packageList.contains(oldPackage)) { 20087 continue; 20088 } 20089 if (removedFromList == null) { 20090 removedFromList = new ArrayList<>(); 20091 } 20092 removedFromList.add(oldPackage); 20093 } 20094 } 20095 mKeepUninstalledPackages = new ArrayList<>(packageList); 20096 if (removedFromList != null) { 20097 final int removedCount = removedFromList.size(); 20098 for (int i = 0; i < removedCount; i++) { 20099 deletePackageIfUnusedLPr(removedFromList.get(i)); 20100 } 20101 } 20102 } 20103 } 20104 20105 @Override 20106 public boolean isPermissionsReviewRequired(String packageName, int userId) { 20107 synchronized (mPackages) { 20108 // If we do not support permission review, done. 20109 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 20110 return false; 20111 } 20112 20113 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 20114 if (packageSetting == null) { 20115 return false; 20116 } 20117 20118 // Permission review applies only to apps not supporting the new permission model. 20119 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 20120 return false; 20121 } 20122 20123 // Legacy apps have the permission and get user consent on launch. 20124 PermissionsState permissionsState = packageSetting.getPermissionsState(); 20125 return permissionsState.isPermissionReviewRequired(userId); 20126 } 20127 } 20128 20129 @Override 20130 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 20131 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 20132 } 20133 20134 @Override 20135 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 20136 int userId) { 20137 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 20138 } 20139 } 20140 20141 @Override 20142 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 20143 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 20144 synchronized (mPackages) { 20145 final long identity = Binder.clearCallingIdentity(); 20146 try { 20147 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 20148 packageNames, userId); 20149 } finally { 20150 Binder.restoreCallingIdentity(identity); 20151 } 20152 } 20153 } 20154 20155 private static void enforceSystemOrPhoneCaller(String tag) { 20156 int callingUid = Binder.getCallingUid(); 20157 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 20158 throw new SecurityException( 20159 "Cannot call " + tag + " from UID " + callingUid); 20160 } 20161 } 20162 20163 boolean isHistoricalPackageUsageAvailable() { 20164 return mPackageUsage.isHistoricalPackageUsageAvailable(); 20165 } 20166 20167 /** 20168 * Return a <b>copy</b> of the collection of packages known to the package manager. 20169 * @return A copy of the values of mPackages. 20170 */ 20171 Collection<PackageParser.Package> getPackages() { 20172 synchronized (mPackages) { 20173 return new ArrayList<>(mPackages.values()); 20174 } 20175 } 20176 20177 /** 20178 * Logs process start information (including base APK hash) to the security log. 20179 * @hide 20180 */ 20181 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 20182 String apkFile, int pid) { 20183 if (!SecurityLog.isLoggingEnabled()) { 20184 return; 20185 } 20186 Bundle data = new Bundle(); 20187 data.putLong("startTimestamp", System.currentTimeMillis()); 20188 data.putString("processName", processName); 20189 data.putInt("uid", uid); 20190 data.putString("seinfo", seinfo); 20191 data.putString("apkFile", apkFile); 20192 data.putInt("pid", pid); 20193 Message msg = mProcessLoggingHandler.obtainMessage( 20194 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 20195 msg.setData(data); 20196 mProcessLoggingHandler.sendMessage(msg); 20197 } 20198} 20199