PackageManagerService.java revision 6d99f796711882ba60977c211d0f92252fe7ad4a
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.UserManagerInternal; 193import android.os.storage.IMountService; 194import android.os.storage.MountServiceInternal; 195import android.os.storage.StorageEventListener; 196import android.os.storage.StorageManager; 197import android.os.storage.VolumeInfo; 198import android.os.storage.VolumeRecord; 199import android.security.KeyStore; 200import android.security.SystemKeyStore; 201import android.system.ErrnoException; 202import android.system.Os; 203import android.text.TextUtils; 204import android.text.format.DateUtils; 205import android.util.ArrayMap; 206import android.util.ArraySet; 207import android.util.AtomicFile; 208import android.util.DisplayMetrics; 209import android.util.EventLog; 210import android.util.ExceptionUtils; 211import android.util.Log; 212import android.util.LogPrinter; 213import android.util.MathUtils; 214import android.util.PrintStreamPrinter; 215import android.util.Slog; 216import android.util.SparseArray; 217import android.util.SparseBooleanArray; 218import android.util.SparseIntArray; 219import android.util.Xml; 220import android.util.jar.StrictJarFile; 221import android.view.Display; 222 223import com.android.internal.R; 224import com.android.internal.annotations.GuardedBy; 225import com.android.internal.app.IMediaContainerService; 226import com.android.internal.app.ResolverActivity; 227import com.android.internal.content.NativeLibraryHelper; 228import com.android.internal.content.PackageHelper; 229import com.android.internal.logging.MetricsLogger; 230import com.android.internal.os.IParcelFileDescriptorFactory; 231import com.android.internal.os.InstallerConnection.InstallerException; 232import com.android.internal.os.SomeArgs; 233import com.android.internal.os.Zygote; 234import com.android.internal.telephony.CarrierAppUtils; 235import com.android.internal.util.ArrayUtils; 236import com.android.internal.util.FastPrintWriter; 237import com.android.internal.util.FastXmlSerializer; 238import com.android.internal.util.IndentingPrintWriter; 239import com.android.internal.util.Preconditions; 240import com.android.internal.util.XmlUtils; 241import com.android.server.EventLogTags; 242import com.android.server.FgThread; 243import com.android.server.IntentResolver; 244import com.android.server.LocalServices; 245import com.android.server.ServiceThread; 246import com.android.server.SystemConfig; 247import com.android.server.Watchdog; 248import com.android.server.net.NetworkPolicyManagerInternal; 249import com.android.server.pm.PermissionsState.PermissionState; 250import com.android.server.pm.Settings.DatabaseVersion; 251import com.android.server.pm.Settings.VersionInfo; 252import com.android.server.storage.DeviceStorageMonitorInternal; 253 254import dalvik.system.CloseGuard; 255import dalvik.system.DexFile; 256import dalvik.system.VMRuntime; 257 258import libcore.io.IoUtils; 259import libcore.util.EmptyArray; 260 261import org.xmlpull.v1.XmlPullParser; 262import org.xmlpull.v1.XmlPullParserException; 263import org.xmlpull.v1.XmlSerializer; 264 265import java.io.BufferedInputStream; 266import java.io.BufferedOutputStream; 267import java.io.BufferedReader; 268import java.io.ByteArrayInputStream; 269import java.io.ByteArrayOutputStream; 270import java.io.File; 271import java.io.FileDescriptor; 272import java.io.FileInputStream; 273import java.io.FileNotFoundException; 274import java.io.FileOutputStream; 275import java.io.FileReader; 276import java.io.FilenameFilter; 277import java.io.IOException; 278import java.io.InputStream; 279import java.io.PrintWriter; 280import java.nio.charset.StandardCharsets; 281import java.security.DigestInputStream; 282import java.security.MessageDigest; 283import java.security.NoSuchAlgorithmException; 284import java.security.PublicKey; 285import java.security.cert.Certificate; 286import java.security.cert.CertificateEncodingException; 287import java.security.cert.CertificateException; 288import java.text.SimpleDateFormat; 289import java.util.ArrayList; 290import java.util.Arrays; 291import java.util.Collection; 292import java.util.Collections; 293import java.util.Comparator; 294import java.util.Date; 295import java.util.HashSet; 296import java.util.Iterator; 297import java.util.List; 298import java.util.Map; 299import java.util.Objects; 300import java.util.Set; 301import java.util.concurrent.CountDownLatch; 302import java.util.concurrent.TimeUnit; 303import java.util.concurrent.atomic.AtomicBoolean; 304import java.util.concurrent.atomic.AtomicInteger; 305import java.util.concurrent.atomic.AtomicLong; 306 307/** 308 * Keep track of all those APKs everywhere. 309 * <p> 310 * Internally there are two important locks: 311 * <ul> 312 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 313 * and other related state. It is a fine-grained lock that should only be held 314 * momentarily, as it's one of the most contended locks in the system. 315 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 316 * operations typically involve heavy lifting of application data on disk. Since 317 * {@code installd} is single-threaded, and it's operations can often be slow, 318 * this lock should never be acquired while already holding {@link #mPackages}. 319 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 320 * holding {@link #mInstallLock}. 321 * </ul> 322 * Many internal methods rely on the caller to hold the appropriate locks, and 323 * this contract is expressed through method name suffixes: 324 * <ul> 325 * <li>fooLI(): the caller must hold {@link #mInstallLock} 326 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 327 * being modified must be frozen 328 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 329 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 330 * </ul> 331 * <p> 332 * Because this class is very central to the platform's security; please run all 333 * CTS and unit tests whenever making modifications: 334 * 335 * <pre> 336 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 337 * $ cts-tradefed run commandAndExit cts -m AppSecurityTests 338 * </pre> 339 */ 340public class PackageManagerService extends IPackageManager.Stub { 341 static final String TAG = "PackageManager"; 342 static final boolean DEBUG_SETTINGS = false; 343 static final boolean DEBUG_PREFERRED = false; 344 static final boolean DEBUG_UPGRADE = false; 345 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 346 private static final boolean DEBUG_BACKUP = false; 347 private static final boolean DEBUG_INSTALL = false; 348 private static final boolean DEBUG_REMOVE = false; 349 private static final boolean DEBUG_BROADCASTS = false; 350 private static final boolean DEBUG_SHOW_INFO = false; 351 private static final boolean DEBUG_PACKAGE_INFO = false; 352 private static final boolean DEBUG_INTENT_MATCHING = false; 353 private static final boolean DEBUG_PACKAGE_SCANNING = false; 354 private static final boolean DEBUG_VERIFY = false; 355 private static final boolean DEBUG_FILTERS = false; 356 357 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 358 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 359 // user, but by default initialize to this. 360 static final boolean DEBUG_DEXOPT = false; 361 362 private static final boolean DEBUG_ABI_SELECTION = false; 363 private static final boolean DEBUG_EPHEMERAL = false; 364 private static final boolean DEBUG_TRIAGED_MISSING = false; 365 private static final boolean DEBUG_APP_DATA = false; 366 367 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 368 369 private static final boolean DISABLE_EPHEMERAL_APPS = true; 370 371 private static final int RADIO_UID = Process.PHONE_UID; 372 private static final int LOG_UID = Process.LOG_UID; 373 private static final int NFC_UID = Process.NFC_UID; 374 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 375 private static final int SHELL_UID = Process.SHELL_UID; 376 377 // Cap the size of permission trees that 3rd party apps can define 378 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 379 380 // Suffix used during package installation when copying/moving 381 // package apks to install directory. 382 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 383 384 static final int SCAN_NO_DEX = 1<<1; 385 static final int SCAN_FORCE_DEX = 1<<2; 386 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 387 static final int SCAN_NEW_INSTALL = 1<<4; 388 static final int SCAN_NO_PATHS = 1<<5; 389 static final int SCAN_UPDATE_TIME = 1<<6; 390 static final int SCAN_DEFER_DEX = 1<<7; 391 static final int SCAN_BOOTING = 1<<8; 392 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 393 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 394 static final int SCAN_REPLACING = 1<<11; 395 static final int SCAN_REQUIRE_KNOWN = 1<<12; 396 static final int SCAN_MOVE = 1<<13; 397 static final int SCAN_INITIAL = 1<<14; 398 static final int SCAN_CHECK_ONLY = 1<<15; 399 static final int SCAN_DONT_KILL_APP = 1<<17; 400 static final int SCAN_IGNORE_FROZEN = 1<<18; 401 402 static final int REMOVE_CHATTY = 1<<16; 403 404 private static final int[] EMPTY_INT_ARRAY = new int[0]; 405 406 /** 407 * Timeout (in milliseconds) after which the watchdog should declare that 408 * our handler thread is wedged. The usual default for such things is one 409 * minute but we sometimes do very lengthy I/O operations on this thread, 410 * such as installing multi-gigabyte applications, so ours needs to be longer. 411 */ 412 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 413 414 /** 415 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 416 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 417 * settings entry if available, otherwise we use the hardcoded default. If it's been 418 * more than this long since the last fstrim, we force one during the boot sequence. 419 * 420 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 421 * one gets run at the next available charging+idle time. This final mandatory 422 * no-fstrim check kicks in only of the other scheduling criteria is never met. 423 */ 424 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 425 426 /** 427 * Whether verification is enabled by default. 428 */ 429 private static final boolean DEFAULT_VERIFY_ENABLE = true; 430 431 /** 432 * The default maximum time to wait for the verification agent to return in 433 * milliseconds. 434 */ 435 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 436 437 /** 438 * The default response for package verification timeout. 439 * 440 * This can be either PackageManager.VERIFICATION_ALLOW or 441 * PackageManager.VERIFICATION_REJECT. 442 */ 443 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 444 445 static final String PLATFORM_PACKAGE_NAME = "android"; 446 447 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 448 449 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 450 DEFAULT_CONTAINER_PACKAGE, 451 "com.android.defcontainer.DefaultContainerService"); 452 453 private static final String KILL_APP_REASON_GIDS_CHANGED = 454 "permission grant or revoke changed gids"; 455 456 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 457 "permissions revoked"; 458 459 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 460 461 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 462 463 /** Permission grant: not grant the permission. */ 464 private static final int GRANT_DENIED = 1; 465 466 /** Permission grant: grant the permission as an install permission. */ 467 private static final int GRANT_INSTALL = 2; 468 469 /** Permission grant: grant the permission as a runtime one. */ 470 private static final int GRANT_RUNTIME = 3; 471 472 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 473 private static final int GRANT_UPGRADE = 4; 474 475 /** Canonical intent used to identify what counts as a "web browser" app */ 476 private static final Intent sBrowserIntent; 477 static { 478 sBrowserIntent = new Intent(); 479 sBrowserIntent.setAction(Intent.ACTION_VIEW); 480 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 481 sBrowserIntent.setData(Uri.parse("http:")); 482 } 483 484 /** 485 * The set of all protected actions [i.e. those actions for which a high priority 486 * intent filter is disallowed]. 487 */ 488 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 489 static { 490 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 491 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 492 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 493 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 494 } 495 496 // Compilation reasons. 497 public static final int REASON_FIRST_BOOT = 0; 498 public static final int REASON_BOOT = 1; 499 public static final int REASON_INSTALL = 2; 500 public static final int REASON_BACKGROUND_DEXOPT = 3; 501 public static final int REASON_AB_OTA = 4; 502 public static final int REASON_NON_SYSTEM_LIBRARY = 5; 503 public static final int REASON_SHARED_APK = 6; 504 public static final int REASON_FORCED_DEXOPT = 7; 505 506 public static final int REASON_LAST = REASON_FORCED_DEXOPT; 507 508 /** Special library name that skips shared libraries check during compilation. */ 509 private static final String SKIP_SHARED_LIBRARY_CHECK = "&"; 510 511 final ServiceThread mHandlerThread; 512 513 final PackageHandler mHandler; 514 515 private final ProcessLoggingHandler mProcessLoggingHandler; 516 517 /** 518 * Messages for {@link #mHandler} that need to wait for system ready before 519 * being dispatched. 520 */ 521 private ArrayList<Message> mPostSystemReadyMessages; 522 523 final int mSdkVersion = Build.VERSION.SDK_INT; 524 525 final Context mContext; 526 final boolean mFactoryTest; 527 final boolean mOnlyCore; 528 final DisplayMetrics mMetrics; 529 final int mDefParseFlags; 530 final String[] mSeparateProcesses; 531 final boolean mIsUpgrade; 532 final boolean mIsPreNUpgrade; 533 534 /** The location for ASEC container files on internal storage. */ 535 final String mAsecInternalPath; 536 537 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 538 // LOCK HELD. Can be called with mInstallLock held. 539 @GuardedBy("mInstallLock") 540 final Installer mInstaller; 541 542 /** Directory where installed third-party apps stored */ 543 final File mAppInstallDir; 544 final File mEphemeralInstallDir; 545 546 /** 547 * Directory to which applications installed internally have their 548 * 32 bit native libraries copied. 549 */ 550 private File mAppLib32InstallDir; 551 552 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 553 // apps. 554 final File mDrmAppPrivateInstallDir; 555 556 // ---------------------------------------------------------------- 557 558 // Lock for state used when installing and doing other long running 559 // operations. Methods that must be called with this lock held have 560 // the suffix "LI". 561 final Object mInstallLock = new Object(); 562 563 // ---------------------------------------------------------------- 564 565 // Keys are String (package name), values are Package. This also serves 566 // as the lock for the global state. Methods that must be called with 567 // this lock held have the prefix "LP". 568 @GuardedBy("mPackages") 569 final ArrayMap<String, PackageParser.Package> mPackages = 570 new ArrayMap<String, PackageParser.Package>(); 571 572 final ArrayMap<String, Set<String>> mKnownCodebase = 573 new ArrayMap<String, Set<String>>(); 574 575 // Tracks available target package names -> overlay package paths. 576 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 577 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 578 579 /** 580 * Tracks new system packages [received in an OTA] that we expect to 581 * find updated user-installed versions. Keys are package name, values 582 * are package location. 583 */ 584 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 585 /** 586 * Tracks high priority intent filters for protected actions. During boot, certain 587 * filter actions are protected and should never be allowed to have a high priority 588 * intent filter for them. However, there is one, and only one exception -- the 589 * setup wizard. It must be able to define a high priority intent filter for these 590 * actions to ensure there are no escapes from the wizard. We need to delay processing 591 * of these during boot as we need to look at all of the system packages in order 592 * to know which component is the setup wizard. 593 */ 594 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 595 /** 596 * Whether or not processing protected filters should be deferred. 597 */ 598 private boolean mDeferProtectedFilters = true; 599 600 /** 601 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 602 */ 603 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 604 /** 605 * Whether or not system app permissions should be promoted from install to runtime. 606 */ 607 boolean mPromoteSystemApps; 608 609 @GuardedBy("mPackages") 610 final Settings mSettings; 611 612 /** 613 * Set of package names that are currently "frozen", which means active 614 * surgery is being done on the code/data for that package. The platform 615 * will refuse to launch frozen packages to avoid race conditions. 616 * 617 * @see PackageFreezer 618 */ 619 @GuardedBy("mPackages") 620 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 621 622 boolean mRestoredSettings; 623 624 // System configuration read by SystemConfig. 625 final int[] mGlobalGids; 626 final SparseArray<ArraySet<String>> mSystemPermissions; 627 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 628 629 // If mac_permissions.xml was found for seinfo labeling. 630 boolean mFoundPolicyFile; 631 632 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 633 634 public static final class SharedLibraryEntry { 635 public final String path; 636 public final String apk; 637 638 SharedLibraryEntry(String _path, String _apk) { 639 path = _path; 640 apk = _apk; 641 } 642 } 643 644 // Currently known shared libraries. 645 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 646 new ArrayMap<String, SharedLibraryEntry>(); 647 648 // All available activities, for your resolving pleasure. 649 final ActivityIntentResolver mActivities = 650 new ActivityIntentResolver(); 651 652 // All available receivers, for your resolving pleasure. 653 final ActivityIntentResolver mReceivers = 654 new ActivityIntentResolver(); 655 656 // All available services, for your resolving pleasure. 657 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 658 659 // All available providers, for your resolving pleasure. 660 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 661 662 // Mapping from provider base names (first directory in content URI codePath) 663 // to the provider information. 664 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 665 new ArrayMap<String, PackageParser.Provider>(); 666 667 // Mapping from instrumentation class names to info about them. 668 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 669 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 670 671 // Mapping from permission names to info about them. 672 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 673 new ArrayMap<String, PackageParser.PermissionGroup>(); 674 675 // Packages whose data we have transfered into another package, thus 676 // should no longer exist. 677 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 678 679 // Broadcast actions that are only available to the system. 680 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 681 682 /** List of packages waiting for verification. */ 683 final SparseArray<PackageVerificationState> mPendingVerification 684 = new SparseArray<PackageVerificationState>(); 685 686 /** Set of packages associated with each app op permission. */ 687 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 688 689 final PackageInstallerService mInstallerService; 690 691 private final PackageDexOptimizer mPackageDexOptimizer; 692 693 private AtomicInteger mNextMoveId = new AtomicInteger(); 694 private final MoveCallbacks mMoveCallbacks; 695 696 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 697 698 // Cache of users who need badging. 699 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 700 701 /** Token for keys in mPendingVerification. */ 702 private int mPendingVerificationToken = 0; 703 704 volatile boolean mSystemReady; 705 volatile boolean mSafeMode; 706 volatile boolean mHasSystemUidErrors; 707 708 ApplicationInfo mAndroidApplication; 709 final ActivityInfo mResolveActivity = new ActivityInfo(); 710 final ResolveInfo mResolveInfo = new ResolveInfo(); 711 ComponentName mResolveComponentName; 712 PackageParser.Package mPlatformPackage; 713 ComponentName mCustomResolverComponentName; 714 715 boolean mResolverReplaced = false; 716 717 private final @Nullable ComponentName mIntentFilterVerifierComponent; 718 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 719 720 private int mIntentFilterVerificationToken = 0; 721 722 /** Component that knows whether or not an ephemeral application exists */ 723 final ComponentName mEphemeralResolverComponent; 724 /** The service connection to the ephemeral resolver */ 725 final EphemeralResolverConnection mEphemeralResolverConnection; 726 727 /** Component used to install ephemeral applications */ 728 final ComponentName mEphemeralInstallerComponent; 729 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 730 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 731 732 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 733 = new SparseArray<IntentFilterVerificationState>(); 734 735 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 736 new DefaultPermissionGrantPolicy(this); 737 738 // List of packages names to keep cached, even if they are uninstalled for all users 739 private List<String> mKeepUninstalledPackages; 740 741 private UserManagerInternal mUserManagerInternal; 742 743 private static class IFVerificationParams { 744 PackageParser.Package pkg; 745 boolean replacing; 746 int userId; 747 int verifierUid; 748 749 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 750 int _userId, int _verifierUid) { 751 pkg = _pkg; 752 replacing = _replacing; 753 userId = _userId; 754 replacing = _replacing; 755 verifierUid = _verifierUid; 756 } 757 } 758 759 private interface IntentFilterVerifier<T extends IntentFilter> { 760 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 761 T filter, String packageName); 762 void startVerifications(int userId); 763 void receiveVerificationResponse(int verificationId); 764 } 765 766 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 767 private Context mContext; 768 private ComponentName mIntentFilterVerifierComponent; 769 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 770 771 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 772 mContext = context; 773 mIntentFilterVerifierComponent = verifierComponent; 774 } 775 776 private String getDefaultScheme() { 777 return IntentFilter.SCHEME_HTTPS; 778 } 779 780 @Override 781 public void startVerifications(int userId) { 782 // Launch verifications requests 783 int count = mCurrentIntentFilterVerifications.size(); 784 for (int n=0; n<count; n++) { 785 int verificationId = mCurrentIntentFilterVerifications.get(n); 786 final IntentFilterVerificationState ivs = 787 mIntentFilterVerificationStates.get(verificationId); 788 789 String packageName = ivs.getPackageName(); 790 791 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 792 final int filterCount = filters.size(); 793 ArraySet<String> domainsSet = new ArraySet<>(); 794 for (int m=0; m<filterCount; m++) { 795 PackageParser.ActivityIntentInfo filter = filters.get(m); 796 domainsSet.addAll(filter.getHostsList()); 797 } 798 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 799 synchronized (mPackages) { 800 if (mSettings.createIntentFilterVerificationIfNeededLPw( 801 packageName, domainsList) != null) { 802 scheduleWriteSettingsLocked(); 803 } 804 } 805 sendVerificationRequest(userId, verificationId, ivs); 806 } 807 mCurrentIntentFilterVerifications.clear(); 808 } 809 810 private void sendVerificationRequest(int userId, int verificationId, 811 IntentFilterVerificationState ivs) { 812 813 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 814 verificationIntent.putExtra( 815 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 816 verificationId); 817 verificationIntent.putExtra( 818 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 819 getDefaultScheme()); 820 verificationIntent.putExtra( 821 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 822 ivs.getHostsString()); 823 verificationIntent.putExtra( 824 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 825 ivs.getPackageName()); 826 verificationIntent.setComponent(mIntentFilterVerifierComponent); 827 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 828 829 UserHandle user = new UserHandle(userId); 830 mContext.sendBroadcastAsUser(verificationIntent, user); 831 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 832 "Sending IntentFilter verification broadcast"); 833 } 834 835 public void receiveVerificationResponse(int verificationId) { 836 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 837 838 final boolean verified = ivs.isVerified(); 839 840 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 841 final int count = filters.size(); 842 if (DEBUG_DOMAIN_VERIFICATION) { 843 Slog.i(TAG, "Received verification response " + verificationId 844 + " for " + count + " filters, verified=" + verified); 845 } 846 for (int n=0; n<count; n++) { 847 PackageParser.ActivityIntentInfo filter = filters.get(n); 848 filter.setVerified(verified); 849 850 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 851 + " verified with result:" + verified + " and hosts:" 852 + ivs.getHostsString()); 853 } 854 855 mIntentFilterVerificationStates.remove(verificationId); 856 857 final String packageName = ivs.getPackageName(); 858 IntentFilterVerificationInfo ivi = null; 859 860 synchronized (mPackages) { 861 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 862 } 863 if (ivi == null) { 864 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 865 + verificationId + " packageName:" + packageName); 866 return; 867 } 868 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 869 "Updating IntentFilterVerificationInfo for package " + packageName 870 +" verificationId:" + verificationId); 871 872 synchronized (mPackages) { 873 if (verified) { 874 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 875 } else { 876 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 877 } 878 scheduleWriteSettingsLocked(); 879 880 final int userId = ivs.getUserId(); 881 if (userId != UserHandle.USER_ALL) { 882 final int userStatus = 883 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 884 885 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 886 boolean needUpdate = false; 887 888 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 889 // already been set by the User thru the Disambiguation dialog 890 switch (userStatus) { 891 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 892 if (verified) { 893 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 894 } else { 895 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 896 } 897 needUpdate = true; 898 break; 899 900 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 901 if (verified) { 902 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 903 needUpdate = true; 904 } 905 break; 906 907 default: 908 // Nothing to do 909 } 910 911 if (needUpdate) { 912 mSettings.updateIntentFilterVerificationStatusLPw( 913 packageName, updatedStatus, userId); 914 scheduleWritePackageRestrictionsLocked(userId); 915 } 916 } 917 } 918 } 919 920 @Override 921 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 922 ActivityIntentInfo filter, String packageName) { 923 if (!hasValidDomains(filter)) { 924 return false; 925 } 926 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 927 if (ivs == null) { 928 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 929 packageName); 930 } 931 if (DEBUG_DOMAIN_VERIFICATION) { 932 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 933 } 934 ivs.addFilter(filter); 935 return true; 936 } 937 938 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 939 int userId, int verificationId, String packageName) { 940 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 941 verifierUid, userId, packageName); 942 ivs.setPendingState(); 943 synchronized (mPackages) { 944 mIntentFilterVerificationStates.append(verificationId, ivs); 945 mCurrentIntentFilterVerifications.add(verificationId); 946 } 947 return ivs; 948 } 949 } 950 951 private static boolean hasValidDomains(ActivityIntentInfo filter) { 952 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 953 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 954 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 955 } 956 957 // Set of pending broadcasts for aggregating enable/disable of components. 958 static class PendingPackageBroadcasts { 959 // for each user id, a map of <package name -> components within that package> 960 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 961 962 public PendingPackageBroadcasts() { 963 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 964 } 965 966 public ArrayList<String> get(int userId, String packageName) { 967 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 968 return packages.get(packageName); 969 } 970 971 public void put(int userId, String packageName, ArrayList<String> components) { 972 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 973 packages.put(packageName, components); 974 } 975 976 public void remove(int userId, String packageName) { 977 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 978 if (packages != null) { 979 packages.remove(packageName); 980 } 981 } 982 983 public void remove(int userId) { 984 mUidMap.remove(userId); 985 } 986 987 public int userIdCount() { 988 return mUidMap.size(); 989 } 990 991 public int userIdAt(int n) { 992 return mUidMap.keyAt(n); 993 } 994 995 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 996 return mUidMap.get(userId); 997 } 998 999 public int size() { 1000 // total number of pending broadcast entries across all userIds 1001 int num = 0; 1002 for (int i = 0; i< mUidMap.size(); i++) { 1003 num += mUidMap.valueAt(i).size(); 1004 } 1005 return num; 1006 } 1007 1008 public void clear() { 1009 mUidMap.clear(); 1010 } 1011 1012 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1013 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1014 if (map == null) { 1015 map = new ArrayMap<String, ArrayList<String>>(); 1016 mUidMap.put(userId, map); 1017 } 1018 return map; 1019 } 1020 } 1021 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1022 1023 // Service Connection to remote media container service to copy 1024 // package uri's from external media onto secure containers 1025 // or internal storage. 1026 private IMediaContainerService mContainerService = null; 1027 1028 static final int SEND_PENDING_BROADCAST = 1; 1029 static final int MCS_BOUND = 3; 1030 static final int END_COPY = 4; 1031 static final int INIT_COPY = 5; 1032 static final int MCS_UNBIND = 6; 1033 static final int START_CLEANING_PACKAGE = 7; 1034 static final int FIND_INSTALL_LOC = 8; 1035 static final int POST_INSTALL = 9; 1036 static final int MCS_RECONNECT = 10; 1037 static final int MCS_GIVE_UP = 11; 1038 static final int UPDATED_MEDIA_STATUS = 12; 1039 static final int WRITE_SETTINGS = 13; 1040 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1041 static final int PACKAGE_VERIFIED = 15; 1042 static final int CHECK_PENDING_VERIFICATION = 16; 1043 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1044 static final int INTENT_FILTER_VERIFIED = 18; 1045 static final int WRITE_PACKAGE_LIST = 19; 1046 1047 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1048 1049 // Delay time in millisecs 1050 static final int BROADCAST_DELAY = 10 * 1000; 1051 1052 static UserManagerService sUserManager; 1053 1054 // Stores a list of users whose package restrictions file needs to be updated 1055 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1056 1057 final private DefaultContainerConnection mDefContainerConn = 1058 new DefaultContainerConnection(); 1059 class DefaultContainerConnection implements ServiceConnection { 1060 public void onServiceConnected(ComponentName name, IBinder service) { 1061 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1062 IMediaContainerService imcs = 1063 IMediaContainerService.Stub.asInterface(service); 1064 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1065 } 1066 1067 public void onServiceDisconnected(ComponentName name) { 1068 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1069 } 1070 } 1071 1072 // Recordkeeping of restore-after-install operations that are currently in flight 1073 // between the Package Manager and the Backup Manager 1074 static class PostInstallData { 1075 public InstallArgs args; 1076 public PackageInstalledInfo res; 1077 1078 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1079 args = _a; 1080 res = _r; 1081 } 1082 } 1083 1084 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1085 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1086 1087 // XML tags for backup/restore of various bits of state 1088 private static final String TAG_PREFERRED_BACKUP = "pa"; 1089 private static final String TAG_DEFAULT_APPS = "da"; 1090 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1091 1092 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1093 private static final String TAG_ALL_GRANTS = "rt-grants"; 1094 private static final String TAG_GRANT = "grant"; 1095 private static final String ATTR_PACKAGE_NAME = "pkg"; 1096 1097 private static final String TAG_PERMISSION = "perm"; 1098 private static final String ATTR_PERMISSION_NAME = "name"; 1099 private static final String ATTR_IS_GRANTED = "g"; 1100 private static final String ATTR_USER_SET = "set"; 1101 private static final String ATTR_USER_FIXED = "fixed"; 1102 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1103 1104 // System/policy permission grants are not backed up 1105 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1106 FLAG_PERMISSION_POLICY_FIXED 1107 | FLAG_PERMISSION_SYSTEM_FIXED 1108 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1109 1110 // And we back up these user-adjusted states 1111 private static final int USER_RUNTIME_GRANT_MASK = 1112 FLAG_PERMISSION_USER_SET 1113 | FLAG_PERMISSION_USER_FIXED 1114 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1115 1116 final @Nullable String mRequiredVerifierPackage; 1117 final @NonNull String mRequiredInstallerPackage; 1118 final @Nullable String mSetupWizardPackage; 1119 final @NonNull String mServicesSystemSharedLibraryPackageName; 1120 final @NonNull String mSharedSystemSharedLibraryPackageName; 1121 1122 private final PackageUsage mPackageUsage = new PackageUsage(); 1123 1124 private class PackageUsage { 1125 private static final int WRITE_INTERVAL 1126 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 1127 1128 private final Object mFileLock = new Object(); 1129 private final AtomicLong mLastWritten = new AtomicLong(0); 1130 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 1131 1132 private boolean mIsHistoricalPackageUsageAvailable = true; 1133 1134 boolean isHistoricalPackageUsageAvailable() { 1135 return mIsHistoricalPackageUsageAvailable; 1136 } 1137 1138 void write(boolean force) { 1139 if (force) { 1140 writeInternal(); 1141 return; 1142 } 1143 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 1144 && !DEBUG_DEXOPT) { 1145 return; 1146 } 1147 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 1148 new Thread("PackageUsage_DiskWriter") { 1149 @Override 1150 public void run() { 1151 try { 1152 writeInternal(); 1153 } finally { 1154 mBackgroundWriteRunning.set(false); 1155 } 1156 } 1157 }.start(); 1158 } 1159 } 1160 1161 private void writeInternal() { 1162 synchronized (mPackages) { 1163 synchronized (mFileLock) { 1164 AtomicFile file = getFile(); 1165 FileOutputStream f = null; 1166 try { 1167 f = file.startWrite(); 1168 BufferedOutputStream out = new BufferedOutputStream(f); 1169 FileUtils.setPermissions(file.getBaseFile().getPath(), 1170 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1171 StringBuilder sb = new StringBuilder(); 1172 1173 sb.append(USAGE_FILE_MAGIC_VERSION_1); 1174 sb.append('\n'); 1175 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1176 1177 for (PackageParser.Package pkg : mPackages.values()) { 1178 if (pkg.getLatestPackageUseTimeInMills() == 0L) { 1179 continue; 1180 } 1181 sb.setLength(0); 1182 sb.append(pkg.packageName); 1183 for (long usageTimeInMillis : pkg.mLastPackageUsageTimeInMills) { 1184 sb.append(' '); 1185 sb.append(usageTimeInMillis); 1186 } 1187 sb.append('\n'); 1188 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1189 } 1190 out.flush(); 1191 file.finishWrite(f); 1192 } catch (IOException e) { 1193 if (f != null) { 1194 file.failWrite(f); 1195 } 1196 Log.e(TAG, "Failed to write package usage times", e); 1197 } 1198 } 1199 } 1200 mLastWritten.set(SystemClock.elapsedRealtime()); 1201 } 1202 1203 void readLP() { 1204 synchronized (mFileLock) { 1205 AtomicFile file = getFile(); 1206 BufferedInputStream in = null; 1207 try { 1208 in = new BufferedInputStream(file.openRead()); 1209 StringBuffer sb = new StringBuffer(); 1210 1211 String firstLine = readLine(in, sb); 1212 if (firstLine.equals(USAGE_FILE_MAGIC_VERSION_1)) { 1213 readVersion1LP(in, sb); 1214 } else { 1215 readVersion0LP(in, sb, firstLine); 1216 } 1217 } catch (FileNotFoundException expected) { 1218 mIsHistoricalPackageUsageAvailable = false; 1219 } catch (IOException e) { 1220 Log.w(TAG, "Failed to read package usage times", e); 1221 } finally { 1222 IoUtils.closeQuietly(in); 1223 } 1224 } 1225 mLastWritten.set(SystemClock.elapsedRealtime()); 1226 } 1227 1228 private void readVersion0LP(InputStream in, StringBuffer sb, String firstLine) 1229 throws IOException { 1230 // Initial version of the file had no version number and stored one 1231 // package-timestamp pair per line. 1232 // Note that the first line has already been read from the InputStream. 1233 for (String line = firstLine; line != null; line = readLine(in, sb)) { 1234 String[] tokens = line.split(" "); 1235 if (tokens.length != 2) { 1236 throw new IOException("Failed to parse " + line + 1237 " as package-timestamp pair."); 1238 } 1239 1240 String packageName = tokens[0]; 1241 PackageParser.Package pkg = mPackages.get(packageName); 1242 if (pkg == null) { 1243 continue; 1244 } 1245 1246 long timestamp = parseAsLong(tokens[1]); 1247 for (int reason = 0; 1248 reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT; 1249 reason++) { 1250 pkg.mLastPackageUsageTimeInMills[reason] = timestamp; 1251 } 1252 } 1253 } 1254 1255 private void readVersion1LP(InputStream in, StringBuffer sb) throws IOException { 1256 // Version 1 of the file started with the corresponding version 1257 // number and then stored a package name and eight timestamps per line. 1258 String line; 1259 while ((line = readLine(in, sb)) != null) { 1260 String[] tokens = line.split(" "); 1261 if (tokens.length != PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT + 1) { 1262 throw new IOException("Failed to parse " + line + " as a timestamp array."); 1263 } 1264 1265 String packageName = tokens[0]; 1266 PackageParser.Package pkg = mPackages.get(packageName); 1267 if (pkg == null) { 1268 continue; 1269 } 1270 1271 for (int reason = 0; 1272 reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT; 1273 reason++) { 1274 pkg.mLastPackageUsageTimeInMills[reason] = parseAsLong(tokens[reason + 1]); 1275 } 1276 } 1277 } 1278 1279 private long parseAsLong(String token) throws IOException { 1280 try { 1281 return Long.parseLong(token); 1282 } catch (NumberFormatException e) { 1283 throw new IOException("Failed to parse " + token + " as a long.", e); 1284 } 1285 } 1286 1287 private String readLine(InputStream in, StringBuffer sb) throws IOException { 1288 return readToken(in, sb, '\n'); 1289 } 1290 1291 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1292 throws IOException { 1293 sb.setLength(0); 1294 while (true) { 1295 int ch = in.read(); 1296 if (ch == -1) { 1297 if (sb.length() == 0) { 1298 return null; 1299 } 1300 throw new IOException("Unexpected EOF"); 1301 } 1302 if (ch == endOfToken) { 1303 return sb.toString(); 1304 } 1305 sb.append((char)ch); 1306 } 1307 } 1308 1309 private AtomicFile getFile() { 1310 File dataDir = Environment.getDataDirectory(); 1311 File systemDir = new File(dataDir, "system"); 1312 File fname = new File(systemDir, "package-usage.list"); 1313 return new AtomicFile(fname); 1314 } 1315 1316 private static final String USAGE_FILE_MAGIC = "PACKAGE_USAGE__VERSION_"; 1317 private static final String USAGE_FILE_MAGIC_VERSION_1 = USAGE_FILE_MAGIC + "1"; 1318 } 1319 1320 class PackageHandler extends Handler { 1321 private boolean mBound = false; 1322 final ArrayList<HandlerParams> mPendingInstalls = 1323 new ArrayList<HandlerParams>(); 1324 1325 private boolean connectToService() { 1326 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1327 " DefaultContainerService"); 1328 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1329 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1330 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1331 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1332 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1333 mBound = true; 1334 return true; 1335 } 1336 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1337 return false; 1338 } 1339 1340 private void disconnectService() { 1341 mContainerService = null; 1342 mBound = false; 1343 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1344 mContext.unbindService(mDefContainerConn); 1345 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1346 } 1347 1348 PackageHandler(Looper looper) { 1349 super(looper); 1350 } 1351 1352 public void handleMessage(Message msg) { 1353 try { 1354 doHandleMessage(msg); 1355 } finally { 1356 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1357 } 1358 } 1359 1360 void doHandleMessage(Message msg) { 1361 switch (msg.what) { 1362 case INIT_COPY: { 1363 HandlerParams params = (HandlerParams) msg.obj; 1364 int idx = mPendingInstalls.size(); 1365 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1366 // If a bind was already initiated we dont really 1367 // need to do anything. The pending install 1368 // will be processed later on. 1369 if (!mBound) { 1370 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1371 System.identityHashCode(mHandler)); 1372 // If this is the only one pending we might 1373 // have to bind to the service again. 1374 if (!connectToService()) { 1375 Slog.e(TAG, "Failed to bind to media container service"); 1376 params.serviceError(); 1377 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1378 System.identityHashCode(mHandler)); 1379 if (params.traceMethod != null) { 1380 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1381 params.traceCookie); 1382 } 1383 return; 1384 } else { 1385 // Once we bind to the service, the first 1386 // pending request will be processed. 1387 mPendingInstalls.add(idx, params); 1388 } 1389 } else { 1390 mPendingInstalls.add(idx, params); 1391 // Already bound to the service. Just make 1392 // sure we trigger off processing the first request. 1393 if (idx == 0) { 1394 mHandler.sendEmptyMessage(MCS_BOUND); 1395 } 1396 } 1397 break; 1398 } 1399 case MCS_BOUND: { 1400 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1401 if (msg.obj != null) { 1402 mContainerService = (IMediaContainerService) msg.obj; 1403 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1404 System.identityHashCode(mHandler)); 1405 } 1406 if (mContainerService == null) { 1407 if (!mBound) { 1408 // Something seriously wrong since we are not bound and we are not 1409 // waiting for connection. Bail out. 1410 Slog.e(TAG, "Cannot bind to media container service"); 1411 for (HandlerParams params : mPendingInstalls) { 1412 // Indicate service bind error 1413 params.serviceError(); 1414 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1415 System.identityHashCode(params)); 1416 if (params.traceMethod != null) { 1417 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1418 params.traceMethod, params.traceCookie); 1419 } 1420 return; 1421 } 1422 mPendingInstalls.clear(); 1423 } else { 1424 Slog.w(TAG, "Waiting to connect to media container service"); 1425 } 1426 } else if (mPendingInstalls.size() > 0) { 1427 HandlerParams params = mPendingInstalls.get(0); 1428 if (params != null) { 1429 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1430 System.identityHashCode(params)); 1431 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1432 if (params.startCopy()) { 1433 // We are done... look for more work or to 1434 // go idle. 1435 if (DEBUG_SD_INSTALL) Log.i(TAG, 1436 "Checking for more work or unbind..."); 1437 // Delete pending install 1438 if (mPendingInstalls.size() > 0) { 1439 mPendingInstalls.remove(0); 1440 } 1441 if (mPendingInstalls.size() == 0) { 1442 if (mBound) { 1443 if (DEBUG_SD_INSTALL) Log.i(TAG, 1444 "Posting delayed MCS_UNBIND"); 1445 removeMessages(MCS_UNBIND); 1446 Message ubmsg = obtainMessage(MCS_UNBIND); 1447 // Unbind after a little delay, to avoid 1448 // continual thrashing. 1449 sendMessageDelayed(ubmsg, 10000); 1450 } 1451 } else { 1452 // There are more pending requests in queue. 1453 // Just post MCS_BOUND message to trigger processing 1454 // of next pending install. 1455 if (DEBUG_SD_INSTALL) Log.i(TAG, 1456 "Posting MCS_BOUND for next work"); 1457 mHandler.sendEmptyMessage(MCS_BOUND); 1458 } 1459 } 1460 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1461 } 1462 } else { 1463 // Should never happen ideally. 1464 Slog.w(TAG, "Empty queue"); 1465 } 1466 break; 1467 } 1468 case MCS_RECONNECT: { 1469 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1470 if (mPendingInstalls.size() > 0) { 1471 if (mBound) { 1472 disconnectService(); 1473 } 1474 if (!connectToService()) { 1475 Slog.e(TAG, "Failed to bind to media container service"); 1476 for (HandlerParams params : mPendingInstalls) { 1477 // Indicate service bind error 1478 params.serviceError(); 1479 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1480 System.identityHashCode(params)); 1481 } 1482 mPendingInstalls.clear(); 1483 } 1484 } 1485 break; 1486 } 1487 case MCS_UNBIND: { 1488 // If there is no actual work left, then time to unbind. 1489 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1490 1491 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1492 if (mBound) { 1493 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1494 1495 disconnectService(); 1496 } 1497 } else if (mPendingInstalls.size() > 0) { 1498 // There are more pending requests in queue. 1499 // Just post MCS_BOUND message to trigger processing 1500 // of next pending install. 1501 mHandler.sendEmptyMessage(MCS_BOUND); 1502 } 1503 1504 break; 1505 } 1506 case MCS_GIVE_UP: { 1507 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1508 HandlerParams params = mPendingInstalls.remove(0); 1509 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1510 System.identityHashCode(params)); 1511 break; 1512 } 1513 case SEND_PENDING_BROADCAST: { 1514 String packages[]; 1515 ArrayList<String> components[]; 1516 int size = 0; 1517 int uids[]; 1518 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1519 synchronized (mPackages) { 1520 if (mPendingBroadcasts == null) { 1521 return; 1522 } 1523 size = mPendingBroadcasts.size(); 1524 if (size <= 0) { 1525 // Nothing to be done. Just return 1526 return; 1527 } 1528 packages = new String[size]; 1529 components = new ArrayList[size]; 1530 uids = new int[size]; 1531 int i = 0; // filling out the above arrays 1532 1533 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1534 int packageUserId = mPendingBroadcasts.userIdAt(n); 1535 Iterator<Map.Entry<String, ArrayList<String>>> it 1536 = mPendingBroadcasts.packagesForUserId(packageUserId) 1537 .entrySet().iterator(); 1538 while (it.hasNext() && i < size) { 1539 Map.Entry<String, ArrayList<String>> ent = it.next(); 1540 packages[i] = ent.getKey(); 1541 components[i] = ent.getValue(); 1542 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1543 uids[i] = (ps != null) 1544 ? UserHandle.getUid(packageUserId, ps.appId) 1545 : -1; 1546 i++; 1547 } 1548 } 1549 size = i; 1550 mPendingBroadcasts.clear(); 1551 } 1552 // Send broadcasts 1553 for (int i = 0; i < size; i++) { 1554 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1555 } 1556 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1557 break; 1558 } 1559 case START_CLEANING_PACKAGE: { 1560 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1561 final String packageName = (String)msg.obj; 1562 final int userId = msg.arg1; 1563 final boolean andCode = msg.arg2 != 0; 1564 synchronized (mPackages) { 1565 if (userId == UserHandle.USER_ALL) { 1566 int[] users = sUserManager.getUserIds(); 1567 for (int user : users) { 1568 mSettings.addPackageToCleanLPw( 1569 new PackageCleanItem(user, packageName, andCode)); 1570 } 1571 } else { 1572 mSettings.addPackageToCleanLPw( 1573 new PackageCleanItem(userId, packageName, andCode)); 1574 } 1575 } 1576 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1577 startCleaningPackages(); 1578 } break; 1579 case POST_INSTALL: { 1580 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1581 1582 PostInstallData data = mRunningInstalls.get(msg.arg1); 1583 final boolean didRestore = (msg.arg2 != 0); 1584 mRunningInstalls.delete(msg.arg1); 1585 1586 if (data != null) { 1587 InstallArgs args = data.args; 1588 PackageInstalledInfo parentRes = data.res; 1589 1590 final boolean grantPermissions = (args.installFlags 1591 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1592 final boolean killApp = (args.installFlags 1593 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1594 final String[] grantedPermissions = args.installGrantPermissions; 1595 1596 // Handle the parent package 1597 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1598 grantedPermissions, didRestore, args.installerPackageName, 1599 args.observer); 1600 1601 // Handle the child packages 1602 final int childCount = (parentRes.addedChildPackages != null) 1603 ? parentRes.addedChildPackages.size() : 0; 1604 for (int i = 0; i < childCount; i++) { 1605 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1606 handlePackagePostInstall(childRes, grantPermissions, killApp, 1607 grantedPermissions, false, args.installerPackageName, 1608 args.observer); 1609 } 1610 1611 // Log tracing if needed 1612 if (args.traceMethod != null) { 1613 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1614 args.traceCookie); 1615 } 1616 } else { 1617 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1618 } 1619 1620 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1621 } break; 1622 case UPDATED_MEDIA_STATUS: { 1623 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1624 boolean reportStatus = msg.arg1 == 1; 1625 boolean doGc = msg.arg2 == 1; 1626 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1627 if (doGc) { 1628 // Force a gc to clear up stale containers. 1629 Runtime.getRuntime().gc(); 1630 } 1631 if (msg.obj != null) { 1632 @SuppressWarnings("unchecked") 1633 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1634 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1635 // Unload containers 1636 unloadAllContainers(args); 1637 } 1638 if (reportStatus) { 1639 try { 1640 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1641 PackageHelper.getMountService().finishMediaUpdate(); 1642 } catch (RemoteException e) { 1643 Log.e(TAG, "MountService not running?"); 1644 } 1645 } 1646 } break; 1647 case WRITE_SETTINGS: { 1648 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1649 synchronized (mPackages) { 1650 removeMessages(WRITE_SETTINGS); 1651 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1652 mSettings.writeLPr(); 1653 mDirtyUsers.clear(); 1654 } 1655 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1656 } break; 1657 case WRITE_PACKAGE_RESTRICTIONS: { 1658 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1659 synchronized (mPackages) { 1660 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1661 for (int userId : mDirtyUsers) { 1662 mSettings.writePackageRestrictionsLPr(userId); 1663 } 1664 mDirtyUsers.clear(); 1665 } 1666 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1667 } break; 1668 case WRITE_PACKAGE_LIST: { 1669 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1670 synchronized (mPackages) { 1671 removeMessages(WRITE_PACKAGE_LIST); 1672 mSettings.writePackageListLPr(msg.arg1); 1673 } 1674 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1675 } break; 1676 case CHECK_PENDING_VERIFICATION: { 1677 final int verificationId = msg.arg1; 1678 final PackageVerificationState state = mPendingVerification.get(verificationId); 1679 1680 if ((state != null) && !state.timeoutExtended()) { 1681 final InstallArgs args = state.getInstallArgs(); 1682 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1683 1684 Slog.i(TAG, "Verification timed out for " + originUri); 1685 mPendingVerification.remove(verificationId); 1686 1687 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1688 1689 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1690 Slog.i(TAG, "Continuing with installation of " + originUri); 1691 state.setVerifierResponse(Binder.getCallingUid(), 1692 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1693 broadcastPackageVerified(verificationId, originUri, 1694 PackageManager.VERIFICATION_ALLOW, 1695 state.getInstallArgs().getUser()); 1696 try { 1697 ret = args.copyApk(mContainerService, true); 1698 } catch (RemoteException e) { 1699 Slog.e(TAG, "Could not contact the ContainerService"); 1700 } 1701 } else { 1702 broadcastPackageVerified(verificationId, originUri, 1703 PackageManager.VERIFICATION_REJECT, 1704 state.getInstallArgs().getUser()); 1705 } 1706 1707 Trace.asyncTraceEnd( 1708 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1709 1710 processPendingInstall(args, ret); 1711 mHandler.sendEmptyMessage(MCS_UNBIND); 1712 } 1713 break; 1714 } 1715 case PACKAGE_VERIFIED: { 1716 final int verificationId = msg.arg1; 1717 1718 final PackageVerificationState state = mPendingVerification.get(verificationId); 1719 if (state == null) { 1720 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1721 break; 1722 } 1723 1724 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1725 1726 state.setVerifierResponse(response.callerUid, response.code); 1727 1728 if (state.isVerificationComplete()) { 1729 mPendingVerification.remove(verificationId); 1730 1731 final InstallArgs args = state.getInstallArgs(); 1732 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1733 1734 int ret; 1735 if (state.isInstallAllowed()) { 1736 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1737 broadcastPackageVerified(verificationId, originUri, 1738 response.code, state.getInstallArgs().getUser()); 1739 try { 1740 ret = args.copyApk(mContainerService, true); 1741 } catch (RemoteException e) { 1742 Slog.e(TAG, "Could not contact the ContainerService"); 1743 } 1744 } else { 1745 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1746 } 1747 1748 Trace.asyncTraceEnd( 1749 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1750 1751 processPendingInstall(args, ret); 1752 mHandler.sendEmptyMessage(MCS_UNBIND); 1753 } 1754 1755 break; 1756 } 1757 case START_INTENT_FILTER_VERIFICATIONS: { 1758 IFVerificationParams params = (IFVerificationParams) msg.obj; 1759 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1760 params.replacing, params.pkg); 1761 break; 1762 } 1763 case INTENT_FILTER_VERIFIED: { 1764 final int verificationId = msg.arg1; 1765 1766 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1767 verificationId); 1768 if (state == null) { 1769 Slog.w(TAG, "Invalid IntentFilter verification token " 1770 + verificationId + " received"); 1771 break; 1772 } 1773 1774 final int userId = state.getUserId(); 1775 1776 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1777 "Processing IntentFilter verification with token:" 1778 + verificationId + " and userId:" + userId); 1779 1780 final IntentFilterVerificationResponse response = 1781 (IntentFilterVerificationResponse) msg.obj; 1782 1783 state.setVerifierResponse(response.callerUid, response.code); 1784 1785 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1786 "IntentFilter verification with token:" + verificationId 1787 + " and userId:" + userId 1788 + " is settings verifier response with response code:" 1789 + response.code); 1790 1791 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1792 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1793 + response.getFailedDomainsString()); 1794 } 1795 1796 if (state.isVerificationComplete()) { 1797 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1798 } else { 1799 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1800 "IntentFilter verification with token:" + verificationId 1801 + " was not said to be complete"); 1802 } 1803 1804 break; 1805 } 1806 } 1807 } 1808 } 1809 1810 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1811 boolean killApp, String[] grantedPermissions, 1812 boolean launchedForRestore, String installerPackage, 1813 IPackageInstallObserver2 installObserver) { 1814 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1815 // Send the removed broadcasts 1816 if (res.removedInfo != null) { 1817 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1818 } 1819 1820 // Now that we successfully installed the package, grant runtime 1821 // permissions if requested before broadcasting the install. 1822 if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion 1823 >= Build.VERSION_CODES.M) { 1824 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1825 } 1826 1827 final boolean update = res.removedInfo != null 1828 && res.removedInfo.removedPackage != null; 1829 1830 // If this is the first time we have child packages for a disabled privileged 1831 // app that had no children, we grant requested runtime permissions to the new 1832 // children if the parent on the system image had them already granted. 1833 if (res.pkg.parentPackage != null) { 1834 synchronized (mPackages) { 1835 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1836 } 1837 } 1838 1839 synchronized (mPackages) { 1840 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1841 } 1842 1843 final String packageName = res.pkg.applicationInfo.packageName; 1844 Bundle extras = new Bundle(1); 1845 extras.putInt(Intent.EXTRA_UID, res.uid); 1846 1847 // Determine the set of users who are adding this package for 1848 // the first time vs. those who are seeing an update. 1849 int[] firstUsers = EMPTY_INT_ARRAY; 1850 int[] updateUsers = EMPTY_INT_ARRAY; 1851 if (res.origUsers == null || res.origUsers.length == 0) { 1852 firstUsers = res.newUsers; 1853 } else { 1854 for (int newUser : res.newUsers) { 1855 boolean isNew = true; 1856 for (int origUser : res.origUsers) { 1857 if (origUser == newUser) { 1858 isNew = false; 1859 break; 1860 } 1861 } 1862 if (isNew) { 1863 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1864 } else { 1865 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1866 } 1867 } 1868 } 1869 1870 // Send installed broadcasts if the install/update is not ephemeral 1871 if (!isEphemeral(res.pkg)) { 1872 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1873 1874 // Send added for users that see the package for the first time 1875 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1876 extras, 0 /*flags*/, null /*targetPackage*/, 1877 null /*finishedReceiver*/, firstUsers); 1878 1879 // Send added for users that don't see the package for the first time 1880 if (update) { 1881 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1882 } 1883 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1884 extras, 0 /*flags*/, null /*targetPackage*/, 1885 null /*finishedReceiver*/, updateUsers); 1886 1887 // Send replaced for users that don't see the package for the first time 1888 if (update) { 1889 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1890 packageName, extras, 0 /*flags*/, 1891 null /*targetPackage*/, null /*finishedReceiver*/, 1892 updateUsers); 1893 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1894 null /*package*/, null /*extras*/, 0 /*flags*/, 1895 packageName /*targetPackage*/, 1896 null /*finishedReceiver*/, updateUsers); 1897 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 1898 // First-install and we did a restore, so we're responsible for the 1899 // first-launch broadcast. 1900 if (DEBUG_BACKUP) { 1901 Slog.i(TAG, "Post-restore of " + packageName 1902 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers)); 1903 } 1904 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers); 1905 } 1906 1907 // Send broadcast package appeared if forward locked/external for all users 1908 // treat asec-hosted packages like removable media on upgrade 1909 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1910 if (DEBUG_INSTALL) { 1911 Slog.i(TAG, "upgrading pkg " + res.pkg 1912 + " is ASEC-hosted -> AVAILABLE"); 1913 } 1914 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1915 ArrayList<String> pkgList = new ArrayList<>(1); 1916 pkgList.add(packageName); 1917 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1918 } 1919 } 1920 1921 // Work that needs to happen on first install within each user 1922 if (firstUsers != null && firstUsers.length > 0) { 1923 synchronized (mPackages) { 1924 for (int userId : firstUsers) { 1925 // If this app is a browser and it's newly-installed for some 1926 // users, clear any default-browser state in those users. The 1927 // app's nature doesn't depend on the user, so we can just check 1928 // its browser nature in any user and generalize. 1929 if (packageIsBrowser(packageName, userId)) { 1930 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1931 } 1932 1933 // We may also need to apply pending (restored) runtime 1934 // permission grants within these users. 1935 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1936 } 1937 } 1938 } 1939 1940 // Log current value of "unknown sources" setting 1941 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1942 getUnknownSourcesSettings()); 1943 1944 // Force a gc to clear up things 1945 Runtime.getRuntime().gc(); 1946 1947 // Remove the replaced package's older resources safely now 1948 // We delete after a gc for applications on sdcard. 1949 if (res.removedInfo != null && res.removedInfo.args != null) { 1950 synchronized (mInstallLock) { 1951 res.removedInfo.args.doPostDeleteLI(true); 1952 } 1953 } 1954 } 1955 1956 // If someone is watching installs - notify them 1957 if (installObserver != null) { 1958 try { 1959 Bundle extras = extrasForInstallResult(res); 1960 installObserver.onPackageInstalled(res.name, res.returnCode, 1961 res.returnMsg, extras); 1962 } catch (RemoteException e) { 1963 Slog.i(TAG, "Observer no longer exists."); 1964 } 1965 } 1966 } 1967 1968 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1969 PackageParser.Package pkg) { 1970 if (pkg.parentPackage == null) { 1971 return; 1972 } 1973 if (pkg.requestedPermissions == null) { 1974 return; 1975 } 1976 final PackageSetting disabledSysParentPs = mSettings 1977 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1978 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1979 || !disabledSysParentPs.isPrivileged() 1980 || (disabledSysParentPs.childPackageNames != null 1981 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1982 return; 1983 } 1984 final int[] allUserIds = sUserManager.getUserIds(); 1985 final int permCount = pkg.requestedPermissions.size(); 1986 for (int i = 0; i < permCount; i++) { 1987 String permission = pkg.requestedPermissions.get(i); 1988 BasePermission bp = mSettings.mPermissions.get(permission); 1989 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1990 continue; 1991 } 1992 for (int userId : allUserIds) { 1993 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1994 permission, userId)) { 1995 grantRuntimePermission(pkg.packageName, permission, userId); 1996 } 1997 } 1998 } 1999 } 2000 2001 private StorageEventListener mStorageListener = new StorageEventListener() { 2002 @Override 2003 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 2004 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 2005 if (vol.state == VolumeInfo.STATE_MOUNTED) { 2006 final String volumeUuid = vol.getFsUuid(); 2007 2008 // Clean up any users or apps that were removed or recreated 2009 // while this volume was missing 2010 reconcileUsers(volumeUuid); 2011 reconcileApps(volumeUuid); 2012 2013 // Clean up any install sessions that expired or were 2014 // cancelled while this volume was missing 2015 mInstallerService.onPrivateVolumeMounted(volumeUuid); 2016 2017 loadPrivatePackages(vol); 2018 2019 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2020 unloadPrivatePackages(vol); 2021 } 2022 } 2023 2024 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 2025 if (vol.state == VolumeInfo.STATE_MOUNTED) { 2026 updateExternalMediaStatus(true, false); 2027 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2028 updateExternalMediaStatus(false, false); 2029 } 2030 } 2031 } 2032 2033 @Override 2034 public void onVolumeForgotten(String fsUuid) { 2035 if (TextUtils.isEmpty(fsUuid)) { 2036 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 2037 return; 2038 } 2039 2040 // Remove any apps installed on the forgotten volume 2041 synchronized (mPackages) { 2042 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 2043 for (PackageSetting ps : packages) { 2044 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 2045 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 2046 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 2047 } 2048 2049 mSettings.onVolumeForgotten(fsUuid); 2050 mSettings.writeLPr(); 2051 } 2052 } 2053 }; 2054 2055 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 2056 String[] grantedPermissions) { 2057 for (int userId : userIds) { 2058 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 2059 } 2060 2061 // We could have touched GID membership, so flush out packages.list 2062 synchronized (mPackages) { 2063 mSettings.writePackageListLPr(); 2064 } 2065 } 2066 2067 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 2068 String[] grantedPermissions) { 2069 SettingBase sb = (SettingBase) pkg.mExtras; 2070 if (sb == null) { 2071 return; 2072 } 2073 2074 PermissionsState permissionsState = sb.getPermissionsState(); 2075 2076 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 2077 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 2078 2079 for (String permission : pkg.requestedPermissions) { 2080 final BasePermission bp; 2081 synchronized (mPackages) { 2082 bp = mSettings.mPermissions.get(permission); 2083 } 2084 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 2085 && (grantedPermissions == null 2086 || ArrayUtils.contains(grantedPermissions, permission))) { 2087 final int flags = permissionsState.getPermissionFlags(permission, userId); 2088 // Installer cannot change immutable permissions. 2089 if ((flags & immutableFlags) == 0) { 2090 grantRuntimePermission(pkg.packageName, permission, userId); 2091 } 2092 } 2093 } 2094 } 2095 2096 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2097 Bundle extras = null; 2098 switch (res.returnCode) { 2099 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2100 extras = new Bundle(); 2101 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2102 res.origPermission); 2103 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2104 res.origPackage); 2105 break; 2106 } 2107 case PackageManager.INSTALL_SUCCEEDED: { 2108 extras = new Bundle(); 2109 extras.putBoolean(Intent.EXTRA_REPLACING, 2110 res.removedInfo != null && res.removedInfo.removedPackage != null); 2111 break; 2112 } 2113 } 2114 return extras; 2115 } 2116 2117 void scheduleWriteSettingsLocked() { 2118 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2119 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2120 } 2121 } 2122 2123 void scheduleWritePackageListLocked(int userId) { 2124 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 2125 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST); 2126 msg.arg1 = userId; 2127 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY); 2128 } 2129 } 2130 2131 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2132 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2133 scheduleWritePackageRestrictionsLocked(userId); 2134 } 2135 2136 void scheduleWritePackageRestrictionsLocked(int userId) { 2137 final int[] userIds = (userId == UserHandle.USER_ALL) 2138 ? sUserManager.getUserIds() : new int[]{userId}; 2139 for (int nextUserId : userIds) { 2140 if (!sUserManager.exists(nextUserId)) return; 2141 mDirtyUsers.add(nextUserId); 2142 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2143 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2144 } 2145 } 2146 } 2147 2148 public static PackageManagerService main(Context context, Installer installer, 2149 boolean factoryTest, boolean onlyCore) { 2150 // Self-check for initial settings. 2151 PackageManagerServiceCompilerMapping.checkProperties(); 2152 2153 PackageManagerService m = new PackageManagerService(context, installer, 2154 factoryTest, onlyCore); 2155 m.enableSystemUserPackages(); 2156 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 2157 // disabled after already being started. 2158 CarrierAppUtils.disableCarrierAppsUntilPrivileged(context.getOpPackageName(), m, 2159 UserHandle.USER_SYSTEM); 2160 ServiceManager.addService("package", m); 2161 return m; 2162 } 2163 2164 private void enableSystemUserPackages() { 2165 if (!UserManager.isSplitSystemUser()) { 2166 return; 2167 } 2168 // For system user, enable apps based on the following conditions: 2169 // - app is whitelisted or belong to one of these groups: 2170 // -- system app which has no launcher icons 2171 // -- system app which has INTERACT_ACROSS_USERS permission 2172 // -- system IME app 2173 // - app is not in the blacklist 2174 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2175 Set<String> enableApps = new ArraySet<>(); 2176 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2177 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2178 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2179 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2180 enableApps.addAll(wlApps); 2181 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2182 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2183 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2184 enableApps.removeAll(blApps); 2185 Log.i(TAG, "Applications installed for system user: " + enableApps); 2186 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2187 UserHandle.SYSTEM); 2188 final int allAppsSize = allAps.size(); 2189 synchronized (mPackages) { 2190 for (int i = 0; i < allAppsSize; i++) { 2191 String pName = allAps.get(i); 2192 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2193 // Should not happen, but we shouldn't be failing if it does 2194 if (pkgSetting == null) { 2195 continue; 2196 } 2197 boolean install = enableApps.contains(pName); 2198 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2199 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2200 + " for system user"); 2201 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2202 } 2203 } 2204 } 2205 } 2206 2207 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2208 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2209 Context.DISPLAY_SERVICE); 2210 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2211 } 2212 2213 public PackageManagerService(Context context, Installer installer, 2214 boolean factoryTest, boolean onlyCore) { 2215 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2216 SystemClock.uptimeMillis()); 2217 2218 if (mSdkVersion <= 0) { 2219 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2220 } 2221 2222 mContext = context; 2223 mFactoryTest = factoryTest; 2224 mOnlyCore = onlyCore; 2225 mMetrics = new DisplayMetrics(); 2226 mSettings = new Settings(mPackages); 2227 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2228 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2229 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2230 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2231 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2232 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2233 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2234 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2235 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2236 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2237 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2238 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2239 2240 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2241 if (separateProcesses != null && separateProcesses.length() > 0) { 2242 if ("*".equals(separateProcesses)) { 2243 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2244 mSeparateProcesses = null; 2245 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2246 } else { 2247 mDefParseFlags = 0; 2248 mSeparateProcesses = separateProcesses.split(","); 2249 Slog.w(TAG, "Running with debug.separate_processes: " 2250 + separateProcesses); 2251 } 2252 } else { 2253 mDefParseFlags = 0; 2254 mSeparateProcesses = null; 2255 } 2256 2257 mInstaller = installer; 2258 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2259 "*dexopt*"); 2260 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2261 2262 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2263 FgThread.get().getLooper()); 2264 2265 getDefaultDisplayMetrics(context, mMetrics); 2266 2267 SystemConfig systemConfig = SystemConfig.getInstance(); 2268 mGlobalGids = systemConfig.getGlobalGids(); 2269 mSystemPermissions = systemConfig.getSystemPermissions(); 2270 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2271 2272 synchronized (mInstallLock) { 2273 // writer 2274 synchronized (mPackages) { 2275 mHandlerThread = new ServiceThread(TAG, 2276 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2277 mHandlerThread.start(); 2278 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2279 mProcessLoggingHandler = new ProcessLoggingHandler(); 2280 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2281 2282 File dataDir = Environment.getDataDirectory(); 2283 mAppInstallDir = new File(dataDir, "app"); 2284 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2285 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2286 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2287 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2288 2289 sUserManager = new UserManagerService(context, this, mPackages); 2290 2291 // Propagate permission configuration in to package manager. 2292 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2293 = systemConfig.getPermissions(); 2294 for (int i=0; i<permConfig.size(); i++) { 2295 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2296 BasePermission bp = mSettings.mPermissions.get(perm.name); 2297 if (bp == null) { 2298 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2299 mSettings.mPermissions.put(perm.name, bp); 2300 } 2301 if (perm.gids != null) { 2302 bp.setGids(perm.gids, perm.perUser); 2303 } 2304 } 2305 2306 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2307 for (int i=0; i<libConfig.size(); i++) { 2308 mSharedLibraries.put(libConfig.keyAt(i), 2309 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2310 } 2311 2312 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2313 2314 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 2315 2316 String customResolverActivity = Resources.getSystem().getString( 2317 R.string.config_customResolverActivity); 2318 if (TextUtils.isEmpty(customResolverActivity)) { 2319 customResolverActivity = null; 2320 } else { 2321 mCustomResolverComponentName = ComponentName.unflattenFromString( 2322 customResolverActivity); 2323 } 2324 2325 long startTime = SystemClock.uptimeMillis(); 2326 2327 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2328 startTime); 2329 2330 // Set flag to monitor and not change apk file paths when 2331 // scanning install directories. 2332 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2333 2334 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2335 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2336 2337 if (bootClassPath == null) { 2338 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2339 } 2340 2341 if (systemServerClassPath == null) { 2342 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2343 } 2344 2345 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2346 final String[] dexCodeInstructionSets = 2347 getDexCodeInstructionSets( 2348 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2349 2350 /** 2351 * Ensure all external libraries have had dexopt run on them. 2352 */ 2353 if (mSharedLibraries.size() > 0) { 2354 // NOTE: For now, we're compiling these system "shared libraries" 2355 // (and framework jars) into all available architectures. It's possible 2356 // to compile them only when we come across an app that uses them (there's 2357 // already logic for that in scanPackageLI) but that adds some complexity. 2358 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2359 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2360 final String lib = libEntry.path; 2361 if (lib == null) { 2362 continue; 2363 } 2364 2365 try { 2366 // Shared libraries do not have profiles so we perform a full 2367 // AOT compilation (if needed). 2368 int dexoptNeeded = DexFile.getDexOptNeeded( 2369 lib, dexCodeInstructionSet, 2370 getCompilerFilterForReason(REASON_SHARED_APK), 2371 false /* newProfile */); 2372 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2373 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2374 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/, 2375 getCompilerFilterForReason(REASON_SHARED_APK), 2376 StorageManager.UUID_PRIVATE_INTERNAL, 2377 SKIP_SHARED_LIBRARY_CHECK); 2378 } 2379 } catch (FileNotFoundException e) { 2380 Slog.w(TAG, "Library not found: " + lib); 2381 } catch (IOException | InstallerException e) { 2382 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2383 + e.getMessage()); 2384 } 2385 } 2386 } 2387 } 2388 2389 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2390 2391 final VersionInfo ver = mSettings.getInternalVersion(); 2392 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2393 2394 // when upgrading from pre-M, promote system app permissions from install to runtime 2395 mPromoteSystemApps = 2396 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2397 2398 // save off the names of pre-existing system packages prior to scanning; we don't 2399 // want to automatically grant runtime permissions for new system apps 2400 if (mPromoteSystemApps) { 2401 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2402 while (pkgSettingIter.hasNext()) { 2403 PackageSetting ps = pkgSettingIter.next(); 2404 if (isSystemApp(ps)) { 2405 mExistingSystemPackages.add(ps.name); 2406 } 2407 } 2408 } 2409 2410 // When upgrading from pre-N, we need to handle package extraction like first boot, 2411 // as there is no profiling data available. 2412 mIsPreNUpgrade = !mSettings.isNWorkDone(); 2413 mSettings.setNWorkDone(); 2414 2415 // Collect vendor overlay packages. 2416 // (Do this before scanning any apps.) 2417 // For security and version matching reason, only consider 2418 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2419 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2420 scanDirTracedLI(vendorOverlayDir, mDefParseFlags 2421 | PackageParser.PARSE_IS_SYSTEM 2422 | PackageParser.PARSE_IS_SYSTEM_DIR 2423 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2424 2425 // Find base frameworks (resource packages without code). 2426 scanDirTracedLI(frameworkDir, mDefParseFlags 2427 | PackageParser.PARSE_IS_SYSTEM 2428 | PackageParser.PARSE_IS_SYSTEM_DIR 2429 | PackageParser.PARSE_IS_PRIVILEGED, 2430 scanFlags | SCAN_NO_DEX, 0); 2431 2432 // Collected privileged system packages. 2433 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2434 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2435 | PackageParser.PARSE_IS_SYSTEM 2436 | PackageParser.PARSE_IS_SYSTEM_DIR 2437 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2438 2439 // Collect ordinary system packages. 2440 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2441 scanDirTracedLI(systemAppDir, mDefParseFlags 2442 | PackageParser.PARSE_IS_SYSTEM 2443 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2444 2445 // Collect all vendor packages. 2446 File vendorAppDir = new File("/vendor/app"); 2447 try { 2448 vendorAppDir = vendorAppDir.getCanonicalFile(); 2449 } catch (IOException e) { 2450 // failed to look up canonical path, continue with original one 2451 } 2452 scanDirTracedLI(vendorAppDir, mDefParseFlags 2453 | PackageParser.PARSE_IS_SYSTEM 2454 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2455 2456 // Collect all OEM packages. 2457 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2458 scanDirTracedLI(oemAppDir, mDefParseFlags 2459 | PackageParser.PARSE_IS_SYSTEM 2460 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2461 2462 // Prune any system packages that no longer exist. 2463 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2464 if (!mOnlyCore) { 2465 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2466 while (psit.hasNext()) { 2467 PackageSetting ps = psit.next(); 2468 2469 /* 2470 * If this is not a system app, it can't be a 2471 * disable system app. 2472 */ 2473 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2474 continue; 2475 } 2476 2477 /* 2478 * If the package is scanned, it's not erased. 2479 */ 2480 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2481 if (scannedPkg != null) { 2482 /* 2483 * If the system app is both scanned and in the 2484 * disabled packages list, then it must have been 2485 * added via OTA. Remove it from the currently 2486 * scanned package so the previously user-installed 2487 * application can be scanned. 2488 */ 2489 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2490 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2491 + ps.name + "; removing system app. Last known codePath=" 2492 + ps.codePathString + ", installStatus=" + ps.installStatus 2493 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2494 + scannedPkg.mVersionCode); 2495 removePackageLI(scannedPkg, true); 2496 mExpectingBetter.put(ps.name, ps.codePath); 2497 } 2498 2499 continue; 2500 } 2501 2502 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2503 psit.remove(); 2504 logCriticalInfo(Log.WARN, "System package " + ps.name 2505 + " no longer exists; it's data will be wiped"); 2506 // Actual deletion of code and data will be handled by later 2507 // reconciliation step 2508 } else { 2509 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2510 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2511 possiblyDeletedUpdatedSystemApps.add(ps.name); 2512 } 2513 } 2514 } 2515 } 2516 2517 //look for any incomplete package installations 2518 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2519 for (int i = 0; i < deletePkgsList.size(); i++) { 2520 // Actual deletion of code and data will be handled by later 2521 // reconciliation step 2522 final String packageName = deletePkgsList.get(i).name; 2523 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2524 synchronized (mPackages) { 2525 mSettings.removePackageLPw(packageName); 2526 } 2527 } 2528 2529 //delete tmp files 2530 deleteTempPackageFiles(); 2531 2532 // Remove any shared userIDs that have no associated packages 2533 mSettings.pruneSharedUsersLPw(); 2534 2535 if (!mOnlyCore) { 2536 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2537 SystemClock.uptimeMillis()); 2538 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2539 2540 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2541 | PackageParser.PARSE_FORWARD_LOCK, 2542 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2543 2544 scanDirLI(mEphemeralInstallDir, mDefParseFlags 2545 | PackageParser.PARSE_IS_EPHEMERAL, 2546 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2547 2548 /** 2549 * Remove disable package settings for any updated system 2550 * apps that were removed via an OTA. If they're not a 2551 * previously-updated app, remove them completely. 2552 * Otherwise, just revoke their system-level permissions. 2553 */ 2554 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2555 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2556 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2557 2558 String msg; 2559 if (deletedPkg == null) { 2560 msg = "Updated system package " + deletedAppName 2561 + " no longer exists; it's data will be wiped"; 2562 // Actual deletion of code and data will be handled by later 2563 // reconciliation step 2564 } else { 2565 msg = "Updated system app + " + deletedAppName 2566 + " no longer present; removing system privileges for " 2567 + deletedAppName; 2568 2569 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2570 2571 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2572 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2573 } 2574 logCriticalInfo(Log.WARN, msg); 2575 } 2576 2577 /** 2578 * Make sure all system apps that we expected to appear on 2579 * the userdata partition actually showed up. If they never 2580 * appeared, crawl back and revive the system version. 2581 */ 2582 for (int i = 0; i < mExpectingBetter.size(); i++) { 2583 final String packageName = mExpectingBetter.keyAt(i); 2584 if (!mPackages.containsKey(packageName)) { 2585 final File scanFile = mExpectingBetter.valueAt(i); 2586 2587 logCriticalInfo(Log.WARN, "Expected better " + packageName 2588 + " but never showed up; reverting to system"); 2589 2590 int reparseFlags = mDefParseFlags; 2591 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2592 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2593 | PackageParser.PARSE_IS_SYSTEM_DIR 2594 | PackageParser.PARSE_IS_PRIVILEGED; 2595 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2596 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2597 | PackageParser.PARSE_IS_SYSTEM_DIR; 2598 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2599 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2600 | PackageParser.PARSE_IS_SYSTEM_DIR; 2601 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2602 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2603 | PackageParser.PARSE_IS_SYSTEM_DIR; 2604 } else { 2605 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2606 continue; 2607 } 2608 2609 mSettings.enableSystemPackageLPw(packageName); 2610 2611 try { 2612 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2613 } catch (PackageManagerException e) { 2614 Slog.e(TAG, "Failed to parse original system package: " 2615 + e.getMessage()); 2616 } 2617 } 2618 } 2619 } 2620 mExpectingBetter.clear(); 2621 2622 // Resolve protected action filters. Only the setup wizard is allowed to 2623 // have a high priority filter for these actions. 2624 mSetupWizardPackage = getSetupWizardPackageName(); 2625 if (mProtectedFilters.size() > 0) { 2626 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2627 Slog.i(TAG, "No setup wizard;" 2628 + " All protected intents capped to priority 0"); 2629 } 2630 for (ActivityIntentInfo filter : mProtectedFilters) { 2631 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2632 if (DEBUG_FILTERS) { 2633 Slog.i(TAG, "Found setup wizard;" 2634 + " allow priority " + filter.getPriority() + ";" 2635 + " package: " + filter.activity.info.packageName 2636 + " activity: " + filter.activity.className 2637 + " priority: " + filter.getPriority()); 2638 } 2639 // skip setup wizard; allow it to keep the high priority filter 2640 continue; 2641 } 2642 Slog.w(TAG, "Protected action; cap priority to 0;" 2643 + " package: " + filter.activity.info.packageName 2644 + " activity: " + filter.activity.className 2645 + " origPrio: " + filter.getPriority()); 2646 filter.setPriority(0); 2647 } 2648 } 2649 mDeferProtectedFilters = false; 2650 mProtectedFilters.clear(); 2651 2652 // Now that we know all of the shared libraries, update all clients to have 2653 // the correct library paths. 2654 updateAllSharedLibrariesLPw(); 2655 2656 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2657 // NOTE: We ignore potential failures here during a system scan (like 2658 // the rest of the commands above) because there's precious little we 2659 // can do about it. A settings error is reported, though. 2660 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2661 false /* boot complete */); 2662 } 2663 2664 // Now that we know all the packages we are keeping, 2665 // read and update their last usage times. 2666 mPackageUsage.readLP(); 2667 2668 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2669 SystemClock.uptimeMillis()); 2670 Slog.i(TAG, "Time to scan packages: " 2671 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2672 + " seconds"); 2673 2674 // If the platform SDK has changed since the last time we booted, 2675 // we need to re-grant app permission to catch any new ones that 2676 // appear. This is really a hack, and means that apps can in some 2677 // cases get permissions that the user didn't initially explicitly 2678 // allow... it would be nice to have some better way to handle 2679 // this situation. 2680 int updateFlags = UPDATE_PERMISSIONS_ALL; 2681 if (ver.sdkVersion != mSdkVersion) { 2682 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2683 + mSdkVersion + "; regranting permissions for internal storage"); 2684 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2685 } 2686 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2687 ver.sdkVersion = mSdkVersion; 2688 2689 // If this is the first boot or an update from pre-M, and it is a normal 2690 // boot, then we need to initialize the default preferred apps across 2691 // all defined users. 2692 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2693 for (UserInfo user : sUserManager.getUsers(true)) { 2694 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2695 applyFactoryDefaultBrowserLPw(user.id); 2696 primeDomainVerificationsLPw(user.id); 2697 } 2698 } 2699 2700 // Prepare storage for system user really early during boot, 2701 // since core system apps like SettingsProvider and SystemUI 2702 // can't wait for user to start 2703 final int storageFlags; 2704 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2705 storageFlags = StorageManager.FLAG_STORAGE_DE; 2706 } else { 2707 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2708 } 2709 reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2710 storageFlags); 2711 2712 // If this is first boot after an OTA, and a normal boot, then 2713 // we need to clear code cache directories. 2714 // Note that we do *not* clear the application profiles. These remain valid 2715 // across OTAs and are used to drive profile verification (post OTA) and 2716 // profile compilation (without waiting to collect a fresh set of profiles). 2717 if (mIsUpgrade && !onlyCore) { 2718 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2719 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2720 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2721 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2722 // No apps are running this early, so no need to freeze 2723 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2724 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2725 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2726 } 2727 clearAppProfilesLIF(ps.pkg, UserHandle.USER_ALL); 2728 } 2729 ver.fingerprint = Build.FINGERPRINT; 2730 } 2731 2732 checkDefaultBrowser(); 2733 2734 // clear only after permissions and other defaults have been updated 2735 mExistingSystemPackages.clear(); 2736 mPromoteSystemApps = false; 2737 2738 // All the changes are done during package scanning. 2739 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2740 2741 // can downgrade to reader 2742 mSettings.writeLPr(); 2743 2744 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2745 SystemClock.uptimeMillis()); 2746 2747 if (!mOnlyCore) { 2748 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2749 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2750 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2751 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2752 mIntentFilterVerifierComponent); 2753 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2754 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 2755 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2756 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED); 2757 } else { 2758 mRequiredVerifierPackage = null; 2759 mRequiredInstallerPackage = null; 2760 mIntentFilterVerifierComponent = null; 2761 mIntentFilterVerifier = null; 2762 mServicesSystemSharedLibraryPackageName = null; 2763 mSharedSystemSharedLibraryPackageName = null; 2764 } 2765 2766 mInstallerService = new PackageInstallerService(context, this); 2767 2768 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2769 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2770 // both the installer and resolver must be present to enable ephemeral 2771 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2772 if (DEBUG_EPHEMERAL) { 2773 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2774 + " installer:" + ephemeralInstallerComponent); 2775 } 2776 mEphemeralResolverComponent = ephemeralResolverComponent; 2777 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2778 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2779 mEphemeralResolverConnection = 2780 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2781 } else { 2782 if (DEBUG_EPHEMERAL) { 2783 final String missingComponent = 2784 (ephemeralResolverComponent == null) 2785 ? (ephemeralInstallerComponent == null) 2786 ? "resolver and installer" 2787 : "resolver" 2788 : "installer"; 2789 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2790 } 2791 mEphemeralResolverComponent = null; 2792 mEphemeralInstallerComponent = null; 2793 mEphemeralResolverConnection = null; 2794 } 2795 2796 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2797 } // synchronized (mPackages) 2798 } // synchronized (mInstallLock) 2799 2800 // Now after opening every single application zip, make sure they 2801 // are all flushed. Not really needed, but keeps things nice and 2802 // tidy. 2803 Runtime.getRuntime().gc(); 2804 2805 // The initial scanning above does many calls into installd while 2806 // holding the mPackages lock, but we're mostly interested in yelling 2807 // once we have a booted system. 2808 mInstaller.setWarnIfHeld(mPackages); 2809 2810 // Expose private service for system components to use. 2811 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2812 } 2813 2814 @Override 2815 public boolean isFirstBoot() { 2816 return !mRestoredSettings; 2817 } 2818 2819 @Override 2820 public boolean isOnlyCoreApps() { 2821 return mOnlyCore; 2822 } 2823 2824 @Override 2825 public boolean isUpgrade() { 2826 return mIsUpgrade; 2827 } 2828 2829 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2830 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2831 2832 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2833 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2834 UserHandle.USER_SYSTEM); 2835 if (matches.size() == 1) { 2836 return matches.get(0).getComponentInfo().packageName; 2837 } else { 2838 Log.e(TAG, "There should probably be exactly one verifier; found " + matches); 2839 return null; 2840 } 2841 } 2842 2843 private @NonNull String getRequiredSharedLibraryLPr(String libraryName) { 2844 synchronized (mPackages) { 2845 SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName); 2846 if (libraryEntry == null) { 2847 throw new IllegalStateException("Missing required shared library:" + libraryName); 2848 } 2849 return libraryEntry.apk; 2850 } 2851 } 2852 2853 private @NonNull String getRequiredInstallerLPr() { 2854 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2855 intent.addCategory(Intent.CATEGORY_DEFAULT); 2856 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2857 2858 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2859 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2860 UserHandle.USER_SYSTEM); 2861 if (matches.size() == 1) { 2862 ResolveInfo resolveInfo = matches.get(0); 2863 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 2864 throw new RuntimeException("The installer must be a privileged app"); 2865 } 2866 return matches.get(0).getComponentInfo().packageName; 2867 } else { 2868 throw new RuntimeException("There must be exactly one installer; found " + matches); 2869 } 2870 } 2871 2872 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2873 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2874 2875 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2876 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2877 UserHandle.USER_SYSTEM); 2878 ResolveInfo best = null; 2879 final int N = matches.size(); 2880 for (int i = 0; i < N; i++) { 2881 final ResolveInfo cur = matches.get(i); 2882 final String packageName = cur.getComponentInfo().packageName; 2883 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2884 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2885 continue; 2886 } 2887 2888 if (best == null || cur.priority > best.priority) { 2889 best = cur; 2890 } 2891 } 2892 2893 if (best != null) { 2894 return best.getComponentInfo().getComponentName(); 2895 } else { 2896 throw new RuntimeException("There must be at least one intent filter verifier"); 2897 } 2898 } 2899 2900 private @Nullable ComponentName getEphemeralResolverLPr() { 2901 final String[] packageArray = 2902 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2903 if (packageArray.length == 0) { 2904 if (DEBUG_EPHEMERAL) { 2905 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2906 } 2907 return null; 2908 } 2909 2910 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2911 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 2912 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2913 UserHandle.USER_SYSTEM); 2914 2915 final int N = resolvers.size(); 2916 if (N == 0) { 2917 if (DEBUG_EPHEMERAL) { 2918 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2919 } 2920 return null; 2921 } 2922 2923 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2924 for (int i = 0; i < N; i++) { 2925 final ResolveInfo info = resolvers.get(i); 2926 2927 if (info.serviceInfo == null) { 2928 continue; 2929 } 2930 2931 final String packageName = info.serviceInfo.packageName; 2932 if (!possiblePackages.contains(packageName)) { 2933 if (DEBUG_EPHEMERAL) { 2934 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2935 + " pkg: " + packageName + ", info:" + info); 2936 } 2937 continue; 2938 } 2939 2940 if (DEBUG_EPHEMERAL) { 2941 Slog.v(TAG, "Ephemeral resolver found;" 2942 + " pkg: " + packageName + ", info:" + info); 2943 } 2944 return new ComponentName(packageName, info.serviceInfo.name); 2945 } 2946 if (DEBUG_EPHEMERAL) { 2947 Slog.v(TAG, "Ephemeral resolver NOT found"); 2948 } 2949 return null; 2950 } 2951 2952 private @Nullable ComponentName getEphemeralInstallerLPr() { 2953 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2954 intent.addCategory(Intent.CATEGORY_DEFAULT); 2955 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2956 2957 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2958 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2959 UserHandle.USER_SYSTEM); 2960 if (matches.size() == 0) { 2961 return null; 2962 } else if (matches.size() == 1) { 2963 return matches.get(0).getComponentInfo().getComponentName(); 2964 } else { 2965 throw new RuntimeException( 2966 "There must be at most one ephemeral installer; found " + matches); 2967 } 2968 } 2969 2970 private void primeDomainVerificationsLPw(int userId) { 2971 if (DEBUG_DOMAIN_VERIFICATION) { 2972 Slog.d(TAG, "Priming domain verifications in user " + userId); 2973 } 2974 2975 SystemConfig systemConfig = SystemConfig.getInstance(); 2976 ArraySet<String> packages = systemConfig.getLinkedApps(); 2977 ArraySet<String> domains = new ArraySet<String>(); 2978 2979 for (String packageName : packages) { 2980 PackageParser.Package pkg = mPackages.get(packageName); 2981 if (pkg != null) { 2982 if (!pkg.isSystemApp()) { 2983 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2984 continue; 2985 } 2986 2987 domains.clear(); 2988 for (PackageParser.Activity a : pkg.activities) { 2989 for (ActivityIntentInfo filter : a.intents) { 2990 if (hasValidDomains(filter)) { 2991 domains.addAll(filter.getHostsList()); 2992 } 2993 } 2994 } 2995 2996 if (domains.size() > 0) { 2997 if (DEBUG_DOMAIN_VERIFICATION) { 2998 Slog.v(TAG, " + " + packageName); 2999 } 3000 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 3001 // state w.r.t. the formal app-linkage "no verification attempted" state; 3002 // and then 'always' in the per-user state actually used for intent resolution. 3003 final IntentFilterVerificationInfo ivi; 3004 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 3005 new ArrayList<String>(domains)); 3006 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 3007 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 3008 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 3009 } else { 3010 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 3011 + "' does not handle web links"); 3012 } 3013 } else { 3014 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 3015 } 3016 } 3017 3018 scheduleWritePackageRestrictionsLocked(userId); 3019 scheduleWriteSettingsLocked(); 3020 } 3021 3022 private void applyFactoryDefaultBrowserLPw(int userId) { 3023 // The default browser app's package name is stored in a string resource, 3024 // with a product-specific overlay used for vendor customization. 3025 String browserPkg = mContext.getResources().getString( 3026 com.android.internal.R.string.default_browser); 3027 if (!TextUtils.isEmpty(browserPkg)) { 3028 // non-empty string => required to be a known package 3029 PackageSetting ps = mSettings.mPackages.get(browserPkg); 3030 if (ps == null) { 3031 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3032 browserPkg = null; 3033 } else { 3034 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3035 } 3036 } 3037 3038 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3039 // default. If there's more than one, just leave everything alone. 3040 if (browserPkg == null) { 3041 calculateDefaultBrowserLPw(userId); 3042 } 3043 } 3044 3045 private void calculateDefaultBrowserLPw(int userId) { 3046 List<String> allBrowsers = resolveAllBrowserApps(userId); 3047 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3048 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3049 } 3050 3051 private List<String> resolveAllBrowserApps(int userId) { 3052 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3053 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3054 PackageManager.MATCH_ALL, userId); 3055 3056 final int count = list.size(); 3057 List<String> result = new ArrayList<String>(count); 3058 for (int i=0; i<count; i++) { 3059 ResolveInfo info = list.get(i); 3060 if (info.activityInfo == null 3061 || !info.handleAllWebDataURI 3062 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3063 || result.contains(info.activityInfo.packageName)) { 3064 continue; 3065 } 3066 result.add(info.activityInfo.packageName); 3067 } 3068 3069 return result; 3070 } 3071 3072 private boolean packageIsBrowser(String packageName, int userId) { 3073 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3074 PackageManager.MATCH_ALL, userId); 3075 final int N = list.size(); 3076 for (int i = 0; i < N; i++) { 3077 ResolveInfo info = list.get(i); 3078 if (packageName.equals(info.activityInfo.packageName)) { 3079 return true; 3080 } 3081 } 3082 return false; 3083 } 3084 3085 private void checkDefaultBrowser() { 3086 final int myUserId = UserHandle.myUserId(); 3087 final String packageName = getDefaultBrowserPackageName(myUserId); 3088 if (packageName != null) { 3089 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3090 if (info == null) { 3091 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3092 synchronized (mPackages) { 3093 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3094 } 3095 } 3096 } 3097 } 3098 3099 @Override 3100 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3101 throws RemoteException { 3102 try { 3103 return super.onTransact(code, data, reply, flags); 3104 } catch (RuntimeException e) { 3105 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3106 Slog.wtf(TAG, "Package Manager Crash", e); 3107 } 3108 throw e; 3109 } 3110 } 3111 3112 static int[] appendInts(int[] cur, int[] add) { 3113 if (add == null) return cur; 3114 if (cur == null) return add; 3115 final int N = add.length; 3116 for (int i=0; i<N; i++) { 3117 cur = appendInt(cur, add[i]); 3118 } 3119 return cur; 3120 } 3121 3122 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3123 if (!sUserManager.exists(userId)) return null; 3124 if (ps == null) { 3125 return null; 3126 } 3127 final PackageParser.Package p = ps.pkg; 3128 if (p == null) { 3129 return null; 3130 } 3131 3132 final PermissionsState permissionsState = ps.getPermissionsState(); 3133 3134 final int[] gids = permissionsState.computeGids(userId); 3135 final Set<String> permissions = permissionsState.getPermissions(userId); 3136 final PackageUserState state = ps.readUserState(userId); 3137 3138 return PackageParser.generatePackageInfo(p, gids, flags, 3139 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3140 } 3141 3142 @Override 3143 public void checkPackageStartable(String packageName, int userId) { 3144 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3145 3146 synchronized (mPackages) { 3147 final PackageSetting ps = mSettings.mPackages.get(packageName); 3148 if (ps == null) { 3149 throw new SecurityException("Package " + packageName + " was not found!"); 3150 } 3151 3152 if (!ps.getInstalled(userId)) { 3153 throw new SecurityException( 3154 "Package " + packageName + " was not installed for user " + userId + "!"); 3155 } 3156 3157 if (mSafeMode && !ps.isSystem()) { 3158 throw new SecurityException("Package " + packageName + " not a system app!"); 3159 } 3160 3161 if (mFrozenPackages.contains(packageName)) { 3162 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3163 } 3164 3165 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3166 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3167 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3168 } 3169 } 3170 } 3171 3172 @Override 3173 public boolean isPackageAvailable(String packageName, int userId) { 3174 if (!sUserManager.exists(userId)) return false; 3175 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3176 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3177 synchronized (mPackages) { 3178 PackageParser.Package p = mPackages.get(packageName); 3179 if (p != null) { 3180 final PackageSetting ps = (PackageSetting) p.mExtras; 3181 if (ps != null) { 3182 final PackageUserState state = ps.readUserState(userId); 3183 if (state != null) { 3184 return PackageParser.isAvailable(state); 3185 } 3186 } 3187 } 3188 } 3189 return false; 3190 } 3191 3192 @Override 3193 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3194 if (!sUserManager.exists(userId)) return null; 3195 flags = updateFlagsForPackage(flags, userId, packageName); 3196 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3197 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3198 // reader 3199 synchronized (mPackages) { 3200 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3201 PackageParser.Package p = null; 3202 if (matchFactoryOnly) { 3203 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3204 if (ps != null) { 3205 return generatePackageInfo(ps, flags, userId); 3206 } 3207 } 3208 if (p == null) { 3209 p = mPackages.get(packageName); 3210 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3211 return null; 3212 } 3213 } 3214 if (DEBUG_PACKAGE_INFO) 3215 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3216 if (p != null) { 3217 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3218 } 3219 if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3220 final PackageSetting ps = mSettings.mPackages.get(packageName); 3221 return generatePackageInfo(ps, flags, userId); 3222 } 3223 } 3224 return null; 3225 } 3226 3227 @Override 3228 public String[] currentToCanonicalPackageNames(String[] names) { 3229 String[] out = new String[names.length]; 3230 // reader 3231 synchronized (mPackages) { 3232 for (int i=names.length-1; i>=0; i--) { 3233 PackageSetting ps = mSettings.mPackages.get(names[i]); 3234 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3235 } 3236 } 3237 return out; 3238 } 3239 3240 @Override 3241 public String[] canonicalToCurrentPackageNames(String[] names) { 3242 String[] out = new String[names.length]; 3243 // reader 3244 synchronized (mPackages) { 3245 for (int i=names.length-1; i>=0; i--) { 3246 String cur = mSettings.mRenamedPackages.get(names[i]); 3247 out[i] = cur != null ? cur : names[i]; 3248 } 3249 } 3250 return out; 3251 } 3252 3253 @Override 3254 public int getPackageUid(String packageName, int flags, int userId) { 3255 if (!sUserManager.exists(userId)) return -1; 3256 flags = updateFlagsForPackage(flags, userId, packageName); 3257 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3258 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3259 3260 // reader 3261 synchronized (mPackages) { 3262 final PackageParser.Package p = mPackages.get(packageName); 3263 if (p != null && p.isMatch(flags)) { 3264 return UserHandle.getUid(userId, p.applicationInfo.uid); 3265 } 3266 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3267 final PackageSetting ps = mSettings.mPackages.get(packageName); 3268 if (ps != null && ps.isMatch(flags)) { 3269 return UserHandle.getUid(userId, ps.appId); 3270 } 3271 } 3272 } 3273 3274 return -1; 3275 } 3276 3277 @Override 3278 public int[] getPackageGids(String packageName, int flags, int userId) { 3279 if (!sUserManager.exists(userId)) return null; 3280 flags = updateFlagsForPackage(flags, userId, packageName); 3281 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3282 false /* requireFullPermission */, false /* checkShell */, 3283 "getPackageGids"); 3284 3285 // reader 3286 synchronized (mPackages) { 3287 final PackageParser.Package p = mPackages.get(packageName); 3288 if (p != null && p.isMatch(flags)) { 3289 PackageSetting ps = (PackageSetting) p.mExtras; 3290 return ps.getPermissionsState().computeGids(userId); 3291 } 3292 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3293 final PackageSetting ps = mSettings.mPackages.get(packageName); 3294 if (ps != null && ps.isMatch(flags)) { 3295 return ps.getPermissionsState().computeGids(userId); 3296 } 3297 } 3298 } 3299 3300 return null; 3301 } 3302 3303 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3304 if (bp.perm != null) { 3305 return PackageParser.generatePermissionInfo(bp.perm, flags); 3306 } 3307 PermissionInfo pi = new PermissionInfo(); 3308 pi.name = bp.name; 3309 pi.packageName = bp.sourcePackage; 3310 pi.nonLocalizedLabel = bp.name; 3311 pi.protectionLevel = bp.protectionLevel; 3312 return pi; 3313 } 3314 3315 @Override 3316 public PermissionInfo getPermissionInfo(String name, int flags) { 3317 // reader 3318 synchronized (mPackages) { 3319 final BasePermission p = mSettings.mPermissions.get(name); 3320 if (p != null) { 3321 return generatePermissionInfo(p, flags); 3322 } 3323 return null; 3324 } 3325 } 3326 3327 @Override 3328 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3329 int flags) { 3330 // reader 3331 synchronized (mPackages) { 3332 if (group != null && !mPermissionGroups.containsKey(group)) { 3333 // This is thrown as NameNotFoundException 3334 return null; 3335 } 3336 3337 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3338 for (BasePermission p : mSettings.mPermissions.values()) { 3339 if (group == null) { 3340 if (p.perm == null || p.perm.info.group == null) { 3341 out.add(generatePermissionInfo(p, flags)); 3342 } 3343 } else { 3344 if (p.perm != null && group.equals(p.perm.info.group)) { 3345 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3346 } 3347 } 3348 } 3349 return new ParceledListSlice<>(out); 3350 } 3351 } 3352 3353 @Override 3354 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3355 // reader 3356 synchronized (mPackages) { 3357 return PackageParser.generatePermissionGroupInfo( 3358 mPermissionGroups.get(name), flags); 3359 } 3360 } 3361 3362 @Override 3363 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3364 // reader 3365 synchronized (mPackages) { 3366 final int N = mPermissionGroups.size(); 3367 ArrayList<PermissionGroupInfo> out 3368 = new ArrayList<PermissionGroupInfo>(N); 3369 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3370 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3371 } 3372 return new ParceledListSlice<>(out); 3373 } 3374 } 3375 3376 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3377 int userId) { 3378 if (!sUserManager.exists(userId)) return null; 3379 PackageSetting ps = mSettings.mPackages.get(packageName); 3380 if (ps != null) { 3381 if (ps.pkg == null) { 3382 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3383 if (pInfo != null) { 3384 return pInfo.applicationInfo; 3385 } 3386 return null; 3387 } 3388 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3389 ps.readUserState(userId), userId); 3390 } 3391 return null; 3392 } 3393 3394 @Override 3395 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3396 if (!sUserManager.exists(userId)) return null; 3397 flags = updateFlagsForApplication(flags, userId, packageName); 3398 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3399 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3400 // writer 3401 synchronized (mPackages) { 3402 PackageParser.Package p = mPackages.get(packageName); 3403 if (DEBUG_PACKAGE_INFO) Log.v( 3404 TAG, "getApplicationInfo " + packageName 3405 + ": " + p); 3406 if (p != null) { 3407 PackageSetting ps = mSettings.mPackages.get(packageName); 3408 if (ps == null) return null; 3409 // Note: isEnabledLP() does not apply here - always return info 3410 return PackageParser.generateApplicationInfo( 3411 p, flags, ps.readUserState(userId), userId); 3412 } 3413 if ("android".equals(packageName)||"system".equals(packageName)) { 3414 return mAndroidApplication; 3415 } 3416 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3417 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3418 } 3419 } 3420 return null; 3421 } 3422 3423 @Override 3424 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3425 final IPackageDataObserver observer) { 3426 mContext.enforceCallingOrSelfPermission( 3427 android.Manifest.permission.CLEAR_APP_CACHE, null); 3428 // Queue up an async operation since clearing cache may take a little while. 3429 mHandler.post(new Runnable() { 3430 public void run() { 3431 mHandler.removeCallbacks(this); 3432 boolean success = true; 3433 synchronized (mInstallLock) { 3434 try { 3435 mInstaller.freeCache(volumeUuid, freeStorageSize); 3436 } catch (InstallerException e) { 3437 Slog.w(TAG, "Couldn't clear application caches: " + e); 3438 success = false; 3439 } 3440 } 3441 if (observer != null) { 3442 try { 3443 observer.onRemoveCompleted(null, success); 3444 } catch (RemoteException e) { 3445 Slog.w(TAG, "RemoveException when invoking call back"); 3446 } 3447 } 3448 } 3449 }); 3450 } 3451 3452 @Override 3453 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3454 final IntentSender pi) { 3455 mContext.enforceCallingOrSelfPermission( 3456 android.Manifest.permission.CLEAR_APP_CACHE, null); 3457 // Queue up an async operation since clearing cache may take a little while. 3458 mHandler.post(new Runnable() { 3459 public void run() { 3460 mHandler.removeCallbacks(this); 3461 boolean success = true; 3462 synchronized (mInstallLock) { 3463 try { 3464 mInstaller.freeCache(volumeUuid, freeStorageSize); 3465 } catch (InstallerException e) { 3466 Slog.w(TAG, "Couldn't clear application caches: " + e); 3467 success = false; 3468 } 3469 } 3470 if(pi != null) { 3471 try { 3472 // Callback via pending intent 3473 int code = success ? 1 : 0; 3474 pi.sendIntent(null, code, null, 3475 null, null); 3476 } catch (SendIntentException e1) { 3477 Slog.i(TAG, "Failed to send pending intent"); 3478 } 3479 } 3480 } 3481 }); 3482 } 3483 3484 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3485 synchronized (mInstallLock) { 3486 try { 3487 mInstaller.freeCache(volumeUuid, freeStorageSize); 3488 } catch (InstallerException e) { 3489 throw new IOException("Failed to free enough space", e); 3490 } 3491 } 3492 } 3493 3494 /** 3495 * Update given flags based on encryption status of current user. 3496 */ 3497 private int updateFlags(int flags, int userId) { 3498 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3499 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3500 // Caller expressed an explicit opinion about what encryption 3501 // aware/unaware components they want to see, so fall through and 3502 // give them what they want 3503 } else { 3504 // Caller expressed no opinion, so match based on user state 3505 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 3506 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3507 } else { 3508 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3509 } 3510 } 3511 return flags; 3512 } 3513 3514 private UserManagerInternal getUserManagerInternal() { 3515 if (mUserManagerInternal == null) { 3516 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 3517 } 3518 return mUserManagerInternal; 3519 } 3520 3521 /** 3522 * Update given flags when being used to request {@link PackageInfo}. 3523 */ 3524 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3525 boolean triaged = true; 3526 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3527 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3528 // Caller is asking for component details, so they'd better be 3529 // asking for specific encryption matching behavior, or be triaged 3530 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3531 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3532 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3533 triaged = false; 3534 } 3535 } 3536 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3537 | PackageManager.MATCH_SYSTEM_ONLY 3538 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3539 triaged = false; 3540 } 3541 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3542 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3543 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3544 } 3545 return updateFlags(flags, userId); 3546 } 3547 3548 /** 3549 * Update given flags when being used to request {@link ApplicationInfo}. 3550 */ 3551 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3552 return updateFlagsForPackage(flags, userId, cookie); 3553 } 3554 3555 /** 3556 * Update given flags when being used to request {@link ComponentInfo}. 3557 */ 3558 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3559 if (cookie instanceof Intent) { 3560 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3561 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3562 } 3563 } 3564 3565 boolean triaged = true; 3566 // Caller is asking for component details, so they'd better be 3567 // asking for specific encryption matching behavior, or be triaged 3568 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3569 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3570 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3571 triaged = false; 3572 } 3573 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3574 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3575 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3576 } 3577 3578 return updateFlags(flags, userId); 3579 } 3580 3581 /** 3582 * Update given flags when being used to request {@link ResolveInfo}. 3583 */ 3584 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3585 // Safe mode means we shouldn't match any third-party components 3586 if (mSafeMode) { 3587 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3588 } 3589 3590 return updateFlagsForComponent(flags, userId, cookie); 3591 } 3592 3593 @Override 3594 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3595 if (!sUserManager.exists(userId)) return null; 3596 flags = updateFlagsForComponent(flags, userId, component); 3597 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3598 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3599 synchronized (mPackages) { 3600 PackageParser.Activity a = mActivities.mActivities.get(component); 3601 3602 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3603 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3604 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3605 if (ps == null) return null; 3606 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3607 userId); 3608 } 3609 if (mResolveComponentName.equals(component)) { 3610 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3611 new PackageUserState(), userId); 3612 } 3613 } 3614 return null; 3615 } 3616 3617 @Override 3618 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3619 String resolvedType) { 3620 synchronized (mPackages) { 3621 if (component.equals(mResolveComponentName)) { 3622 // The resolver supports EVERYTHING! 3623 return true; 3624 } 3625 PackageParser.Activity a = mActivities.mActivities.get(component); 3626 if (a == null) { 3627 return false; 3628 } 3629 for (int i=0; i<a.intents.size(); i++) { 3630 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3631 intent.getData(), intent.getCategories(), TAG) >= 0) { 3632 return true; 3633 } 3634 } 3635 return false; 3636 } 3637 } 3638 3639 @Override 3640 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3641 if (!sUserManager.exists(userId)) return null; 3642 flags = updateFlagsForComponent(flags, userId, component); 3643 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3644 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3645 synchronized (mPackages) { 3646 PackageParser.Activity a = mReceivers.mActivities.get(component); 3647 if (DEBUG_PACKAGE_INFO) Log.v( 3648 TAG, "getReceiverInfo " + component + ": " + a); 3649 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3650 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3651 if (ps == null) return null; 3652 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3653 userId); 3654 } 3655 } 3656 return null; 3657 } 3658 3659 @Override 3660 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3661 if (!sUserManager.exists(userId)) return null; 3662 flags = updateFlagsForComponent(flags, userId, component); 3663 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3664 false /* requireFullPermission */, false /* checkShell */, "get service info"); 3665 synchronized (mPackages) { 3666 PackageParser.Service s = mServices.mServices.get(component); 3667 if (DEBUG_PACKAGE_INFO) Log.v( 3668 TAG, "getServiceInfo " + component + ": " + s); 3669 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3670 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3671 if (ps == null) return null; 3672 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3673 userId); 3674 } 3675 } 3676 return null; 3677 } 3678 3679 @Override 3680 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3681 if (!sUserManager.exists(userId)) return null; 3682 flags = updateFlagsForComponent(flags, userId, component); 3683 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3684 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 3685 synchronized (mPackages) { 3686 PackageParser.Provider p = mProviders.mProviders.get(component); 3687 if (DEBUG_PACKAGE_INFO) Log.v( 3688 TAG, "getProviderInfo " + component + ": " + p); 3689 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3690 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3691 if (ps == null) return null; 3692 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3693 userId); 3694 } 3695 } 3696 return null; 3697 } 3698 3699 @Override 3700 public String[] getSystemSharedLibraryNames() { 3701 Set<String> libSet; 3702 synchronized (mPackages) { 3703 libSet = mSharedLibraries.keySet(); 3704 int size = libSet.size(); 3705 if (size > 0) { 3706 String[] libs = new String[size]; 3707 libSet.toArray(libs); 3708 return libs; 3709 } 3710 } 3711 return null; 3712 } 3713 3714 @Override 3715 public @NonNull String getServicesSystemSharedLibraryPackageName() { 3716 synchronized (mPackages) { 3717 return mServicesSystemSharedLibraryPackageName; 3718 } 3719 } 3720 3721 @Override 3722 public @NonNull String getSharedSystemSharedLibraryPackageName() { 3723 synchronized (mPackages) { 3724 return mSharedSystemSharedLibraryPackageName; 3725 } 3726 } 3727 3728 @Override 3729 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 3730 synchronized (mPackages) { 3731 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values()); 3732 3733 final FeatureInfo fi = new FeatureInfo(); 3734 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3735 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3736 res.add(fi); 3737 3738 return new ParceledListSlice<>(res); 3739 } 3740 } 3741 3742 @Override 3743 public boolean hasSystemFeature(String name, int version) { 3744 synchronized (mPackages) { 3745 final FeatureInfo feat = mAvailableFeatures.get(name); 3746 if (feat == null) { 3747 return false; 3748 } else { 3749 return feat.version >= version; 3750 } 3751 } 3752 } 3753 3754 @Override 3755 public int checkPermission(String permName, String pkgName, int userId) { 3756 if (!sUserManager.exists(userId)) { 3757 return PackageManager.PERMISSION_DENIED; 3758 } 3759 3760 synchronized (mPackages) { 3761 final PackageParser.Package p = mPackages.get(pkgName); 3762 if (p != null && p.mExtras != null) { 3763 final PackageSetting ps = (PackageSetting) p.mExtras; 3764 final PermissionsState permissionsState = ps.getPermissionsState(); 3765 if (permissionsState.hasPermission(permName, userId)) { 3766 return PackageManager.PERMISSION_GRANTED; 3767 } 3768 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3769 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3770 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3771 return PackageManager.PERMISSION_GRANTED; 3772 } 3773 } 3774 } 3775 3776 return PackageManager.PERMISSION_DENIED; 3777 } 3778 3779 @Override 3780 public int checkUidPermission(String permName, int uid) { 3781 final int userId = UserHandle.getUserId(uid); 3782 3783 if (!sUserManager.exists(userId)) { 3784 return PackageManager.PERMISSION_DENIED; 3785 } 3786 3787 synchronized (mPackages) { 3788 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3789 if (obj != null) { 3790 final SettingBase ps = (SettingBase) obj; 3791 final PermissionsState permissionsState = ps.getPermissionsState(); 3792 if (permissionsState.hasPermission(permName, userId)) { 3793 return PackageManager.PERMISSION_GRANTED; 3794 } 3795 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3796 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3797 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3798 return PackageManager.PERMISSION_GRANTED; 3799 } 3800 } else { 3801 ArraySet<String> perms = mSystemPermissions.get(uid); 3802 if (perms != null) { 3803 if (perms.contains(permName)) { 3804 return PackageManager.PERMISSION_GRANTED; 3805 } 3806 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3807 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3808 return PackageManager.PERMISSION_GRANTED; 3809 } 3810 } 3811 } 3812 } 3813 3814 return PackageManager.PERMISSION_DENIED; 3815 } 3816 3817 @Override 3818 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3819 if (UserHandle.getCallingUserId() != userId) { 3820 mContext.enforceCallingPermission( 3821 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3822 "isPermissionRevokedByPolicy for user " + userId); 3823 } 3824 3825 if (checkPermission(permission, packageName, userId) 3826 == PackageManager.PERMISSION_GRANTED) { 3827 return false; 3828 } 3829 3830 final long identity = Binder.clearCallingIdentity(); 3831 try { 3832 final int flags = getPermissionFlags(permission, packageName, userId); 3833 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3834 } finally { 3835 Binder.restoreCallingIdentity(identity); 3836 } 3837 } 3838 3839 @Override 3840 public String getPermissionControllerPackageName() { 3841 synchronized (mPackages) { 3842 return mRequiredInstallerPackage; 3843 } 3844 } 3845 3846 /** 3847 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3848 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3849 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3850 * @param message the message to log on security exception 3851 */ 3852 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3853 boolean checkShell, String message) { 3854 if (userId < 0) { 3855 throw new IllegalArgumentException("Invalid userId " + userId); 3856 } 3857 if (checkShell) { 3858 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3859 } 3860 if (userId == UserHandle.getUserId(callingUid)) return; 3861 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3862 if (requireFullPermission) { 3863 mContext.enforceCallingOrSelfPermission( 3864 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3865 } else { 3866 try { 3867 mContext.enforceCallingOrSelfPermission( 3868 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3869 } catch (SecurityException se) { 3870 mContext.enforceCallingOrSelfPermission( 3871 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3872 } 3873 } 3874 } 3875 } 3876 3877 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3878 if (callingUid == Process.SHELL_UID) { 3879 if (userHandle >= 0 3880 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3881 throw new SecurityException("Shell does not have permission to access user " 3882 + userHandle); 3883 } else if (userHandle < 0) { 3884 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3885 + Debug.getCallers(3)); 3886 } 3887 } 3888 } 3889 3890 private BasePermission findPermissionTreeLP(String permName) { 3891 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3892 if (permName.startsWith(bp.name) && 3893 permName.length() > bp.name.length() && 3894 permName.charAt(bp.name.length()) == '.') { 3895 return bp; 3896 } 3897 } 3898 return null; 3899 } 3900 3901 private BasePermission checkPermissionTreeLP(String permName) { 3902 if (permName != null) { 3903 BasePermission bp = findPermissionTreeLP(permName); 3904 if (bp != null) { 3905 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3906 return bp; 3907 } 3908 throw new SecurityException("Calling uid " 3909 + Binder.getCallingUid() 3910 + " is not allowed to add to permission tree " 3911 + bp.name + " owned by uid " + bp.uid); 3912 } 3913 } 3914 throw new SecurityException("No permission tree found for " + permName); 3915 } 3916 3917 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3918 if (s1 == null) { 3919 return s2 == null; 3920 } 3921 if (s2 == null) { 3922 return false; 3923 } 3924 if (s1.getClass() != s2.getClass()) { 3925 return false; 3926 } 3927 return s1.equals(s2); 3928 } 3929 3930 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3931 if (pi1.icon != pi2.icon) return false; 3932 if (pi1.logo != pi2.logo) return false; 3933 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3934 if (!compareStrings(pi1.name, pi2.name)) return false; 3935 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3936 // We'll take care of setting this one. 3937 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3938 // These are not currently stored in settings. 3939 //if (!compareStrings(pi1.group, pi2.group)) return false; 3940 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3941 //if (pi1.labelRes != pi2.labelRes) return false; 3942 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3943 return true; 3944 } 3945 3946 int permissionInfoFootprint(PermissionInfo info) { 3947 int size = info.name.length(); 3948 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3949 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3950 return size; 3951 } 3952 3953 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3954 int size = 0; 3955 for (BasePermission perm : mSettings.mPermissions.values()) { 3956 if (perm.uid == tree.uid) { 3957 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3958 } 3959 } 3960 return size; 3961 } 3962 3963 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3964 // We calculate the max size of permissions defined by this uid and throw 3965 // if that plus the size of 'info' would exceed our stated maximum. 3966 if (tree.uid != Process.SYSTEM_UID) { 3967 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3968 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3969 throw new SecurityException("Permission tree size cap exceeded"); 3970 } 3971 } 3972 } 3973 3974 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3975 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3976 throw new SecurityException("Label must be specified in permission"); 3977 } 3978 BasePermission tree = checkPermissionTreeLP(info.name); 3979 BasePermission bp = mSettings.mPermissions.get(info.name); 3980 boolean added = bp == null; 3981 boolean changed = true; 3982 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3983 if (added) { 3984 enforcePermissionCapLocked(info, tree); 3985 bp = new BasePermission(info.name, tree.sourcePackage, 3986 BasePermission.TYPE_DYNAMIC); 3987 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3988 throw new SecurityException( 3989 "Not allowed to modify non-dynamic permission " 3990 + info.name); 3991 } else { 3992 if (bp.protectionLevel == fixedLevel 3993 && bp.perm.owner.equals(tree.perm.owner) 3994 && bp.uid == tree.uid 3995 && comparePermissionInfos(bp.perm.info, info)) { 3996 changed = false; 3997 } 3998 } 3999 bp.protectionLevel = fixedLevel; 4000 info = new PermissionInfo(info); 4001 info.protectionLevel = fixedLevel; 4002 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 4003 bp.perm.info.packageName = tree.perm.info.packageName; 4004 bp.uid = tree.uid; 4005 if (added) { 4006 mSettings.mPermissions.put(info.name, bp); 4007 } 4008 if (changed) { 4009 if (!async) { 4010 mSettings.writeLPr(); 4011 } else { 4012 scheduleWriteSettingsLocked(); 4013 } 4014 } 4015 return added; 4016 } 4017 4018 @Override 4019 public boolean addPermission(PermissionInfo info) { 4020 synchronized (mPackages) { 4021 return addPermissionLocked(info, false); 4022 } 4023 } 4024 4025 @Override 4026 public boolean addPermissionAsync(PermissionInfo info) { 4027 synchronized (mPackages) { 4028 return addPermissionLocked(info, true); 4029 } 4030 } 4031 4032 @Override 4033 public void removePermission(String name) { 4034 synchronized (mPackages) { 4035 checkPermissionTreeLP(name); 4036 BasePermission bp = mSettings.mPermissions.get(name); 4037 if (bp != null) { 4038 if (bp.type != BasePermission.TYPE_DYNAMIC) { 4039 throw new SecurityException( 4040 "Not allowed to modify non-dynamic permission " 4041 + name); 4042 } 4043 mSettings.mPermissions.remove(name); 4044 mSettings.writeLPr(); 4045 } 4046 } 4047 } 4048 4049 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 4050 BasePermission bp) { 4051 int index = pkg.requestedPermissions.indexOf(bp.name); 4052 if (index == -1) { 4053 throw new SecurityException("Package " + pkg.packageName 4054 + " has not requested permission " + bp.name); 4055 } 4056 if (!bp.isRuntime() && !bp.isDevelopment()) { 4057 throw new SecurityException("Permission " + bp.name 4058 + " is not a changeable permission type"); 4059 } 4060 } 4061 4062 @Override 4063 public void grantRuntimePermission(String packageName, String name, final int userId) { 4064 if (!sUserManager.exists(userId)) { 4065 Log.e(TAG, "No such user:" + userId); 4066 return; 4067 } 4068 4069 mContext.enforceCallingOrSelfPermission( 4070 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 4071 "grantRuntimePermission"); 4072 4073 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4074 true /* requireFullPermission */, true /* checkShell */, 4075 "grantRuntimePermission"); 4076 4077 final int uid; 4078 final SettingBase sb; 4079 4080 synchronized (mPackages) { 4081 final PackageParser.Package pkg = mPackages.get(packageName); 4082 if (pkg == null) { 4083 throw new IllegalArgumentException("Unknown package: " + packageName); 4084 } 4085 4086 final BasePermission bp = mSettings.mPermissions.get(name); 4087 if (bp == null) { 4088 throw new IllegalArgumentException("Unknown permission: " + name); 4089 } 4090 4091 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4092 4093 // If a permission review is required for legacy apps we represent 4094 // their permissions as always granted runtime ones since we need 4095 // to keep the review required permission flag per user while an 4096 // install permission's state is shared across all users. 4097 if (Build.PERMISSIONS_REVIEW_REQUIRED 4098 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4099 && bp.isRuntime()) { 4100 return; 4101 } 4102 4103 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4104 sb = (SettingBase) pkg.mExtras; 4105 if (sb == null) { 4106 throw new IllegalArgumentException("Unknown package: " + packageName); 4107 } 4108 4109 final PermissionsState permissionsState = sb.getPermissionsState(); 4110 4111 final int flags = permissionsState.getPermissionFlags(name, userId); 4112 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4113 throw new SecurityException("Cannot grant system fixed permission " 4114 + name + " for package " + packageName); 4115 } 4116 4117 if (bp.isDevelopment()) { 4118 // Development permissions must be handled specially, since they are not 4119 // normal runtime permissions. For now they apply to all users. 4120 if (permissionsState.grantInstallPermission(bp) != 4121 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4122 scheduleWriteSettingsLocked(); 4123 } 4124 return; 4125 } 4126 4127 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4128 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4129 return; 4130 } 4131 4132 final int result = permissionsState.grantRuntimePermission(bp, userId); 4133 switch (result) { 4134 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4135 return; 4136 } 4137 4138 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4139 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4140 mHandler.post(new Runnable() { 4141 @Override 4142 public void run() { 4143 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4144 } 4145 }); 4146 } 4147 break; 4148 } 4149 4150 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4151 4152 // Not critical if that is lost - app has to request again. 4153 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4154 } 4155 4156 // Only need to do this if user is initialized. Otherwise it's a new user 4157 // and there are no processes running as the user yet and there's no need 4158 // to make an expensive call to remount processes for the changed permissions. 4159 if (READ_EXTERNAL_STORAGE.equals(name) 4160 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4161 final long token = Binder.clearCallingIdentity(); 4162 try { 4163 if (sUserManager.isInitialized(userId)) { 4164 MountServiceInternal mountServiceInternal = LocalServices.getService( 4165 MountServiceInternal.class); 4166 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 4167 } 4168 } finally { 4169 Binder.restoreCallingIdentity(token); 4170 } 4171 } 4172 } 4173 4174 @Override 4175 public void revokeRuntimePermission(String packageName, String name, int userId) { 4176 if (!sUserManager.exists(userId)) { 4177 Log.e(TAG, "No such user:" + userId); 4178 return; 4179 } 4180 4181 mContext.enforceCallingOrSelfPermission( 4182 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4183 "revokeRuntimePermission"); 4184 4185 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4186 true /* requireFullPermission */, true /* checkShell */, 4187 "revokeRuntimePermission"); 4188 4189 final int appId; 4190 4191 synchronized (mPackages) { 4192 final PackageParser.Package pkg = mPackages.get(packageName); 4193 if (pkg == null) { 4194 throw new IllegalArgumentException("Unknown package: " + packageName); 4195 } 4196 4197 final BasePermission bp = mSettings.mPermissions.get(name); 4198 if (bp == null) { 4199 throw new IllegalArgumentException("Unknown permission: " + name); 4200 } 4201 4202 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4203 4204 // If a permission review is required for legacy apps we represent 4205 // their permissions as always granted runtime ones since we need 4206 // to keep the review required permission flag per user while an 4207 // install permission's state is shared across all users. 4208 if (Build.PERMISSIONS_REVIEW_REQUIRED 4209 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4210 && bp.isRuntime()) { 4211 return; 4212 } 4213 4214 SettingBase sb = (SettingBase) pkg.mExtras; 4215 if (sb == null) { 4216 throw new IllegalArgumentException("Unknown package: " + packageName); 4217 } 4218 4219 final PermissionsState permissionsState = sb.getPermissionsState(); 4220 4221 final int flags = permissionsState.getPermissionFlags(name, userId); 4222 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4223 throw new SecurityException("Cannot revoke system fixed permission " 4224 + name + " for package " + packageName); 4225 } 4226 4227 if (bp.isDevelopment()) { 4228 // Development permissions must be handled specially, since they are not 4229 // normal runtime permissions. For now they apply to all users. 4230 if (permissionsState.revokeInstallPermission(bp) != 4231 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4232 scheduleWriteSettingsLocked(); 4233 } 4234 return; 4235 } 4236 4237 if (permissionsState.revokeRuntimePermission(bp, userId) == 4238 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4239 return; 4240 } 4241 4242 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4243 4244 // Critical, after this call app should never have the permission. 4245 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4246 4247 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4248 } 4249 4250 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4251 } 4252 4253 @Override 4254 public void resetRuntimePermissions() { 4255 mContext.enforceCallingOrSelfPermission( 4256 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4257 "revokeRuntimePermission"); 4258 4259 int callingUid = Binder.getCallingUid(); 4260 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4261 mContext.enforceCallingOrSelfPermission( 4262 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4263 "resetRuntimePermissions"); 4264 } 4265 4266 synchronized (mPackages) { 4267 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4268 for (int userId : UserManagerService.getInstance().getUserIds()) { 4269 final int packageCount = mPackages.size(); 4270 for (int i = 0; i < packageCount; i++) { 4271 PackageParser.Package pkg = mPackages.valueAt(i); 4272 if (!(pkg.mExtras instanceof PackageSetting)) { 4273 continue; 4274 } 4275 PackageSetting ps = (PackageSetting) pkg.mExtras; 4276 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4277 } 4278 } 4279 } 4280 } 4281 4282 @Override 4283 public int getPermissionFlags(String name, String packageName, int userId) { 4284 if (!sUserManager.exists(userId)) { 4285 return 0; 4286 } 4287 4288 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4289 4290 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4291 true /* requireFullPermission */, false /* checkShell */, 4292 "getPermissionFlags"); 4293 4294 synchronized (mPackages) { 4295 final PackageParser.Package pkg = mPackages.get(packageName); 4296 if (pkg == null) { 4297 return 0; 4298 } 4299 4300 final BasePermission bp = mSettings.mPermissions.get(name); 4301 if (bp == null) { 4302 return 0; 4303 } 4304 4305 SettingBase sb = (SettingBase) pkg.mExtras; 4306 if (sb == null) { 4307 return 0; 4308 } 4309 4310 PermissionsState permissionsState = sb.getPermissionsState(); 4311 return permissionsState.getPermissionFlags(name, userId); 4312 } 4313 } 4314 4315 @Override 4316 public void updatePermissionFlags(String name, String packageName, int flagMask, 4317 int flagValues, int userId) { 4318 if (!sUserManager.exists(userId)) { 4319 return; 4320 } 4321 4322 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4323 4324 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4325 true /* requireFullPermission */, true /* checkShell */, 4326 "updatePermissionFlags"); 4327 4328 // Only the system can change these flags and nothing else. 4329 if (getCallingUid() != Process.SYSTEM_UID) { 4330 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4331 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4332 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4333 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4334 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4335 } 4336 4337 synchronized (mPackages) { 4338 final PackageParser.Package pkg = mPackages.get(packageName); 4339 if (pkg == null) { 4340 throw new IllegalArgumentException("Unknown package: " + packageName); 4341 } 4342 4343 final BasePermission bp = mSettings.mPermissions.get(name); 4344 if (bp == null) { 4345 throw new IllegalArgumentException("Unknown permission: " + name); 4346 } 4347 4348 SettingBase sb = (SettingBase) pkg.mExtras; 4349 if (sb == null) { 4350 throw new IllegalArgumentException("Unknown package: " + packageName); 4351 } 4352 4353 PermissionsState permissionsState = sb.getPermissionsState(); 4354 4355 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4356 4357 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4358 // Install and runtime permissions are stored in different places, 4359 // so figure out what permission changed and persist the change. 4360 if (permissionsState.getInstallPermissionState(name) != null) { 4361 scheduleWriteSettingsLocked(); 4362 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4363 || hadState) { 4364 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4365 } 4366 } 4367 } 4368 } 4369 4370 /** 4371 * Update the permission flags for all packages and runtime permissions of a user in order 4372 * to allow device or profile owner to remove POLICY_FIXED. 4373 */ 4374 @Override 4375 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4376 if (!sUserManager.exists(userId)) { 4377 return; 4378 } 4379 4380 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4381 4382 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4383 true /* requireFullPermission */, true /* checkShell */, 4384 "updatePermissionFlagsForAllApps"); 4385 4386 // Only the system can change system fixed flags. 4387 if (getCallingUid() != Process.SYSTEM_UID) { 4388 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4389 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4390 } 4391 4392 synchronized (mPackages) { 4393 boolean changed = false; 4394 final int packageCount = mPackages.size(); 4395 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4396 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4397 SettingBase sb = (SettingBase) pkg.mExtras; 4398 if (sb == null) { 4399 continue; 4400 } 4401 PermissionsState permissionsState = sb.getPermissionsState(); 4402 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4403 userId, flagMask, flagValues); 4404 } 4405 if (changed) { 4406 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4407 } 4408 } 4409 } 4410 4411 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4412 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4413 != PackageManager.PERMISSION_GRANTED 4414 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4415 != PackageManager.PERMISSION_GRANTED) { 4416 throw new SecurityException(message + " requires " 4417 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4418 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4419 } 4420 } 4421 4422 @Override 4423 public boolean shouldShowRequestPermissionRationale(String permissionName, 4424 String packageName, int userId) { 4425 if (UserHandle.getCallingUserId() != userId) { 4426 mContext.enforceCallingPermission( 4427 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4428 "canShowRequestPermissionRationale for user " + userId); 4429 } 4430 4431 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4432 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4433 return false; 4434 } 4435 4436 if (checkPermission(permissionName, packageName, userId) 4437 == PackageManager.PERMISSION_GRANTED) { 4438 return false; 4439 } 4440 4441 final int flags; 4442 4443 final long identity = Binder.clearCallingIdentity(); 4444 try { 4445 flags = getPermissionFlags(permissionName, 4446 packageName, userId); 4447 } finally { 4448 Binder.restoreCallingIdentity(identity); 4449 } 4450 4451 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4452 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4453 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4454 4455 if ((flags & fixedFlags) != 0) { 4456 return false; 4457 } 4458 4459 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4460 } 4461 4462 @Override 4463 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4464 mContext.enforceCallingOrSelfPermission( 4465 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4466 "addOnPermissionsChangeListener"); 4467 4468 synchronized (mPackages) { 4469 mOnPermissionChangeListeners.addListenerLocked(listener); 4470 } 4471 } 4472 4473 @Override 4474 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4475 synchronized (mPackages) { 4476 mOnPermissionChangeListeners.removeListenerLocked(listener); 4477 } 4478 } 4479 4480 @Override 4481 public boolean isProtectedBroadcast(String actionName) { 4482 synchronized (mPackages) { 4483 if (mProtectedBroadcasts.contains(actionName)) { 4484 return true; 4485 } else if (actionName != null) { 4486 // TODO: remove these terrible hacks 4487 if (actionName.startsWith("android.net.netmon.lingerExpired") 4488 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4489 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 4490 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 4491 return true; 4492 } 4493 } 4494 } 4495 return false; 4496 } 4497 4498 @Override 4499 public int checkSignatures(String pkg1, String pkg2) { 4500 synchronized (mPackages) { 4501 final PackageParser.Package p1 = mPackages.get(pkg1); 4502 final PackageParser.Package p2 = mPackages.get(pkg2); 4503 if (p1 == null || p1.mExtras == null 4504 || p2 == null || p2.mExtras == null) { 4505 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4506 } 4507 return compareSignatures(p1.mSignatures, p2.mSignatures); 4508 } 4509 } 4510 4511 @Override 4512 public int checkUidSignatures(int uid1, int uid2) { 4513 // Map to base uids. 4514 uid1 = UserHandle.getAppId(uid1); 4515 uid2 = UserHandle.getAppId(uid2); 4516 // reader 4517 synchronized (mPackages) { 4518 Signature[] s1; 4519 Signature[] s2; 4520 Object obj = mSettings.getUserIdLPr(uid1); 4521 if (obj != null) { 4522 if (obj instanceof SharedUserSetting) { 4523 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4524 } else if (obj instanceof PackageSetting) { 4525 s1 = ((PackageSetting)obj).signatures.mSignatures; 4526 } else { 4527 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4528 } 4529 } else { 4530 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4531 } 4532 obj = mSettings.getUserIdLPr(uid2); 4533 if (obj != null) { 4534 if (obj instanceof SharedUserSetting) { 4535 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4536 } else if (obj instanceof PackageSetting) { 4537 s2 = ((PackageSetting)obj).signatures.mSignatures; 4538 } else { 4539 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4540 } 4541 } else { 4542 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4543 } 4544 return compareSignatures(s1, s2); 4545 } 4546 } 4547 4548 /** 4549 * This method should typically only be used when granting or revoking 4550 * permissions, since the app may immediately restart after this call. 4551 * <p> 4552 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 4553 * guard your work against the app being relaunched. 4554 */ 4555 private void killUid(int appId, int userId, String reason) { 4556 final long identity = Binder.clearCallingIdentity(); 4557 try { 4558 IActivityManager am = ActivityManagerNative.getDefault(); 4559 if (am != null) { 4560 try { 4561 am.killUid(appId, userId, reason); 4562 } catch (RemoteException e) { 4563 /* ignore - same process */ 4564 } 4565 } 4566 } finally { 4567 Binder.restoreCallingIdentity(identity); 4568 } 4569 } 4570 4571 /** 4572 * Compares two sets of signatures. Returns: 4573 * <br /> 4574 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4575 * <br /> 4576 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4577 * <br /> 4578 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4579 * <br /> 4580 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4581 * <br /> 4582 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4583 */ 4584 static int compareSignatures(Signature[] s1, Signature[] s2) { 4585 if (s1 == null) { 4586 return s2 == null 4587 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4588 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4589 } 4590 4591 if (s2 == null) { 4592 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4593 } 4594 4595 if (s1.length != s2.length) { 4596 return PackageManager.SIGNATURE_NO_MATCH; 4597 } 4598 4599 // Since both signature sets are of size 1, we can compare without HashSets. 4600 if (s1.length == 1) { 4601 return s1[0].equals(s2[0]) ? 4602 PackageManager.SIGNATURE_MATCH : 4603 PackageManager.SIGNATURE_NO_MATCH; 4604 } 4605 4606 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4607 for (Signature sig : s1) { 4608 set1.add(sig); 4609 } 4610 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4611 for (Signature sig : s2) { 4612 set2.add(sig); 4613 } 4614 // Make sure s2 contains all signatures in s1. 4615 if (set1.equals(set2)) { 4616 return PackageManager.SIGNATURE_MATCH; 4617 } 4618 return PackageManager.SIGNATURE_NO_MATCH; 4619 } 4620 4621 /** 4622 * If the database version for this type of package (internal storage or 4623 * external storage) is less than the version where package signatures 4624 * were updated, return true. 4625 */ 4626 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4627 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4628 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4629 } 4630 4631 /** 4632 * Used for backward compatibility to make sure any packages with 4633 * certificate chains get upgraded to the new style. {@code existingSigs} 4634 * will be in the old format (since they were stored on disk from before the 4635 * system upgrade) and {@code scannedSigs} will be in the newer format. 4636 */ 4637 private int compareSignaturesCompat(PackageSignatures existingSigs, 4638 PackageParser.Package scannedPkg) { 4639 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4640 return PackageManager.SIGNATURE_NO_MATCH; 4641 } 4642 4643 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4644 for (Signature sig : existingSigs.mSignatures) { 4645 existingSet.add(sig); 4646 } 4647 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4648 for (Signature sig : scannedPkg.mSignatures) { 4649 try { 4650 Signature[] chainSignatures = sig.getChainSignatures(); 4651 for (Signature chainSig : chainSignatures) { 4652 scannedCompatSet.add(chainSig); 4653 } 4654 } catch (CertificateEncodingException e) { 4655 scannedCompatSet.add(sig); 4656 } 4657 } 4658 /* 4659 * Make sure the expanded scanned set contains all signatures in the 4660 * existing one. 4661 */ 4662 if (scannedCompatSet.equals(existingSet)) { 4663 // Migrate the old signatures to the new scheme. 4664 existingSigs.assignSignatures(scannedPkg.mSignatures); 4665 // The new KeySets will be re-added later in the scanning process. 4666 synchronized (mPackages) { 4667 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4668 } 4669 return PackageManager.SIGNATURE_MATCH; 4670 } 4671 return PackageManager.SIGNATURE_NO_MATCH; 4672 } 4673 4674 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4675 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4676 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4677 } 4678 4679 private int compareSignaturesRecover(PackageSignatures existingSigs, 4680 PackageParser.Package scannedPkg) { 4681 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4682 return PackageManager.SIGNATURE_NO_MATCH; 4683 } 4684 4685 String msg = null; 4686 try { 4687 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4688 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4689 + scannedPkg.packageName); 4690 return PackageManager.SIGNATURE_MATCH; 4691 } 4692 } catch (CertificateException e) { 4693 msg = e.getMessage(); 4694 } 4695 4696 logCriticalInfo(Log.INFO, 4697 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4698 return PackageManager.SIGNATURE_NO_MATCH; 4699 } 4700 4701 @Override 4702 public List<String> getAllPackages() { 4703 synchronized (mPackages) { 4704 return new ArrayList<String>(mPackages.keySet()); 4705 } 4706 } 4707 4708 @Override 4709 public String[] getPackagesForUid(int uid) { 4710 uid = UserHandle.getAppId(uid); 4711 // reader 4712 synchronized (mPackages) { 4713 Object obj = mSettings.getUserIdLPr(uid); 4714 if (obj instanceof SharedUserSetting) { 4715 final SharedUserSetting sus = (SharedUserSetting) obj; 4716 final int N = sus.packages.size(); 4717 final String[] res = new String[N]; 4718 final Iterator<PackageSetting> it = sus.packages.iterator(); 4719 int i = 0; 4720 while (it.hasNext()) { 4721 res[i++] = it.next().name; 4722 } 4723 return res; 4724 } else if (obj instanceof PackageSetting) { 4725 final PackageSetting ps = (PackageSetting) obj; 4726 return new String[] { ps.name }; 4727 } 4728 } 4729 return null; 4730 } 4731 4732 @Override 4733 public String getNameForUid(int uid) { 4734 // reader 4735 synchronized (mPackages) { 4736 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4737 if (obj instanceof SharedUserSetting) { 4738 final SharedUserSetting sus = (SharedUserSetting) obj; 4739 return sus.name + ":" + sus.userId; 4740 } else if (obj instanceof PackageSetting) { 4741 final PackageSetting ps = (PackageSetting) obj; 4742 return ps.name; 4743 } 4744 } 4745 return null; 4746 } 4747 4748 @Override 4749 public int getUidForSharedUser(String sharedUserName) { 4750 if(sharedUserName == null) { 4751 return -1; 4752 } 4753 // reader 4754 synchronized (mPackages) { 4755 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4756 if (suid == null) { 4757 return -1; 4758 } 4759 return suid.userId; 4760 } 4761 } 4762 4763 @Override 4764 public int getFlagsForUid(int uid) { 4765 synchronized (mPackages) { 4766 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4767 if (obj instanceof SharedUserSetting) { 4768 final SharedUserSetting sus = (SharedUserSetting) obj; 4769 return sus.pkgFlags; 4770 } else if (obj instanceof PackageSetting) { 4771 final PackageSetting ps = (PackageSetting) obj; 4772 return ps.pkgFlags; 4773 } 4774 } 4775 return 0; 4776 } 4777 4778 @Override 4779 public int getPrivateFlagsForUid(int uid) { 4780 synchronized (mPackages) { 4781 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4782 if (obj instanceof SharedUserSetting) { 4783 final SharedUserSetting sus = (SharedUserSetting) obj; 4784 return sus.pkgPrivateFlags; 4785 } else if (obj instanceof PackageSetting) { 4786 final PackageSetting ps = (PackageSetting) obj; 4787 return ps.pkgPrivateFlags; 4788 } 4789 } 4790 return 0; 4791 } 4792 4793 @Override 4794 public boolean isUidPrivileged(int uid) { 4795 uid = UserHandle.getAppId(uid); 4796 // reader 4797 synchronized (mPackages) { 4798 Object obj = mSettings.getUserIdLPr(uid); 4799 if (obj instanceof SharedUserSetting) { 4800 final SharedUserSetting sus = (SharedUserSetting) obj; 4801 final Iterator<PackageSetting> it = sus.packages.iterator(); 4802 while (it.hasNext()) { 4803 if (it.next().isPrivileged()) { 4804 return true; 4805 } 4806 } 4807 } else if (obj instanceof PackageSetting) { 4808 final PackageSetting ps = (PackageSetting) obj; 4809 return ps.isPrivileged(); 4810 } 4811 } 4812 return false; 4813 } 4814 4815 @Override 4816 public String[] getAppOpPermissionPackages(String permissionName) { 4817 synchronized (mPackages) { 4818 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4819 if (pkgs == null) { 4820 return null; 4821 } 4822 return pkgs.toArray(new String[pkgs.size()]); 4823 } 4824 } 4825 4826 @Override 4827 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4828 int flags, int userId) { 4829 try { 4830 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 4831 4832 if (!sUserManager.exists(userId)) return null; 4833 flags = updateFlagsForResolve(flags, userId, intent); 4834 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4835 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 4836 4837 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 4838 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 4839 flags, userId); 4840 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4841 4842 final ResolveInfo bestChoice = 4843 chooseBestActivity(intent, resolvedType, flags, query, userId); 4844 4845 if (isEphemeralAllowed(intent, query, userId)) { 4846 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 4847 final EphemeralResolveInfo ai = 4848 getEphemeralResolveInfo(intent, resolvedType, userId); 4849 if (ai != null) { 4850 if (DEBUG_EPHEMERAL) { 4851 Slog.v(TAG, "Returning an EphemeralResolveInfo"); 4852 } 4853 bestChoice.ephemeralInstaller = mEphemeralInstallerInfo; 4854 bestChoice.ephemeralResolveInfo = ai; 4855 } 4856 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4857 } 4858 return bestChoice; 4859 } finally { 4860 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4861 } 4862 } 4863 4864 @Override 4865 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4866 IntentFilter filter, int match, ComponentName activity) { 4867 final int userId = UserHandle.getCallingUserId(); 4868 if (DEBUG_PREFERRED) { 4869 Log.v(TAG, "setLastChosenActivity intent=" + intent 4870 + " resolvedType=" + resolvedType 4871 + " flags=" + flags 4872 + " filter=" + filter 4873 + " match=" + match 4874 + " activity=" + activity); 4875 filter.dump(new PrintStreamPrinter(System.out), " "); 4876 } 4877 intent.setComponent(null); 4878 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4879 userId); 4880 // Find any earlier preferred or last chosen entries and nuke them 4881 findPreferredActivity(intent, resolvedType, 4882 flags, query, 0, false, true, false, userId); 4883 // Add the new activity as the last chosen for this filter 4884 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4885 "Setting last chosen"); 4886 } 4887 4888 @Override 4889 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4890 final int userId = UserHandle.getCallingUserId(); 4891 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4892 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4893 userId); 4894 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4895 false, false, false, userId); 4896 } 4897 4898 4899 private boolean isEphemeralAllowed( 4900 Intent intent, List<ResolveInfo> resolvedActivites, int userId) { 4901 // Short circuit and return early if possible. 4902 if (DISABLE_EPHEMERAL_APPS) { 4903 return false; 4904 } 4905 final int callingUser = UserHandle.getCallingUserId(); 4906 if (callingUser != UserHandle.USER_SYSTEM) { 4907 return false; 4908 } 4909 if (mEphemeralResolverConnection == null) { 4910 return false; 4911 } 4912 if (intent.getComponent() != null) { 4913 return false; 4914 } 4915 if (intent.getPackage() != null) { 4916 return false; 4917 } 4918 final boolean isWebUri = hasWebURI(intent); 4919 if (!isWebUri) { 4920 return false; 4921 } 4922 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4923 synchronized (mPackages) { 4924 final int count = resolvedActivites.size(); 4925 for (int n = 0; n < count; n++) { 4926 ResolveInfo info = resolvedActivites.get(n); 4927 String packageName = info.activityInfo.packageName; 4928 PackageSetting ps = mSettings.mPackages.get(packageName); 4929 if (ps != null) { 4930 // Try to get the status from User settings first 4931 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4932 int status = (int) (packedStatus >> 32); 4933 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4934 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4935 if (DEBUG_EPHEMERAL) { 4936 Slog.v(TAG, "DENY ephemeral apps;" 4937 + " pkg: " + packageName + ", status: " + status); 4938 } 4939 return false; 4940 } 4941 } 4942 } 4943 } 4944 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4945 return true; 4946 } 4947 4948 private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType, 4949 int userId) { 4950 MessageDigest digest = null; 4951 try { 4952 digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM); 4953 } catch (NoSuchAlgorithmException e) { 4954 // If we can't create a digest, ignore ephemeral apps. 4955 return null; 4956 } 4957 4958 final byte[] hostBytes = intent.getData().getHost().getBytes(); 4959 final byte[] digestBytes = digest.digest(hostBytes); 4960 int shaPrefix = 4961 digestBytes[0] << 24 4962 | digestBytes[1] << 16 4963 | digestBytes[2] << 8 4964 | digestBytes[3] << 0; 4965 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4966 mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix); 4967 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4968 // No hash prefix match; there are no ephemeral apps for this domain. 4969 return null; 4970 } 4971 for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) { 4972 EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i); 4973 if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) { 4974 continue; 4975 } 4976 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 4977 // No filters; this should never happen. 4978 if (filters.isEmpty()) { 4979 continue; 4980 } 4981 // We have a domain match; resolve the filters to see if anything matches. 4982 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4983 for (int j = filters.size() - 1; j >= 0; --j) { 4984 final EphemeralResolveIntentInfo intentInfo = 4985 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 4986 ephemeralResolver.addFilter(intentInfo); 4987 } 4988 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 4989 intent, resolvedType, false /*defaultOnly*/, userId); 4990 if (!matchedResolveInfoList.isEmpty()) { 4991 return matchedResolveInfoList.get(0); 4992 } 4993 } 4994 // Hash or filter mis-match; no ephemeral apps for this domain. 4995 return null; 4996 } 4997 4998 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4999 int flags, List<ResolveInfo> query, int userId) { 5000 if (query != null) { 5001 final int N = query.size(); 5002 if (N == 1) { 5003 return query.get(0); 5004 } else if (N > 1) { 5005 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 5006 // If there is more than one activity with the same priority, 5007 // then let the user decide between them. 5008 ResolveInfo r0 = query.get(0); 5009 ResolveInfo r1 = query.get(1); 5010 if (DEBUG_INTENT_MATCHING || debug) { 5011 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 5012 + r1.activityInfo.name + "=" + r1.priority); 5013 } 5014 // If the first activity has a higher priority, or a different 5015 // default, then it is always desirable to pick it. 5016 if (r0.priority != r1.priority 5017 || r0.preferredOrder != r1.preferredOrder 5018 || r0.isDefault != r1.isDefault) { 5019 return query.get(0); 5020 } 5021 // If we have saved a preference for a preferred activity for 5022 // this Intent, use that. 5023 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 5024 flags, query, r0.priority, true, false, debug, userId); 5025 if (ri != null) { 5026 return ri; 5027 } 5028 ri = new ResolveInfo(mResolveInfo); 5029 ri.activityInfo = new ActivityInfo(ri.activityInfo); 5030 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 5031 // If all of the options come from the same package, show the application's 5032 // label and icon instead of the generic resolver's. 5033 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 5034 // and then throw away the ResolveInfo itself, meaning that the caller loses 5035 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 5036 // a fallback for this case; we only set the target package's resources on 5037 // the ResolveInfo, not the ActivityInfo. 5038 final String intentPackage = intent.getPackage(); 5039 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 5040 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 5041 ri.resolvePackageName = intentPackage; 5042 if (userNeedsBadging(userId)) { 5043 ri.noResourceId = true; 5044 } else { 5045 ri.icon = appi.icon; 5046 } 5047 ri.iconResourceId = appi.icon; 5048 ri.labelRes = appi.labelRes; 5049 } 5050 ri.activityInfo.applicationInfo = new ApplicationInfo( 5051 ri.activityInfo.applicationInfo); 5052 if (userId != 0) { 5053 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 5054 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 5055 } 5056 // Make sure that the resolver is displayable in car mode 5057 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 5058 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 5059 return ri; 5060 } 5061 } 5062 return null; 5063 } 5064 5065 /** 5066 * Return true if the given list is not empty and all of its contents have 5067 * an activityInfo with the given package name. 5068 */ 5069 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 5070 if (ArrayUtils.isEmpty(list)) { 5071 return false; 5072 } 5073 for (int i = 0, N = list.size(); i < N; i++) { 5074 final ResolveInfo ri = list.get(i); 5075 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 5076 if (ai == null || !packageName.equals(ai.packageName)) { 5077 return false; 5078 } 5079 } 5080 return true; 5081 } 5082 5083 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 5084 int flags, List<ResolveInfo> query, boolean debug, int userId) { 5085 final int N = query.size(); 5086 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 5087 .get(userId); 5088 // Get the list of persistent preferred activities that handle the intent 5089 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 5090 List<PersistentPreferredActivity> pprefs = ppir != null 5091 ? ppir.queryIntent(intent, resolvedType, 5092 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5093 : null; 5094 if (pprefs != null && pprefs.size() > 0) { 5095 final int M = pprefs.size(); 5096 for (int i=0; i<M; i++) { 5097 final PersistentPreferredActivity ppa = pprefs.get(i); 5098 if (DEBUG_PREFERRED || debug) { 5099 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 5100 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 5101 + "\n component=" + ppa.mComponent); 5102 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5103 } 5104 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 5105 flags | MATCH_DISABLED_COMPONENTS, userId); 5106 if (DEBUG_PREFERRED || debug) { 5107 Slog.v(TAG, "Found persistent preferred activity:"); 5108 if (ai != null) { 5109 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5110 } else { 5111 Slog.v(TAG, " null"); 5112 } 5113 } 5114 if (ai == null) { 5115 // This previously registered persistent preferred activity 5116 // component is no longer known. Ignore it and do NOT remove it. 5117 continue; 5118 } 5119 for (int j=0; j<N; j++) { 5120 final ResolveInfo ri = query.get(j); 5121 if (!ri.activityInfo.applicationInfo.packageName 5122 .equals(ai.applicationInfo.packageName)) { 5123 continue; 5124 } 5125 if (!ri.activityInfo.name.equals(ai.name)) { 5126 continue; 5127 } 5128 // Found a persistent preference that can handle the intent. 5129 if (DEBUG_PREFERRED || debug) { 5130 Slog.v(TAG, "Returning persistent preferred activity: " + 5131 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5132 } 5133 return ri; 5134 } 5135 } 5136 } 5137 return null; 5138 } 5139 5140 // TODO: handle preferred activities missing while user has amnesia 5141 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5142 List<ResolveInfo> query, int priority, boolean always, 5143 boolean removeMatches, boolean debug, int userId) { 5144 if (!sUserManager.exists(userId)) return null; 5145 flags = updateFlagsForResolve(flags, userId, intent); 5146 // writer 5147 synchronized (mPackages) { 5148 if (intent.getSelector() != null) { 5149 intent = intent.getSelector(); 5150 } 5151 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 5152 5153 // Try to find a matching persistent preferred activity. 5154 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5155 debug, userId); 5156 5157 // If a persistent preferred activity matched, use it. 5158 if (pri != null) { 5159 return pri; 5160 } 5161 5162 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5163 // Get the list of preferred activities that handle the intent 5164 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5165 List<PreferredActivity> prefs = pir != null 5166 ? pir.queryIntent(intent, resolvedType, 5167 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5168 : null; 5169 if (prefs != null && prefs.size() > 0) { 5170 boolean changed = false; 5171 try { 5172 // First figure out how good the original match set is. 5173 // We will only allow preferred activities that came 5174 // from the same match quality. 5175 int match = 0; 5176 5177 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5178 5179 final int N = query.size(); 5180 for (int j=0; j<N; j++) { 5181 final ResolveInfo ri = query.get(j); 5182 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5183 + ": 0x" + Integer.toHexString(match)); 5184 if (ri.match > match) { 5185 match = ri.match; 5186 } 5187 } 5188 5189 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5190 + Integer.toHexString(match)); 5191 5192 match &= IntentFilter.MATCH_CATEGORY_MASK; 5193 final int M = prefs.size(); 5194 for (int i=0; i<M; i++) { 5195 final PreferredActivity pa = prefs.get(i); 5196 if (DEBUG_PREFERRED || debug) { 5197 Slog.v(TAG, "Checking PreferredActivity ds=" 5198 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5199 + "\n component=" + pa.mPref.mComponent); 5200 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5201 } 5202 if (pa.mPref.mMatch != match) { 5203 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5204 + Integer.toHexString(pa.mPref.mMatch)); 5205 continue; 5206 } 5207 // If it's not an "always" type preferred activity and that's what we're 5208 // looking for, skip it. 5209 if (always && !pa.mPref.mAlways) { 5210 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5211 continue; 5212 } 5213 final ActivityInfo ai = getActivityInfo( 5214 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5215 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5216 userId); 5217 if (DEBUG_PREFERRED || debug) { 5218 Slog.v(TAG, "Found preferred activity:"); 5219 if (ai != null) { 5220 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5221 } else { 5222 Slog.v(TAG, " null"); 5223 } 5224 } 5225 if (ai == null) { 5226 // This previously registered preferred activity 5227 // component is no longer known. Most likely an update 5228 // to the app was installed and in the new version this 5229 // component no longer exists. Clean it up by removing 5230 // it from the preferred activities list, and skip it. 5231 Slog.w(TAG, "Removing dangling preferred activity: " 5232 + pa.mPref.mComponent); 5233 pir.removeFilter(pa); 5234 changed = true; 5235 continue; 5236 } 5237 for (int j=0; j<N; j++) { 5238 final ResolveInfo ri = query.get(j); 5239 if (!ri.activityInfo.applicationInfo.packageName 5240 .equals(ai.applicationInfo.packageName)) { 5241 continue; 5242 } 5243 if (!ri.activityInfo.name.equals(ai.name)) { 5244 continue; 5245 } 5246 5247 if (removeMatches) { 5248 pir.removeFilter(pa); 5249 changed = true; 5250 if (DEBUG_PREFERRED) { 5251 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 5252 } 5253 break; 5254 } 5255 5256 // Okay we found a previously set preferred or last chosen app. 5257 // If the result set is different from when this 5258 // was created, we need to clear it and re-ask the 5259 // user their preference, if we're looking for an "always" type entry. 5260 if (always && !pa.mPref.sameSet(query)) { 5261 Slog.i(TAG, "Result set changed, dropping preferred activity for " 5262 + intent + " type " + resolvedType); 5263 if (DEBUG_PREFERRED) { 5264 Slog.v(TAG, "Removing preferred activity since set changed " 5265 + pa.mPref.mComponent); 5266 } 5267 pir.removeFilter(pa); 5268 // Re-add the filter as a "last chosen" entry (!always) 5269 PreferredActivity lastChosen = new PreferredActivity( 5270 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5271 pir.addFilter(lastChosen); 5272 changed = true; 5273 return null; 5274 } 5275 5276 // Yay! Either the set matched or we're looking for the last chosen 5277 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5278 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5279 return ri; 5280 } 5281 } 5282 } finally { 5283 if (changed) { 5284 if (DEBUG_PREFERRED) { 5285 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5286 } 5287 scheduleWritePackageRestrictionsLocked(userId); 5288 } 5289 } 5290 } 5291 } 5292 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5293 return null; 5294 } 5295 5296 /* 5297 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5298 */ 5299 @Override 5300 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5301 int targetUserId) { 5302 mContext.enforceCallingOrSelfPermission( 5303 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5304 List<CrossProfileIntentFilter> matches = 5305 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5306 if (matches != null) { 5307 int size = matches.size(); 5308 for (int i = 0; i < size; i++) { 5309 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5310 } 5311 } 5312 if (hasWebURI(intent)) { 5313 // cross-profile app linking works only towards the parent. 5314 final UserInfo parent = getProfileParent(sourceUserId); 5315 synchronized(mPackages) { 5316 int flags = updateFlagsForResolve(0, parent.id, intent); 5317 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5318 intent, resolvedType, flags, sourceUserId, parent.id); 5319 return xpDomainInfo != null; 5320 } 5321 } 5322 return false; 5323 } 5324 5325 private UserInfo getProfileParent(int userId) { 5326 final long identity = Binder.clearCallingIdentity(); 5327 try { 5328 return sUserManager.getProfileParent(userId); 5329 } finally { 5330 Binder.restoreCallingIdentity(identity); 5331 } 5332 } 5333 5334 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5335 String resolvedType, int userId) { 5336 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5337 if (resolver != null) { 5338 return resolver.queryIntent(intent, resolvedType, false, userId); 5339 } 5340 return null; 5341 } 5342 5343 @Override 5344 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5345 String resolvedType, int flags, int userId) { 5346 try { 5347 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5348 5349 return new ParceledListSlice<>( 5350 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5351 } finally { 5352 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5353 } 5354 } 5355 5356 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5357 String resolvedType, int flags, int userId) { 5358 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5359 flags = updateFlagsForResolve(flags, userId, intent); 5360 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5361 false /* requireFullPermission */, false /* checkShell */, 5362 "query intent activities"); 5363 ComponentName comp = intent.getComponent(); 5364 if (comp == null) { 5365 if (intent.getSelector() != null) { 5366 intent = intent.getSelector(); 5367 comp = intent.getComponent(); 5368 } 5369 } 5370 5371 if (comp != null) { 5372 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5373 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5374 if (ai != null) { 5375 final ResolveInfo ri = new ResolveInfo(); 5376 ri.activityInfo = ai; 5377 list.add(ri); 5378 } 5379 return list; 5380 } 5381 5382 // reader 5383 synchronized (mPackages) { 5384 final String pkgName = intent.getPackage(); 5385 if (pkgName == null) { 5386 List<CrossProfileIntentFilter> matchingFilters = 5387 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5388 // Check for results that need to skip the current profile. 5389 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5390 resolvedType, flags, userId); 5391 if (xpResolveInfo != null) { 5392 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 5393 result.add(xpResolveInfo); 5394 return filterIfNotSystemUser(result, userId); 5395 } 5396 5397 // Check for results in the current profile. 5398 List<ResolveInfo> result = mActivities.queryIntent( 5399 intent, resolvedType, flags, userId); 5400 result = filterIfNotSystemUser(result, userId); 5401 5402 // Check for cross profile results. 5403 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5404 xpResolveInfo = queryCrossProfileIntents( 5405 matchingFilters, intent, resolvedType, flags, userId, 5406 hasNonNegativePriorityResult); 5407 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5408 boolean isVisibleToUser = filterIfNotSystemUser( 5409 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5410 if (isVisibleToUser) { 5411 result.add(xpResolveInfo); 5412 Collections.sort(result, mResolvePrioritySorter); 5413 } 5414 } 5415 if (hasWebURI(intent)) { 5416 CrossProfileDomainInfo xpDomainInfo = null; 5417 final UserInfo parent = getProfileParent(userId); 5418 if (parent != null) { 5419 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5420 flags, userId, parent.id); 5421 } 5422 if (xpDomainInfo != null) { 5423 if (xpResolveInfo != null) { 5424 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5425 // in the result. 5426 result.remove(xpResolveInfo); 5427 } 5428 if (result.size() == 0) { 5429 result.add(xpDomainInfo.resolveInfo); 5430 return result; 5431 } 5432 } else if (result.size() <= 1) { 5433 return result; 5434 } 5435 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 5436 xpDomainInfo, userId); 5437 Collections.sort(result, mResolvePrioritySorter); 5438 } 5439 return result; 5440 } 5441 final PackageParser.Package pkg = mPackages.get(pkgName); 5442 if (pkg != null) { 5443 return filterIfNotSystemUser( 5444 mActivities.queryIntentForPackage( 5445 intent, resolvedType, flags, pkg.activities, userId), 5446 userId); 5447 } 5448 return new ArrayList<ResolveInfo>(); 5449 } 5450 } 5451 5452 private static class CrossProfileDomainInfo { 5453 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5454 ResolveInfo resolveInfo; 5455 /* Best domain verification status of the activities found in the other profile */ 5456 int bestDomainVerificationStatus; 5457 } 5458 5459 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5460 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5461 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5462 sourceUserId)) { 5463 return null; 5464 } 5465 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5466 resolvedType, flags, parentUserId); 5467 5468 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5469 return null; 5470 } 5471 CrossProfileDomainInfo result = null; 5472 int size = resultTargetUser.size(); 5473 for (int i = 0; i < size; i++) { 5474 ResolveInfo riTargetUser = resultTargetUser.get(i); 5475 // Intent filter verification is only for filters that specify a host. So don't return 5476 // those that handle all web uris. 5477 if (riTargetUser.handleAllWebDataURI) { 5478 continue; 5479 } 5480 String packageName = riTargetUser.activityInfo.packageName; 5481 PackageSetting ps = mSettings.mPackages.get(packageName); 5482 if (ps == null) { 5483 continue; 5484 } 5485 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5486 int status = (int)(verificationState >> 32); 5487 if (result == null) { 5488 result = new CrossProfileDomainInfo(); 5489 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5490 sourceUserId, parentUserId); 5491 result.bestDomainVerificationStatus = status; 5492 } else { 5493 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5494 result.bestDomainVerificationStatus); 5495 } 5496 } 5497 // Don't consider matches with status NEVER across profiles. 5498 if (result != null && result.bestDomainVerificationStatus 5499 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5500 return null; 5501 } 5502 return result; 5503 } 5504 5505 /** 5506 * Verification statuses are ordered from the worse to the best, except for 5507 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5508 */ 5509 private int bestDomainVerificationStatus(int status1, int status2) { 5510 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5511 return status2; 5512 } 5513 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5514 return status1; 5515 } 5516 return (int) MathUtils.max(status1, status2); 5517 } 5518 5519 private boolean isUserEnabled(int userId) { 5520 long callingId = Binder.clearCallingIdentity(); 5521 try { 5522 UserInfo userInfo = sUserManager.getUserInfo(userId); 5523 return userInfo != null && userInfo.isEnabled(); 5524 } finally { 5525 Binder.restoreCallingIdentity(callingId); 5526 } 5527 } 5528 5529 /** 5530 * Filter out activities with systemUserOnly flag set, when current user is not System. 5531 * 5532 * @return filtered list 5533 */ 5534 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5535 if (userId == UserHandle.USER_SYSTEM) { 5536 return resolveInfos; 5537 } 5538 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5539 ResolveInfo info = resolveInfos.get(i); 5540 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5541 resolveInfos.remove(i); 5542 } 5543 } 5544 return resolveInfos; 5545 } 5546 5547 /** 5548 * @param resolveInfos list of resolve infos in descending priority order 5549 * @return if the list contains a resolve info with non-negative priority 5550 */ 5551 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5552 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5553 } 5554 5555 private static boolean hasWebURI(Intent intent) { 5556 if (intent.getData() == null) { 5557 return false; 5558 } 5559 final String scheme = intent.getScheme(); 5560 if (TextUtils.isEmpty(scheme)) { 5561 return false; 5562 } 5563 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5564 } 5565 5566 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5567 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5568 int userId) { 5569 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5570 5571 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5572 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5573 candidates.size()); 5574 } 5575 5576 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5577 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5578 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5579 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5580 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5581 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5582 5583 synchronized (mPackages) { 5584 final int count = candidates.size(); 5585 // First, try to use linked apps. Partition the candidates into four lists: 5586 // one for the final results, one for the "do not use ever", one for "undefined status" 5587 // and finally one for "browser app type". 5588 for (int n=0; n<count; n++) { 5589 ResolveInfo info = candidates.get(n); 5590 String packageName = info.activityInfo.packageName; 5591 PackageSetting ps = mSettings.mPackages.get(packageName); 5592 if (ps != null) { 5593 // Add to the special match all list (Browser use case) 5594 if (info.handleAllWebDataURI) { 5595 matchAllList.add(info); 5596 continue; 5597 } 5598 // Try to get the status from User settings first 5599 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5600 int status = (int)(packedStatus >> 32); 5601 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5602 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5603 if (DEBUG_DOMAIN_VERIFICATION) { 5604 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5605 + " : linkgen=" + linkGeneration); 5606 } 5607 // Use link-enabled generation as preferredOrder, i.e. 5608 // prefer newly-enabled over earlier-enabled. 5609 info.preferredOrder = linkGeneration; 5610 alwaysList.add(info); 5611 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5612 if (DEBUG_DOMAIN_VERIFICATION) { 5613 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5614 } 5615 neverList.add(info); 5616 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5617 if (DEBUG_DOMAIN_VERIFICATION) { 5618 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5619 } 5620 alwaysAskList.add(info); 5621 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5622 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5623 if (DEBUG_DOMAIN_VERIFICATION) { 5624 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5625 } 5626 undefinedList.add(info); 5627 } 5628 } 5629 } 5630 5631 // We'll want to include browser possibilities in a few cases 5632 boolean includeBrowser = false; 5633 5634 // First try to add the "always" resolution(s) for the current user, if any 5635 if (alwaysList.size() > 0) { 5636 result.addAll(alwaysList); 5637 } else { 5638 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5639 result.addAll(undefinedList); 5640 // Maybe add one for the other profile. 5641 if (xpDomainInfo != null && ( 5642 xpDomainInfo.bestDomainVerificationStatus 5643 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5644 result.add(xpDomainInfo.resolveInfo); 5645 } 5646 includeBrowser = true; 5647 } 5648 5649 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5650 // If there were 'always' entries their preferred order has been set, so we also 5651 // back that off to make the alternatives equivalent 5652 if (alwaysAskList.size() > 0) { 5653 for (ResolveInfo i : result) { 5654 i.preferredOrder = 0; 5655 } 5656 result.addAll(alwaysAskList); 5657 includeBrowser = true; 5658 } 5659 5660 if (includeBrowser) { 5661 // Also add browsers (all of them or only the default one) 5662 if (DEBUG_DOMAIN_VERIFICATION) { 5663 Slog.v(TAG, " ...including browsers in candidate set"); 5664 } 5665 if ((matchFlags & MATCH_ALL) != 0) { 5666 result.addAll(matchAllList); 5667 } else { 5668 // Browser/generic handling case. If there's a default browser, go straight 5669 // to that (but only if there is no other higher-priority match). 5670 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5671 int maxMatchPrio = 0; 5672 ResolveInfo defaultBrowserMatch = null; 5673 final int numCandidates = matchAllList.size(); 5674 for (int n = 0; n < numCandidates; n++) { 5675 ResolveInfo info = matchAllList.get(n); 5676 // track the highest overall match priority... 5677 if (info.priority > maxMatchPrio) { 5678 maxMatchPrio = info.priority; 5679 } 5680 // ...and the highest-priority default browser match 5681 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5682 if (defaultBrowserMatch == null 5683 || (defaultBrowserMatch.priority < info.priority)) { 5684 if (debug) { 5685 Slog.v(TAG, "Considering default browser match " + info); 5686 } 5687 defaultBrowserMatch = info; 5688 } 5689 } 5690 } 5691 if (defaultBrowserMatch != null 5692 && defaultBrowserMatch.priority >= maxMatchPrio 5693 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5694 { 5695 if (debug) { 5696 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5697 } 5698 result.add(defaultBrowserMatch); 5699 } else { 5700 result.addAll(matchAllList); 5701 } 5702 } 5703 5704 // If there is nothing selected, add all candidates and remove the ones that the user 5705 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5706 if (result.size() == 0) { 5707 result.addAll(candidates); 5708 result.removeAll(neverList); 5709 } 5710 } 5711 } 5712 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5713 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5714 result.size()); 5715 for (ResolveInfo info : result) { 5716 Slog.v(TAG, " + " + info.activityInfo); 5717 } 5718 } 5719 return result; 5720 } 5721 5722 // Returns a packed value as a long: 5723 // 5724 // high 'int'-sized word: link status: undefined/ask/never/always. 5725 // low 'int'-sized word: relative priority among 'always' results. 5726 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5727 long result = ps.getDomainVerificationStatusForUser(userId); 5728 // if none available, get the master status 5729 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5730 if (ps.getIntentFilterVerificationInfo() != null) { 5731 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5732 } 5733 } 5734 return result; 5735 } 5736 5737 private ResolveInfo querySkipCurrentProfileIntents( 5738 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5739 int flags, int sourceUserId) { 5740 if (matchingFilters != null) { 5741 int size = matchingFilters.size(); 5742 for (int i = 0; i < size; i ++) { 5743 CrossProfileIntentFilter filter = matchingFilters.get(i); 5744 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5745 // Checking if there are activities in the target user that can handle the 5746 // intent. 5747 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5748 resolvedType, flags, sourceUserId); 5749 if (resolveInfo != null) { 5750 return resolveInfo; 5751 } 5752 } 5753 } 5754 } 5755 return null; 5756 } 5757 5758 // Return matching ResolveInfo in target user if any. 5759 private ResolveInfo queryCrossProfileIntents( 5760 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5761 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5762 if (matchingFilters != null) { 5763 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5764 // match the same intent. For performance reasons, it is better not to 5765 // run queryIntent twice for the same userId 5766 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5767 int size = matchingFilters.size(); 5768 for (int i = 0; i < size; i++) { 5769 CrossProfileIntentFilter filter = matchingFilters.get(i); 5770 int targetUserId = filter.getTargetUserId(); 5771 boolean skipCurrentProfile = 5772 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5773 boolean skipCurrentProfileIfNoMatchFound = 5774 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5775 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5776 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5777 // Checking if there are activities in the target user that can handle the 5778 // intent. 5779 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5780 resolvedType, flags, sourceUserId); 5781 if (resolveInfo != null) return resolveInfo; 5782 alreadyTriedUserIds.put(targetUserId, true); 5783 } 5784 } 5785 } 5786 return null; 5787 } 5788 5789 /** 5790 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5791 * will forward the intent to the filter's target user. 5792 * Otherwise, returns null. 5793 */ 5794 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5795 String resolvedType, int flags, int sourceUserId) { 5796 int targetUserId = filter.getTargetUserId(); 5797 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5798 resolvedType, flags, targetUserId); 5799 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5800 // If all the matches in the target profile are suspended, return null. 5801 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5802 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5803 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5804 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5805 targetUserId); 5806 } 5807 } 5808 } 5809 return null; 5810 } 5811 5812 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5813 int sourceUserId, int targetUserId) { 5814 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5815 long ident = Binder.clearCallingIdentity(); 5816 boolean targetIsProfile; 5817 try { 5818 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5819 } finally { 5820 Binder.restoreCallingIdentity(ident); 5821 } 5822 String className; 5823 if (targetIsProfile) { 5824 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5825 } else { 5826 className = FORWARD_INTENT_TO_PARENT; 5827 } 5828 ComponentName forwardingActivityComponentName = new ComponentName( 5829 mAndroidApplication.packageName, className); 5830 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5831 sourceUserId); 5832 if (!targetIsProfile) { 5833 forwardingActivityInfo.showUserIcon = targetUserId; 5834 forwardingResolveInfo.noResourceId = true; 5835 } 5836 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5837 forwardingResolveInfo.priority = 0; 5838 forwardingResolveInfo.preferredOrder = 0; 5839 forwardingResolveInfo.match = 0; 5840 forwardingResolveInfo.isDefault = true; 5841 forwardingResolveInfo.filter = filter; 5842 forwardingResolveInfo.targetUserId = targetUserId; 5843 return forwardingResolveInfo; 5844 } 5845 5846 @Override 5847 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5848 Intent[] specifics, String[] specificTypes, Intent intent, 5849 String resolvedType, int flags, int userId) { 5850 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 5851 specificTypes, intent, resolvedType, flags, userId)); 5852 } 5853 5854 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 5855 Intent[] specifics, String[] specificTypes, Intent intent, 5856 String resolvedType, int flags, int userId) { 5857 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5858 flags = updateFlagsForResolve(flags, userId, intent); 5859 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5860 false /* requireFullPermission */, false /* checkShell */, 5861 "query intent activity options"); 5862 final String resultsAction = intent.getAction(); 5863 5864 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 5865 | PackageManager.GET_RESOLVED_FILTER, userId); 5866 5867 if (DEBUG_INTENT_MATCHING) { 5868 Log.v(TAG, "Query " + intent + ": " + results); 5869 } 5870 5871 int specificsPos = 0; 5872 int N; 5873 5874 // todo: note that the algorithm used here is O(N^2). This 5875 // isn't a problem in our current environment, but if we start running 5876 // into situations where we have more than 5 or 10 matches then this 5877 // should probably be changed to something smarter... 5878 5879 // First we go through and resolve each of the specific items 5880 // that were supplied, taking care of removing any corresponding 5881 // duplicate items in the generic resolve list. 5882 if (specifics != null) { 5883 for (int i=0; i<specifics.length; i++) { 5884 final Intent sintent = specifics[i]; 5885 if (sintent == null) { 5886 continue; 5887 } 5888 5889 if (DEBUG_INTENT_MATCHING) { 5890 Log.v(TAG, "Specific #" + i + ": " + sintent); 5891 } 5892 5893 String action = sintent.getAction(); 5894 if (resultsAction != null && resultsAction.equals(action)) { 5895 // If this action was explicitly requested, then don't 5896 // remove things that have it. 5897 action = null; 5898 } 5899 5900 ResolveInfo ri = null; 5901 ActivityInfo ai = null; 5902 5903 ComponentName comp = sintent.getComponent(); 5904 if (comp == null) { 5905 ri = resolveIntent( 5906 sintent, 5907 specificTypes != null ? specificTypes[i] : null, 5908 flags, userId); 5909 if (ri == null) { 5910 continue; 5911 } 5912 if (ri == mResolveInfo) { 5913 // ACK! Must do something better with this. 5914 } 5915 ai = ri.activityInfo; 5916 comp = new ComponentName(ai.applicationInfo.packageName, 5917 ai.name); 5918 } else { 5919 ai = getActivityInfo(comp, flags, userId); 5920 if (ai == null) { 5921 continue; 5922 } 5923 } 5924 5925 // Look for any generic query activities that are duplicates 5926 // of this specific one, and remove them from the results. 5927 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5928 N = results.size(); 5929 int j; 5930 for (j=specificsPos; j<N; j++) { 5931 ResolveInfo sri = results.get(j); 5932 if ((sri.activityInfo.name.equals(comp.getClassName()) 5933 && sri.activityInfo.applicationInfo.packageName.equals( 5934 comp.getPackageName())) 5935 || (action != null && sri.filter.matchAction(action))) { 5936 results.remove(j); 5937 if (DEBUG_INTENT_MATCHING) Log.v( 5938 TAG, "Removing duplicate item from " + j 5939 + " due to specific " + specificsPos); 5940 if (ri == null) { 5941 ri = sri; 5942 } 5943 j--; 5944 N--; 5945 } 5946 } 5947 5948 // Add this specific item to its proper place. 5949 if (ri == null) { 5950 ri = new ResolveInfo(); 5951 ri.activityInfo = ai; 5952 } 5953 results.add(specificsPos, ri); 5954 ri.specificIndex = i; 5955 specificsPos++; 5956 } 5957 } 5958 5959 // Now we go through the remaining generic results and remove any 5960 // duplicate actions that are found here. 5961 N = results.size(); 5962 for (int i=specificsPos; i<N-1; i++) { 5963 final ResolveInfo rii = results.get(i); 5964 if (rii.filter == null) { 5965 continue; 5966 } 5967 5968 // Iterate over all of the actions of this result's intent 5969 // filter... typically this should be just one. 5970 final Iterator<String> it = rii.filter.actionsIterator(); 5971 if (it == null) { 5972 continue; 5973 } 5974 while (it.hasNext()) { 5975 final String action = it.next(); 5976 if (resultsAction != null && resultsAction.equals(action)) { 5977 // If this action was explicitly requested, then don't 5978 // remove things that have it. 5979 continue; 5980 } 5981 for (int j=i+1; j<N; j++) { 5982 final ResolveInfo rij = results.get(j); 5983 if (rij.filter != null && rij.filter.hasAction(action)) { 5984 results.remove(j); 5985 if (DEBUG_INTENT_MATCHING) Log.v( 5986 TAG, "Removing duplicate item from " + j 5987 + " due to action " + action + " at " + i); 5988 j--; 5989 N--; 5990 } 5991 } 5992 } 5993 5994 // If the caller didn't request filter information, drop it now 5995 // so we don't have to marshall/unmarshall it. 5996 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5997 rii.filter = null; 5998 } 5999 } 6000 6001 // Filter out the caller activity if so requested. 6002 if (caller != null) { 6003 N = results.size(); 6004 for (int i=0; i<N; i++) { 6005 ActivityInfo ainfo = results.get(i).activityInfo; 6006 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 6007 && caller.getClassName().equals(ainfo.name)) { 6008 results.remove(i); 6009 break; 6010 } 6011 } 6012 } 6013 6014 // If the caller didn't request filter information, 6015 // drop them now so we don't have to 6016 // marshall/unmarshall it. 6017 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6018 N = results.size(); 6019 for (int i=0; i<N; i++) { 6020 results.get(i).filter = null; 6021 } 6022 } 6023 6024 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 6025 return results; 6026 } 6027 6028 @Override 6029 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 6030 String resolvedType, int flags, int userId) { 6031 return new ParceledListSlice<>( 6032 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 6033 } 6034 6035 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 6036 String resolvedType, int flags, int userId) { 6037 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6038 flags = updateFlagsForResolve(flags, userId, intent); 6039 ComponentName comp = intent.getComponent(); 6040 if (comp == null) { 6041 if (intent.getSelector() != null) { 6042 intent = intent.getSelector(); 6043 comp = intent.getComponent(); 6044 } 6045 } 6046 if (comp != null) { 6047 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6048 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 6049 if (ai != null) { 6050 ResolveInfo ri = new ResolveInfo(); 6051 ri.activityInfo = ai; 6052 list.add(ri); 6053 } 6054 return list; 6055 } 6056 6057 // reader 6058 synchronized (mPackages) { 6059 String pkgName = intent.getPackage(); 6060 if (pkgName == null) { 6061 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 6062 } 6063 final PackageParser.Package pkg = mPackages.get(pkgName); 6064 if (pkg != null) { 6065 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 6066 userId); 6067 } 6068 return Collections.emptyList(); 6069 } 6070 } 6071 6072 @Override 6073 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 6074 if (!sUserManager.exists(userId)) return null; 6075 flags = updateFlagsForResolve(flags, userId, intent); 6076 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 6077 if (query != null) { 6078 if (query.size() >= 1) { 6079 // If there is more than one service with the same priority, 6080 // just arbitrarily pick the first one. 6081 return query.get(0); 6082 } 6083 } 6084 return null; 6085 } 6086 6087 @Override 6088 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 6089 String resolvedType, int flags, int userId) { 6090 return new ParceledListSlice<>( 6091 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 6092 } 6093 6094 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 6095 String resolvedType, int flags, int userId) { 6096 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6097 flags = updateFlagsForResolve(flags, userId, intent); 6098 ComponentName comp = intent.getComponent(); 6099 if (comp == null) { 6100 if (intent.getSelector() != null) { 6101 intent = intent.getSelector(); 6102 comp = intent.getComponent(); 6103 } 6104 } 6105 if (comp != null) { 6106 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6107 final ServiceInfo si = getServiceInfo(comp, flags, userId); 6108 if (si != null) { 6109 final ResolveInfo ri = new ResolveInfo(); 6110 ri.serviceInfo = si; 6111 list.add(ri); 6112 } 6113 return list; 6114 } 6115 6116 // reader 6117 synchronized (mPackages) { 6118 String pkgName = intent.getPackage(); 6119 if (pkgName == null) { 6120 return mServices.queryIntent(intent, resolvedType, flags, userId); 6121 } 6122 final PackageParser.Package pkg = mPackages.get(pkgName); 6123 if (pkg != null) { 6124 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 6125 userId); 6126 } 6127 return Collections.emptyList(); 6128 } 6129 } 6130 6131 @Override 6132 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 6133 String resolvedType, int flags, int userId) { 6134 return new ParceledListSlice<>( 6135 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 6136 } 6137 6138 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 6139 Intent intent, String resolvedType, int flags, int userId) { 6140 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6141 flags = updateFlagsForResolve(flags, userId, intent); 6142 ComponentName comp = intent.getComponent(); 6143 if (comp == null) { 6144 if (intent.getSelector() != null) { 6145 intent = intent.getSelector(); 6146 comp = intent.getComponent(); 6147 } 6148 } 6149 if (comp != null) { 6150 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6151 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 6152 if (pi != null) { 6153 final ResolveInfo ri = new ResolveInfo(); 6154 ri.providerInfo = pi; 6155 list.add(ri); 6156 } 6157 return list; 6158 } 6159 6160 // reader 6161 synchronized (mPackages) { 6162 String pkgName = intent.getPackage(); 6163 if (pkgName == null) { 6164 return mProviders.queryIntent(intent, resolvedType, flags, userId); 6165 } 6166 final PackageParser.Package pkg = mPackages.get(pkgName); 6167 if (pkg != null) { 6168 return mProviders.queryIntentForPackage( 6169 intent, resolvedType, flags, pkg.providers, userId); 6170 } 6171 return Collections.emptyList(); 6172 } 6173 } 6174 6175 @Override 6176 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 6177 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6178 flags = updateFlagsForPackage(flags, userId, null); 6179 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6180 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6181 true /* requireFullPermission */, false /* checkShell */, 6182 "get installed packages"); 6183 6184 // writer 6185 synchronized (mPackages) { 6186 ArrayList<PackageInfo> list; 6187 if (listUninstalled) { 6188 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 6189 for (PackageSetting ps : mSettings.mPackages.values()) { 6190 final PackageInfo pi; 6191 if (ps.pkg != null) { 6192 pi = generatePackageInfo(ps, flags, userId); 6193 } else { 6194 pi = generatePackageInfo(ps, flags, userId); 6195 } 6196 if (pi != null) { 6197 list.add(pi); 6198 } 6199 } 6200 } else { 6201 list = new ArrayList<PackageInfo>(mPackages.size()); 6202 for (PackageParser.Package p : mPackages.values()) { 6203 final PackageInfo pi = 6204 generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 6205 if (pi != null) { 6206 list.add(pi); 6207 } 6208 } 6209 } 6210 6211 return new ParceledListSlice<PackageInfo>(list); 6212 } 6213 } 6214 6215 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 6216 String[] permissions, boolean[] tmp, int flags, int userId) { 6217 int numMatch = 0; 6218 final PermissionsState permissionsState = ps.getPermissionsState(); 6219 for (int i=0; i<permissions.length; i++) { 6220 final String permission = permissions[i]; 6221 if (permissionsState.hasPermission(permission, userId)) { 6222 tmp[i] = true; 6223 numMatch++; 6224 } else { 6225 tmp[i] = false; 6226 } 6227 } 6228 if (numMatch == 0) { 6229 return; 6230 } 6231 final PackageInfo pi; 6232 if (ps.pkg != null) { 6233 pi = generatePackageInfo(ps, flags, userId); 6234 } else { 6235 pi = generatePackageInfo(ps, flags, userId); 6236 } 6237 // The above might return null in cases of uninstalled apps or install-state 6238 // skew across users/profiles. 6239 if (pi != null) { 6240 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 6241 if (numMatch == permissions.length) { 6242 pi.requestedPermissions = permissions; 6243 } else { 6244 pi.requestedPermissions = new String[numMatch]; 6245 numMatch = 0; 6246 for (int i=0; i<permissions.length; i++) { 6247 if (tmp[i]) { 6248 pi.requestedPermissions[numMatch] = permissions[i]; 6249 numMatch++; 6250 } 6251 } 6252 } 6253 } 6254 list.add(pi); 6255 } 6256 } 6257 6258 @Override 6259 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 6260 String[] permissions, int flags, int userId) { 6261 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6262 flags = updateFlagsForPackage(flags, userId, permissions); 6263 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6264 6265 // writer 6266 synchronized (mPackages) { 6267 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 6268 boolean[] tmpBools = new boolean[permissions.length]; 6269 if (listUninstalled) { 6270 for (PackageSetting ps : mSettings.mPackages.values()) { 6271 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 6272 } 6273 } else { 6274 for (PackageParser.Package pkg : mPackages.values()) { 6275 PackageSetting ps = (PackageSetting)pkg.mExtras; 6276 if (ps != null) { 6277 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6278 userId); 6279 } 6280 } 6281 } 6282 6283 return new ParceledListSlice<PackageInfo>(list); 6284 } 6285 } 6286 6287 @Override 6288 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 6289 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6290 flags = updateFlagsForApplication(flags, userId, null); 6291 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6292 6293 // writer 6294 synchronized (mPackages) { 6295 ArrayList<ApplicationInfo> list; 6296 if (listUninstalled) { 6297 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 6298 for (PackageSetting ps : mSettings.mPackages.values()) { 6299 ApplicationInfo ai; 6300 if (ps.pkg != null) { 6301 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 6302 ps.readUserState(userId), userId); 6303 } else { 6304 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 6305 } 6306 if (ai != null) { 6307 list.add(ai); 6308 } 6309 } 6310 } else { 6311 list = new ArrayList<ApplicationInfo>(mPackages.size()); 6312 for (PackageParser.Package p : mPackages.values()) { 6313 if (p.mExtras != null) { 6314 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6315 ((PackageSetting)p.mExtras).readUserState(userId), userId); 6316 if (ai != null) { 6317 list.add(ai); 6318 } 6319 } 6320 } 6321 } 6322 6323 return new ParceledListSlice<ApplicationInfo>(list); 6324 } 6325 } 6326 6327 @Override 6328 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 6329 if (DISABLE_EPHEMERAL_APPS) { 6330 return null; 6331 } 6332 6333 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6334 "getEphemeralApplications"); 6335 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6336 true /* requireFullPermission */, false /* checkShell */, 6337 "getEphemeralApplications"); 6338 synchronized (mPackages) { 6339 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 6340 .getEphemeralApplicationsLPw(userId); 6341 if (ephemeralApps != null) { 6342 return new ParceledListSlice<>(ephemeralApps); 6343 } 6344 } 6345 return null; 6346 } 6347 6348 @Override 6349 public boolean isEphemeralApplication(String packageName, int userId) { 6350 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6351 true /* requireFullPermission */, false /* checkShell */, 6352 "isEphemeral"); 6353 if (DISABLE_EPHEMERAL_APPS) { 6354 return false; 6355 } 6356 6357 if (!isCallerSameApp(packageName)) { 6358 return false; 6359 } 6360 synchronized (mPackages) { 6361 PackageParser.Package pkg = mPackages.get(packageName); 6362 if (pkg != null) { 6363 return pkg.applicationInfo.isEphemeralApp(); 6364 } 6365 } 6366 return false; 6367 } 6368 6369 @Override 6370 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6371 if (DISABLE_EPHEMERAL_APPS) { 6372 return null; 6373 } 6374 6375 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6376 true /* requireFullPermission */, false /* checkShell */, 6377 "getCookie"); 6378 if (!isCallerSameApp(packageName)) { 6379 return null; 6380 } 6381 synchronized (mPackages) { 6382 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6383 packageName, userId); 6384 } 6385 } 6386 6387 @Override 6388 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6389 if (DISABLE_EPHEMERAL_APPS) { 6390 return true; 6391 } 6392 6393 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6394 true /* requireFullPermission */, true /* checkShell */, 6395 "setCookie"); 6396 if (!isCallerSameApp(packageName)) { 6397 return false; 6398 } 6399 synchronized (mPackages) { 6400 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6401 packageName, cookie, userId); 6402 } 6403 } 6404 6405 @Override 6406 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6407 if (DISABLE_EPHEMERAL_APPS) { 6408 return null; 6409 } 6410 6411 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6412 "getEphemeralApplicationIcon"); 6413 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6414 true /* requireFullPermission */, false /* checkShell */, 6415 "getEphemeralApplicationIcon"); 6416 synchronized (mPackages) { 6417 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6418 packageName, userId); 6419 } 6420 } 6421 6422 private boolean isCallerSameApp(String packageName) { 6423 PackageParser.Package pkg = mPackages.get(packageName); 6424 return pkg != null 6425 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6426 } 6427 6428 @Override 6429 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 6430 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 6431 } 6432 6433 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 6434 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6435 6436 // reader 6437 synchronized (mPackages) { 6438 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6439 final int userId = UserHandle.getCallingUserId(); 6440 while (i.hasNext()) { 6441 final PackageParser.Package p = i.next(); 6442 if (p.applicationInfo == null) continue; 6443 6444 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 6445 && !p.applicationInfo.isDirectBootAware(); 6446 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 6447 && p.applicationInfo.isDirectBootAware(); 6448 6449 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6450 && (!mSafeMode || isSystemApp(p)) 6451 && (matchesUnaware || matchesAware)) { 6452 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6453 if (ps != null) { 6454 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6455 ps.readUserState(userId), userId); 6456 if (ai != null) { 6457 finalList.add(ai); 6458 } 6459 } 6460 } 6461 } 6462 } 6463 6464 return finalList; 6465 } 6466 6467 @Override 6468 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6469 if (!sUserManager.exists(userId)) return null; 6470 flags = updateFlagsForComponent(flags, userId, name); 6471 // reader 6472 synchronized (mPackages) { 6473 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6474 PackageSetting ps = provider != null 6475 ? mSettings.mPackages.get(provider.owner.packageName) 6476 : null; 6477 return ps != null 6478 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6479 ? PackageParser.generateProviderInfo(provider, flags, 6480 ps.readUserState(userId), userId) 6481 : null; 6482 } 6483 } 6484 6485 /** 6486 * @deprecated 6487 */ 6488 @Deprecated 6489 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6490 // reader 6491 synchronized (mPackages) { 6492 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6493 .entrySet().iterator(); 6494 final int userId = UserHandle.getCallingUserId(); 6495 while (i.hasNext()) { 6496 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6497 PackageParser.Provider p = entry.getValue(); 6498 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6499 6500 if (ps != null && p.syncable 6501 && (!mSafeMode || (p.info.applicationInfo.flags 6502 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6503 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6504 ps.readUserState(userId), userId); 6505 if (info != null) { 6506 outNames.add(entry.getKey()); 6507 outInfo.add(info); 6508 } 6509 } 6510 } 6511 } 6512 } 6513 6514 @Override 6515 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6516 int uid, int flags) { 6517 final int userId = processName != null ? UserHandle.getUserId(uid) 6518 : UserHandle.getCallingUserId(); 6519 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6520 flags = updateFlagsForComponent(flags, userId, processName); 6521 6522 ArrayList<ProviderInfo> finalList = null; 6523 // reader 6524 synchronized (mPackages) { 6525 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6526 while (i.hasNext()) { 6527 final PackageParser.Provider p = i.next(); 6528 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6529 if (ps != null && p.info.authority != null 6530 && (processName == null 6531 || (p.info.processName.equals(processName) 6532 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6533 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6534 if (finalList == null) { 6535 finalList = new ArrayList<ProviderInfo>(3); 6536 } 6537 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6538 ps.readUserState(userId), userId); 6539 if (info != null) { 6540 finalList.add(info); 6541 } 6542 } 6543 } 6544 } 6545 6546 if (finalList != null) { 6547 Collections.sort(finalList, mProviderInitOrderSorter); 6548 return new ParceledListSlice<ProviderInfo>(finalList); 6549 } 6550 6551 return ParceledListSlice.emptyList(); 6552 } 6553 6554 @Override 6555 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6556 // reader 6557 synchronized (mPackages) { 6558 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6559 return PackageParser.generateInstrumentationInfo(i, flags); 6560 } 6561 } 6562 6563 @Override 6564 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 6565 String targetPackage, int flags) { 6566 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 6567 } 6568 6569 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 6570 int flags) { 6571 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 6572 6573 // reader 6574 synchronized (mPackages) { 6575 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6576 while (i.hasNext()) { 6577 final PackageParser.Instrumentation p = i.next(); 6578 if (targetPackage == null 6579 || targetPackage.equals(p.info.targetPackage)) { 6580 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6581 flags); 6582 if (ii != null) { 6583 finalList.add(ii); 6584 } 6585 } 6586 } 6587 } 6588 6589 return finalList; 6590 } 6591 6592 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6593 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6594 if (overlays == null) { 6595 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6596 return; 6597 } 6598 for (PackageParser.Package opkg : overlays.values()) { 6599 // Not much to do if idmap fails: we already logged the error 6600 // and we certainly don't want to abort installation of pkg simply 6601 // because an overlay didn't fit properly. For these reasons, 6602 // ignore the return value of createIdmapForPackagePairLI. 6603 createIdmapForPackagePairLI(pkg, opkg); 6604 } 6605 } 6606 6607 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6608 PackageParser.Package opkg) { 6609 if (!opkg.mTrustedOverlay) { 6610 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6611 opkg.baseCodePath + ": overlay not trusted"); 6612 return false; 6613 } 6614 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6615 if (overlaySet == null) { 6616 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6617 opkg.baseCodePath + " but target package has no known overlays"); 6618 return false; 6619 } 6620 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6621 // TODO: generate idmap for split APKs 6622 try { 6623 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6624 } catch (InstallerException e) { 6625 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6626 + opkg.baseCodePath); 6627 return false; 6628 } 6629 PackageParser.Package[] overlayArray = 6630 overlaySet.values().toArray(new PackageParser.Package[0]); 6631 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6632 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6633 return p1.mOverlayPriority - p2.mOverlayPriority; 6634 } 6635 }; 6636 Arrays.sort(overlayArray, cmp); 6637 6638 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6639 int i = 0; 6640 for (PackageParser.Package p : overlayArray) { 6641 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6642 } 6643 return true; 6644 } 6645 6646 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6647 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6648 try { 6649 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6650 } finally { 6651 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6652 } 6653 } 6654 6655 private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6656 final File[] files = dir.listFiles(); 6657 if (ArrayUtils.isEmpty(files)) { 6658 Log.d(TAG, "No files in app dir " + dir); 6659 return; 6660 } 6661 6662 if (DEBUG_PACKAGE_SCANNING) { 6663 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6664 + " flags=0x" + Integer.toHexString(parseFlags)); 6665 } 6666 6667 for (File file : files) { 6668 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6669 && !PackageInstallerService.isStageName(file.getName()); 6670 if (!isPackage) { 6671 // Ignore entries which are not packages 6672 continue; 6673 } 6674 try { 6675 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6676 scanFlags, currentTime, null); 6677 } catch (PackageManagerException e) { 6678 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6679 6680 // Delete invalid userdata apps 6681 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6682 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6683 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6684 removeCodePathLI(file); 6685 } 6686 } 6687 } 6688 } 6689 6690 private static File getSettingsProblemFile() { 6691 File dataDir = Environment.getDataDirectory(); 6692 File systemDir = new File(dataDir, "system"); 6693 File fname = new File(systemDir, "uiderrors.txt"); 6694 return fname; 6695 } 6696 6697 static void reportSettingsProblem(int priority, String msg) { 6698 logCriticalInfo(priority, msg); 6699 } 6700 6701 static void logCriticalInfo(int priority, String msg) { 6702 Slog.println(priority, TAG, msg); 6703 EventLogTags.writePmCriticalInfo(msg); 6704 try { 6705 File fname = getSettingsProblemFile(); 6706 FileOutputStream out = new FileOutputStream(fname, true); 6707 PrintWriter pw = new FastPrintWriter(out); 6708 SimpleDateFormat formatter = new SimpleDateFormat(); 6709 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6710 pw.println(dateString + ": " + msg); 6711 pw.close(); 6712 FileUtils.setPermissions( 6713 fname.toString(), 6714 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6715 -1, -1); 6716 } catch (java.io.IOException e) { 6717 } 6718 } 6719 6720 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6721 final int policyFlags) throws PackageManagerException { 6722 if (ps != null 6723 && ps.codePath.equals(srcFile) 6724 && ps.timeStamp == srcFile.lastModified() 6725 && !isCompatSignatureUpdateNeeded(pkg) 6726 && !isRecoverSignatureUpdateNeeded(pkg)) { 6727 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6728 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6729 ArraySet<PublicKey> signingKs; 6730 synchronized (mPackages) { 6731 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6732 } 6733 if (ps.signatures.mSignatures != null 6734 && ps.signatures.mSignatures.length != 0 6735 && signingKs != null) { 6736 // Optimization: reuse the existing cached certificates 6737 // if the package appears to be unchanged. 6738 pkg.mSignatures = ps.signatures.mSignatures; 6739 pkg.mSigningKeys = signingKs; 6740 return; 6741 } 6742 6743 Slog.w(TAG, "PackageSetting for " + ps.name 6744 + " is missing signatures. Collecting certs again to recover them."); 6745 } else { 6746 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6747 } 6748 6749 try { 6750 PackageParser.collectCertificates(pkg, policyFlags); 6751 } catch (PackageParserException e) { 6752 throw PackageManagerException.from(e); 6753 } 6754 } 6755 6756 /** 6757 * Traces a package scan. 6758 * @see #scanPackageLI(File, int, int, long, UserHandle) 6759 */ 6760 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 6761 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6762 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6763 try { 6764 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6765 } finally { 6766 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6767 } 6768 } 6769 6770 /** 6771 * Scans a package and returns the newly parsed package. 6772 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6773 */ 6774 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6775 long currentTime, UserHandle user) throws PackageManagerException { 6776 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6777 PackageParser pp = new PackageParser(); 6778 pp.setSeparateProcesses(mSeparateProcesses); 6779 pp.setOnlyCoreApps(mOnlyCore); 6780 pp.setDisplayMetrics(mMetrics); 6781 6782 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6783 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6784 } 6785 6786 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 6787 final PackageParser.Package pkg; 6788 try { 6789 pkg = pp.parsePackage(scanFile, parseFlags); 6790 } catch (PackageParserException e) { 6791 throw PackageManagerException.from(e); 6792 } finally { 6793 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6794 } 6795 6796 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6797 } 6798 6799 /** 6800 * Scans a package and returns the newly parsed package. 6801 * @throws PackageManagerException on a parse error. 6802 */ 6803 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6804 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 6805 throws PackageManagerException { 6806 // If the package has children and this is the first dive in the function 6807 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6808 // packages (parent and children) would be successfully scanned before the 6809 // actual scan since scanning mutates internal state and we want to atomically 6810 // install the package and its children. 6811 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6812 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6813 scanFlags |= SCAN_CHECK_ONLY; 6814 } 6815 } else { 6816 scanFlags &= ~SCAN_CHECK_ONLY; 6817 } 6818 6819 // Scan the parent 6820 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 6821 scanFlags, currentTime, user); 6822 6823 // Scan the children 6824 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6825 for (int i = 0; i < childCount; i++) { 6826 PackageParser.Package childPackage = pkg.childPackages.get(i); 6827 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 6828 currentTime, user); 6829 } 6830 6831 6832 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6833 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 6834 } 6835 6836 return scannedPkg; 6837 } 6838 6839 /** 6840 * Scans a package and returns the newly parsed package. 6841 * @throws PackageManagerException on a parse error. 6842 */ 6843 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6844 int policyFlags, int scanFlags, long currentTime, UserHandle user) 6845 throws PackageManagerException { 6846 PackageSetting ps = null; 6847 PackageSetting updatedPkg; 6848 // reader 6849 synchronized (mPackages) { 6850 // Look to see if we already know about this package. 6851 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6852 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6853 // This package has been renamed to its original name. Let's 6854 // use that. 6855 ps = mSettings.peekPackageLPr(oldName); 6856 } 6857 // If there was no original package, see one for the real package name. 6858 if (ps == null) { 6859 ps = mSettings.peekPackageLPr(pkg.packageName); 6860 } 6861 // Check to see if this package could be hiding/updating a system 6862 // package. Must look for it either under the original or real 6863 // package name depending on our state. 6864 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6865 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6866 6867 // If this is a package we don't know about on the system partition, we 6868 // may need to remove disabled child packages on the system partition 6869 // or may need to not add child packages if the parent apk is updated 6870 // on the data partition and no longer defines this child package. 6871 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6872 // If this is a parent package for an updated system app and this system 6873 // app got an OTA update which no longer defines some of the child packages 6874 // we have to prune them from the disabled system packages. 6875 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6876 if (disabledPs != null) { 6877 final int scannedChildCount = (pkg.childPackages != null) 6878 ? pkg.childPackages.size() : 0; 6879 final int disabledChildCount = disabledPs.childPackageNames != null 6880 ? disabledPs.childPackageNames.size() : 0; 6881 for (int i = 0; i < disabledChildCount; i++) { 6882 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6883 boolean disabledPackageAvailable = false; 6884 for (int j = 0; j < scannedChildCount; j++) { 6885 PackageParser.Package childPkg = pkg.childPackages.get(j); 6886 if (childPkg.packageName.equals(disabledChildPackageName)) { 6887 disabledPackageAvailable = true; 6888 break; 6889 } 6890 } 6891 if (!disabledPackageAvailable) { 6892 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6893 } 6894 } 6895 } 6896 } 6897 } 6898 6899 boolean updatedPkgBetter = false; 6900 // First check if this is a system package that may involve an update 6901 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6902 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6903 // it needs to drop FLAG_PRIVILEGED. 6904 if (locationIsPrivileged(scanFile)) { 6905 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6906 } else { 6907 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6908 } 6909 6910 if (ps != null && !ps.codePath.equals(scanFile)) { 6911 // The path has changed from what was last scanned... check the 6912 // version of the new path against what we have stored to determine 6913 // what to do. 6914 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6915 if (pkg.mVersionCode <= ps.versionCode) { 6916 // The system package has been updated and the code path does not match 6917 // Ignore entry. Skip it. 6918 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6919 + " ignored: updated version " + ps.versionCode 6920 + " better than this " + pkg.mVersionCode); 6921 if (!updatedPkg.codePath.equals(scanFile)) { 6922 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6923 + ps.name + " changing from " + updatedPkg.codePathString 6924 + " to " + scanFile); 6925 updatedPkg.codePath = scanFile; 6926 updatedPkg.codePathString = scanFile.toString(); 6927 updatedPkg.resourcePath = scanFile; 6928 updatedPkg.resourcePathString = scanFile.toString(); 6929 } 6930 updatedPkg.pkg = pkg; 6931 updatedPkg.versionCode = pkg.mVersionCode; 6932 6933 // Update the disabled system child packages to point to the package too. 6934 final int childCount = updatedPkg.childPackageNames != null 6935 ? updatedPkg.childPackageNames.size() : 0; 6936 for (int i = 0; i < childCount; i++) { 6937 String childPackageName = updatedPkg.childPackageNames.get(i); 6938 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 6939 childPackageName); 6940 if (updatedChildPkg != null) { 6941 updatedChildPkg.pkg = pkg; 6942 updatedChildPkg.versionCode = pkg.mVersionCode; 6943 } 6944 } 6945 6946 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 6947 + scanFile + " ignored: updated version " + ps.versionCode 6948 + " better than this " + pkg.mVersionCode); 6949 } else { 6950 // The current app on the system partition is better than 6951 // what we have updated to on the data partition; switch 6952 // back to the system partition version. 6953 // At this point, its safely assumed that package installation for 6954 // apps in system partition will go through. If not there won't be a working 6955 // version of the app 6956 // writer 6957 synchronized (mPackages) { 6958 // Just remove the loaded entries from package lists. 6959 mPackages.remove(ps.name); 6960 } 6961 6962 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6963 + " reverting from " + ps.codePathString 6964 + ": new version " + pkg.mVersionCode 6965 + " better than installed " + ps.versionCode); 6966 6967 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6968 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6969 synchronized (mInstallLock) { 6970 args.cleanUpResourcesLI(); 6971 } 6972 synchronized (mPackages) { 6973 mSettings.enableSystemPackageLPw(ps.name); 6974 } 6975 updatedPkgBetter = true; 6976 } 6977 } 6978 } 6979 6980 if (updatedPkg != null) { 6981 // An updated system app will not have the PARSE_IS_SYSTEM flag set 6982 // initially 6983 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 6984 6985 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 6986 // flag set initially 6987 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 6988 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 6989 } 6990 } 6991 6992 // Verify certificates against what was last scanned 6993 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 6994 6995 /* 6996 * A new system app appeared, but we already had a non-system one of the 6997 * same name installed earlier. 6998 */ 6999 boolean shouldHideSystemApp = false; 7000 if (updatedPkg == null && ps != null 7001 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 7002 /* 7003 * Check to make sure the signatures match first. If they don't, 7004 * wipe the installed application and its data. 7005 */ 7006 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 7007 != PackageManager.SIGNATURE_MATCH) { 7008 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 7009 + " signatures don't match existing userdata copy; removing"); 7010 try (PackageFreezer freezer = freezePackage(pkg.packageName, 7011 "scanPackageInternalLI")) { 7012 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 7013 } 7014 ps = null; 7015 } else { 7016 /* 7017 * If the newly-added system app is an older version than the 7018 * already installed version, hide it. It will be scanned later 7019 * and re-added like an update. 7020 */ 7021 if (pkg.mVersionCode <= ps.versionCode) { 7022 shouldHideSystemApp = true; 7023 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 7024 + " but new version " + pkg.mVersionCode + " better than installed " 7025 + ps.versionCode + "; hiding system"); 7026 } else { 7027 /* 7028 * The newly found system app is a newer version that the 7029 * one previously installed. Simply remove the 7030 * already-installed application and replace it with our own 7031 * while keeping the application data. 7032 */ 7033 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7034 + " reverting from " + ps.codePathString + ": new version " 7035 + pkg.mVersionCode + " better than installed " + ps.versionCode); 7036 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7037 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7038 synchronized (mInstallLock) { 7039 args.cleanUpResourcesLI(); 7040 } 7041 } 7042 } 7043 } 7044 7045 // The apk is forward locked (not public) if its code and resources 7046 // are kept in different files. (except for app in either system or 7047 // vendor path). 7048 // TODO grab this value from PackageSettings 7049 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7050 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 7051 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 7052 } 7053 } 7054 7055 // TODO: extend to support forward-locked splits 7056 String resourcePath = null; 7057 String baseResourcePath = null; 7058 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 7059 if (ps != null && ps.resourcePathString != null) { 7060 resourcePath = ps.resourcePathString; 7061 baseResourcePath = ps.resourcePathString; 7062 } else { 7063 // Should not happen at all. Just log an error. 7064 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 7065 } 7066 } else { 7067 resourcePath = pkg.codePath; 7068 baseResourcePath = pkg.baseCodePath; 7069 } 7070 7071 // Set application objects path explicitly. 7072 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 7073 pkg.setApplicationInfoCodePath(pkg.codePath); 7074 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 7075 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 7076 pkg.setApplicationInfoResourcePath(resourcePath); 7077 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 7078 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 7079 7080 // Note that we invoke the following method only if we are about to unpack an application 7081 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 7082 | SCAN_UPDATE_SIGNATURE, currentTime, user); 7083 7084 /* 7085 * If the system app should be overridden by a previously installed 7086 * data, hide the system app now and let the /data/app scan pick it up 7087 * again. 7088 */ 7089 if (shouldHideSystemApp) { 7090 synchronized (mPackages) { 7091 mSettings.disableSystemPackageLPw(pkg.packageName, true); 7092 } 7093 } 7094 7095 return scannedPkg; 7096 } 7097 7098 private static String fixProcessName(String defProcessName, 7099 String processName, int uid) { 7100 if (processName == null) { 7101 return defProcessName; 7102 } 7103 return processName; 7104 } 7105 7106 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 7107 throws PackageManagerException { 7108 if (pkgSetting.signatures.mSignatures != null) { 7109 // Already existing package. Make sure signatures match 7110 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 7111 == PackageManager.SIGNATURE_MATCH; 7112 if (!match) { 7113 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 7114 == PackageManager.SIGNATURE_MATCH; 7115 } 7116 if (!match) { 7117 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 7118 == PackageManager.SIGNATURE_MATCH; 7119 } 7120 if (!match) { 7121 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 7122 + pkg.packageName + " signatures do not match the " 7123 + "previously installed version; ignoring!"); 7124 } 7125 } 7126 7127 // Check for shared user signatures 7128 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 7129 // Already existing package. Make sure signatures match 7130 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7131 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 7132 if (!match) { 7133 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 7134 == PackageManager.SIGNATURE_MATCH; 7135 } 7136 if (!match) { 7137 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 7138 == PackageManager.SIGNATURE_MATCH; 7139 } 7140 if (!match) { 7141 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 7142 "Package " + pkg.packageName 7143 + " has no signatures that match those in shared user " 7144 + pkgSetting.sharedUser.name + "; ignoring!"); 7145 } 7146 } 7147 } 7148 7149 /** 7150 * Enforces that only the system UID or root's UID can call a method exposed 7151 * via Binder. 7152 * 7153 * @param message used as message if SecurityException is thrown 7154 * @throws SecurityException if the caller is not system or root 7155 */ 7156 private static final void enforceSystemOrRoot(String message) { 7157 final int uid = Binder.getCallingUid(); 7158 if (uid != Process.SYSTEM_UID && uid != 0) { 7159 throw new SecurityException(message); 7160 } 7161 } 7162 7163 @Override 7164 public void performFstrimIfNeeded() { 7165 enforceSystemOrRoot("Only the system can request fstrim"); 7166 7167 // Before everything else, see whether we need to fstrim. 7168 try { 7169 IMountService ms = PackageHelper.getMountService(); 7170 if (ms != null) { 7171 final boolean isUpgrade = isUpgrade(); 7172 boolean doTrim = isUpgrade; 7173 if (doTrim) { 7174 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 7175 } else { 7176 final long interval = android.provider.Settings.Global.getLong( 7177 mContext.getContentResolver(), 7178 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 7179 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 7180 if (interval > 0) { 7181 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 7182 if (timeSinceLast > interval) { 7183 doTrim = true; 7184 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 7185 + "; running immediately"); 7186 } 7187 } 7188 } 7189 if (doTrim) { 7190 if (!isFirstBoot()) { 7191 try { 7192 ActivityManagerNative.getDefault().showBootMessage( 7193 mContext.getResources().getString( 7194 R.string.android_upgrading_fstrim), true); 7195 } catch (RemoteException e) { 7196 } 7197 } 7198 ms.runMaintenance(); 7199 } 7200 } else { 7201 Slog.e(TAG, "Mount service unavailable!"); 7202 } 7203 } catch (RemoteException e) { 7204 // Can't happen; MountService is local 7205 } 7206 } 7207 7208 @Override 7209 public void updatePackagesIfNeeded() { 7210 enforceSystemOrRoot("Only the system can request package update"); 7211 7212 // We need to re-extract after an OTA. 7213 boolean causeUpgrade = isUpgrade(); 7214 7215 // First boot or factory reset. 7216 // Note: we also handle devices that are upgrading to N right now as if it is their 7217 // first boot, as they do not have profile data. 7218 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 7219 7220 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 7221 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 7222 7223 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 7224 return; 7225 } 7226 7227 List<PackageParser.Package> pkgs; 7228 synchronized (mPackages) { 7229 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 7230 } 7231 7232 int numberOfPackagesVisited = 0; 7233 int numberOfPackagesOptimized = 0; 7234 int numberOfPackagesSkipped = 0; 7235 int numberOfPackagesFailed = 0; 7236 final int numberOfPackagesToDexopt = pkgs.size(); 7237 final long startTime = System.nanoTime(); 7238 7239 for (PackageParser.Package pkg : pkgs) { 7240 numberOfPackagesVisited++; 7241 7242 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 7243 if (DEBUG_DEXOPT) { 7244 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 7245 } 7246 numberOfPackagesSkipped++; 7247 continue; 7248 } 7249 7250 if (DEBUG_DEXOPT) { 7251 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 7252 numberOfPackagesToDexopt + ": " + pkg.packageName); 7253 } 7254 7255 if (mIsPreNUpgrade) { 7256 try { 7257 ActivityManagerNative.getDefault().showBootMessage( 7258 mContext.getResources().getString(R.string.android_upgrading_apk, 7259 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 7260 } catch (RemoteException e) { 7261 } 7262 } 7263 7264 // checkProfiles is false to avoid merging profiles during boot which 7265 // might interfere with background compilation (b/28612421). 7266 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 7267 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 7268 // trade-off worth doing to save boot time work. 7269 int dexOptStatus = performDexOptTraced(pkg.packageName, 7270 null /* instructionSet */, 7271 false /* checkProfiles */, 7272 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT), 7273 false /* force */); 7274 switch (dexOptStatus) { 7275 case PackageDexOptimizer.DEX_OPT_PERFORMED: 7276 numberOfPackagesOptimized++; 7277 break; 7278 case PackageDexOptimizer.DEX_OPT_SKIPPED: 7279 numberOfPackagesSkipped++; 7280 break; 7281 case PackageDexOptimizer.DEX_OPT_FAILED: 7282 numberOfPackagesFailed++; 7283 break; 7284 default: 7285 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 7286 break; 7287 } 7288 } 7289 7290 final int elapsedTimeSeconds = 7291 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 7292 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", numberOfPackagesOptimized); 7293 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", numberOfPackagesSkipped); 7294 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", numberOfPackagesFailed); 7295 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 7296 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 7297 } 7298 7299 @Override 7300 public void notifyPackageUse(String packageName, int reason) { 7301 synchronized (mPackages) { 7302 PackageParser.Package p = mPackages.get(packageName); 7303 if (p == null) { 7304 return; 7305 } 7306 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 7307 } 7308 } 7309 7310 // TODO: this is not used nor needed. Delete it. 7311 @Override 7312 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 7313 int dexOptStatus = performDexOptTraced(packageName, instructionSet, 7314 false /* checkProfiles */, getFullCompilerFilter(), false /* force */); 7315 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7316 } 7317 7318 @Override 7319 public boolean performDexOpt(String packageName, String instructionSet, 7320 boolean checkProfiles, int compileReason, boolean force) { 7321 int dexOptStatus = performDexOptTraced(packageName, instructionSet, checkProfiles, 7322 getCompilerFilterForReason(compileReason), force); 7323 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7324 } 7325 7326 @Override 7327 public boolean performDexOptMode(String packageName, String instructionSet, 7328 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7329 int dexOptStatus = performDexOptTraced(packageName, instructionSet, checkProfiles, 7330 targetCompilerFilter, force); 7331 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7332 } 7333 7334 private int performDexOptTraced(String packageName, String instructionSet, 7335 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7336 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7337 try { 7338 return performDexOptInternal(packageName, instructionSet, checkProfiles, 7339 targetCompilerFilter, force); 7340 } finally { 7341 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7342 } 7343 } 7344 7345 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 7346 // if the package can now be considered up to date for the given filter. 7347 private int performDexOptInternal(String packageName, String instructionSet, 7348 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7349 PackageParser.Package p; 7350 final String targetInstructionSet; 7351 synchronized (mPackages) { 7352 p = mPackages.get(packageName); 7353 if (p == null) { 7354 // Package could not be found. Report failure. 7355 return PackageDexOptimizer.DEX_OPT_FAILED; 7356 } 7357 mPackageUsage.write(false); 7358 7359 targetInstructionSet = instructionSet != null ? instructionSet : 7360 getPrimaryInstructionSet(p.applicationInfo); 7361 } 7362 long callingId = Binder.clearCallingIdentity(); 7363 try { 7364 synchronized (mInstallLock) { 7365 final String[] instructionSets = new String[] { targetInstructionSet }; 7366 return performDexOptInternalWithDependenciesLI(p, instructionSets, checkProfiles, 7367 targetCompilerFilter, force); 7368 } 7369 } finally { 7370 Binder.restoreCallingIdentity(callingId); 7371 } 7372 } 7373 7374 public ArraySet<String> getOptimizablePackages() { 7375 ArraySet<String> pkgs = new ArraySet<String>(); 7376 synchronized (mPackages) { 7377 for (PackageParser.Package p : mPackages.values()) { 7378 if (PackageDexOptimizer.canOptimizePackage(p)) { 7379 pkgs.add(p.packageName); 7380 } 7381 } 7382 } 7383 return pkgs; 7384 } 7385 7386 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7387 String instructionSets[], boolean checkProfiles, String targetCompilerFilter, 7388 boolean force) { 7389 // Select the dex optimizer based on the force parameter. 7390 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7391 // allocate an object here. 7392 PackageDexOptimizer pdo = force 7393 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7394 : mPackageDexOptimizer; 7395 7396 // Optimize all dependencies first. Note: we ignore the return value and march on 7397 // on errors. 7398 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7399 if (!deps.isEmpty()) { 7400 for (PackageParser.Package depPackage : deps) { 7401 // TODO: Analyze and investigate if we (should) profile libraries. 7402 // Currently this will do a full compilation of the library by default. 7403 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 7404 false /* checkProfiles */, 7405 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY)); 7406 } 7407 } 7408 7409 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 7410 targetCompilerFilter); 7411 } 7412 7413 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7414 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7415 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7416 Set<String> collectedNames = new HashSet<>(); 7417 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7418 7419 retValue.remove(p); 7420 7421 return retValue; 7422 } else { 7423 return Collections.emptyList(); 7424 } 7425 } 7426 7427 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7428 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7429 if (!collectedNames.contains(p.packageName)) { 7430 collectedNames.add(p.packageName); 7431 collected.add(p); 7432 7433 if (p.usesLibraries != null) { 7434 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7435 } 7436 if (p.usesOptionalLibraries != null) { 7437 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7438 collectedNames); 7439 } 7440 } 7441 } 7442 7443 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7444 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7445 for (String libName : libs) { 7446 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7447 if (libPkg != null) { 7448 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7449 } 7450 } 7451 } 7452 7453 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7454 synchronized (mPackages) { 7455 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7456 if (lib != null && lib.apk != null) { 7457 return mPackages.get(lib.apk); 7458 } 7459 } 7460 return null; 7461 } 7462 7463 public void shutdown() { 7464 mPackageUsage.write(true); 7465 } 7466 7467 @Override 7468 public void forceDexOpt(String packageName) { 7469 enforceSystemOrRoot("forceDexOpt"); 7470 7471 PackageParser.Package pkg; 7472 synchronized (mPackages) { 7473 pkg = mPackages.get(packageName); 7474 if (pkg == null) { 7475 throw new IllegalArgumentException("Unknown package: " + packageName); 7476 } 7477 } 7478 7479 synchronized (mInstallLock) { 7480 final String[] instructionSets = new String[] { 7481 getPrimaryInstructionSet(pkg.applicationInfo) }; 7482 7483 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7484 7485 // Whoever is calling forceDexOpt wants a fully compiled package. 7486 // Don't use profiles since that may cause compilation to be skipped. 7487 final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets, 7488 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7489 true /* force */); 7490 7491 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7492 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7493 throw new IllegalStateException("Failed to dexopt: " + res); 7494 } 7495 } 7496 } 7497 7498 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7499 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7500 Slog.w(TAG, "Unable to update from " + oldPkg.name 7501 + " to " + newPkg.packageName 7502 + ": old package not in system partition"); 7503 return false; 7504 } else if (mPackages.get(oldPkg.name) != null) { 7505 Slog.w(TAG, "Unable to update from " + oldPkg.name 7506 + " to " + newPkg.packageName 7507 + ": old package still exists"); 7508 return false; 7509 } 7510 return true; 7511 } 7512 7513 void removeCodePathLI(File codePath) { 7514 if (codePath.isDirectory()) { 7515 try { 7516 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7517 } catch (InstallerException e) { 7518 Slog.w(TAG, "Failed to remove code path", e); 7519 } 7520 } else { 7521 codePath.delete(); 7522 } 7523 } 7524 7525 private int[] resolveUserIds(int userId) { 7526 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 7527 } 7528 7529 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7530 if (pkg == null) { 7531 Slog.wtf(TAG, "Package was null!", new Throwable()); 7532 return; 7533 } 7534 clearAppDataLeafLIF(pkg, userId, flags); 7535 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7536 for (int i = 0; i < childCount; i++) { 7537 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7538 } 7539 } 7540 7541 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7542 final PackageSetting ps; 7543 synchronized (mPackages) { 7544 ps = mSettings.mPackages.get(pkg.packageName); 7545 } 7546 for (int realUserId : resolveUserIds(userId)) { 7547 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7548 try { 7549 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7550 ceDataInode); 7551 } catch (InstallerException e) { 7552 Slog.w(TAG, String.valueOf(e)); 7553 } 7554 } 7555 } 7556 7557 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7558 if (pkg == null) { 7559 Slog.wtf(TAG, "Package was null!", new Throwable()); 7560 return; 7561 } 7562 destroyAppDataLeafLIF(pkg, userId, flags); 7563 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7564 for (int i = 0; i < childCount; i++) { 7565 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7566 } 7567 } 7568 7569 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7570 final PackageSetting ps; 7571 synchronized (mPackages) { 7572 ps = mSettings.mPackages.get(pkg.packageName); 7573 } 7574 for (int realUserId : resolveUserIds(userId)) { 7575 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7576 try { 7577 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7578 ceDataInode); 7579 } catch (InstallerException e) { 7580 Slog.w(TAG, String.valueOf(e)); 7581 } 7582 } 7583 } 7584 7585 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 7586 if (pkg == null) { 7587 Slog.wtf(TAG, "Package was null!", new Throwable()); 7588 return; 7589 } 7590 destroyAppProfilesLeafLIF(pkg); 7591 destroyAppReferenceProfileLeafLIF(pkg, userId); 7592 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7593 for (int i = 0; i < childCount; i++) { 7594 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 7595 destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId); 7596 } 7597 } 7598 7599 private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId) { 7600 if (pkg.isForwardLocked()) { 7601 return; 7602 } 7603 7604 for (String path : pkg.getAllCodePathsExcludingResourceOnly()) { 7605 try { 7606 path = PackageManagerServiceUtils.realpath(new File(path)); 7607 } catch (IOException e) { 7608 // TODO: Should we return early here ? 7609 Slog.w(TAG, "Failed to get canonical path", e); 7610 continue; 7611 } 7612 7613 final String useMarker = path.replace('/', '@'); 7614 for (int realUserId : resolveUserIds(userId)) { 7615 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId); 7616 File foreignUseMark = new File(profileDir, useMarker); 7617 if (foreignUseMark.exists()) { 7618 if (!foreignUseMark.delete()) { 7619 Slog.w(TAG, "Unable to delete foreign user mark for package: " 7620 + pkg.packageName); 7621 } 7622 } 7623 7624 File[] markers = profileDir.listFiles(); 7625 if (markers != null) { 7626 final String searchString = "@" + pkg.packageName + "@"; 7627 // We also delete all markers that contain the package name we're 7628 // uninstalling. These are associated with secondary dex-files belonging 7629 // to the package. Reconstructing the path of these dex files is messy 7630 // in general. 7631 for (File marker : markers) { 7632 if (marker.getName().indexOf(searchString) > 0) { 7633 if (!marker.delete()) { 7634 Slog.w(TAG, "Unable to delete foreign user mark for package: " 7635 + pkg.packageName); 7636 } 7637 } 7638 } 7639 } 7640 } 7641 } 7642 } 7643 7644 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 7645 try { 7646 mInstaller.destroyAppProfiles(pkg.packageName); 7647 } catch (InstallerException e) { 7648 Slog.w(TAG, String.valueOf(e)); 7649 } 7650 } 7651 7652 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 7653 if (pkg == null) { 7654 Slog.wtf(TAG, "Package was null!", new Throwable()); 7655 return; 7656 } 7657 clearAppProfilesLeafLIF(pkg); 7658 destroyAppReferenceProfileLeafLIF(pkg, userId); 7659 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7660 for (int i = 0; i < childCount; i++) { 7661 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 7662 } 7663 } 7664 7665 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 7666 try { 7667 mInstaller.clearAppProfiles(pkg.packageName); 7668 } catch (InstallerException e) { 7669 Slog.w(TAG, String.valueOf(e)); 7670 } 7671 } 7672 7673 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7674 long lastUpdateTime) { 7675 // Set parent install/update time 7676 PackageSetting ps = (PackageSetting) pkg.mExtras; 7677 if (ps != null) { 7678 ps.firstInstallTime = firstInstallTime; 7679 ps.lastUpdateTime = lastUpdateTime; 7680 } 7681 // Set children install/update time 7682 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7683 for (int i = 0; i < childCount; i++) { 7684 PackageParser.Package childPkg = pkg.childPackages.get(i); 7685 ps = (PackageSetting) childPkg.mExtras; 7686 if (ps != null) { 7687 ps.firstInstallTime = firstInstallTime; 7688 ps.lastUpdateTime = lastUpdateTime; 7689 } 7690 } 7691 } 7692 7693 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7694 PackageParser.Package changingLib) { 7695 if (file.path != null) { 7696 usesLibraryFiles.add(file.path); 7697 return; 7698 } 7699 PackageParser.Package p = mPackages.get(file.apk); 7700 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7701 // If we are doing this while in the middle of updating a library apk, 7702 // then we need to make sure to use that new apk for determining the 7703 // dependencies here. (We haven't yet finished committing the new apk 7704 // to the package manager state.) 7705 if (p == null || p.packageName.equals(changingLib.packageName)) { 7706 p = changingLib; 7707 } 7708 } 7709 if (p != null) { 7710 usesLibraryFiles.addAll(p.getAllCodePaths()); 7711 } 7712 } 7713 7714 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7715 PackageParser.Package changingLib) throws PackageManagerException { 7716 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7717 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7718 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7719 for (int i=0; i<N; i++) { 7720 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7721 if (file == null) { 7722 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7723 "Package " + pkg.packageName + " requires unavailable shared library " 7724 + pkg.usesLibraries.get(i) + "; failing!"); 7725 } 7726 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7727 } 7728 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7729 for (int i=0; i<N; i++) { 7730 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7731 if (file == null) { 7732 Slog.w(TAG, "Package " + pkg.packageName 7733 + " desires unavailable shared library " 7734 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7735 } else { 7736 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7737 } 7738 } 7739 N = usesLibraryFiles.size(); 7740 if (N > 0) { 7741 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7742 } else { 7743 pkg.usesLibraryFiles = null; 7744 } 7745 } 7746 } 7747 7748 private static boolean hasString(List<String> list, List<String> which) { 7749 if (list == null) { 7750 return false; 7751 } 7752 for (int i=list.size()-1; i>=0; i--) { 7753 for (int j=which.size()-1; j>=0; j--) { 7754 if (which.get(j).equals(list.get(i))) { 7755 return true; 7756 } 7757 } 7758 } 7759 return false; 7760 } 7761 7762 private void updateAllSharedLibrariesLPw() { 7763 for (PackageParser.Package pkg : mPackages.values()) { 7764 try { 7765 updateSharedLibrariesLPw(pkg, null); 7766 } catch (PackageManagerException e) { 7767 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7768 } 7769 } 7770 } 7771 7772 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7773 PackageParser.Package changingPkg) { 7774 ArrayList<PackageParser.Package> res = null; 7775 for (PackageParser.Package pkg : mPackages.values()) { 7776 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7777 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7778 if (res == null) { 7779 res = new ArrayList<PackageParser.Package>(); 7780 } 7781 res.add(pkg); 7782 try { 7783 updateSharedLibrariesLPw(pkg, changingPkg); 7784 } catch (PackageManagerException e) { 7785 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7786 } 7787 } 7788 } 7789 return res; 7790 } 7791 7792 /** 7793 * Derive the value of the {@code cpuAbiOverride} based on the provided 7794 * value and an optional stored value from the package settings. 7795 */ 7796 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7797 String cpuAbiOverride = null; 7798 7799 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7800 cpuAbiOverride = null; 7801 } else if (abiOverride != null) { 7802 cpuAbiOverride = abiOverride; 7803 } else if (settings != null) { 7804 cpuAbiOverride = settings.cpuAbiOverrideString; 7805 } 7806 7807 return cpuAbiOverride; 7808 } 7809 7810 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 7811 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 7812 throws PackageManagerException { 7813 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7814 // If the package has children and this is the first dive in the function 7815 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7816 // whether all packages (parent and children) would be successfully scanned 7817 // before the actual scan since scanning mutates internal state and we want 7818 // to atomically install the package and its children. 7819 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7820 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7821 scanFlags |= SCAN_CHECK_ONLY; 7822 } 7823 } else { 7824 scanFlags &= ~SCAN_CHECK_ONLY; 7825 } 7826 7827 final PackageParser.Package scannedPkg; 7828 try { 7829 // Scan the parent 7830 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 7831 // Scan the children 7832 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7833 for (int i = 0; i < childCount; i++) { 7834 PackageParser.Package childPkg = pkg.childPackages.get(i); 7835 scanPackageLI(childPkg, policyFlags, 7836 scanFlags, currentTime, user); 7837 } 7838 } finally { 7839 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7840 } 7841 7842 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7843 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 7844 } 7845 7846 return scannedPkg; 7847 } 7848 7849 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 7850 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7851 boolean success = false; 7852 try { 7853 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 7854 currentTime, user); 7855 success = true; 7856 return res; 7857 } finally { 7858 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 7859 // DELETE_DATA_ON_FAILURES is only used by frozen paths 7860 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 7861 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 7862 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 7863 } 7864 } 7865 } 7866 7867 /** 7868 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 7869 */ 7870 private static boolean apkHasCode(String fileName) { 7871 StrictJarFile jarFile = null; 7872 try { 7873 jarFile = new StrictJarFile(fileName, 7874 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 7875 return jarFile.findEntry("classes.dex") != null; 7876 } catch (IOException ignore) { 7877 } finally { 7878 try { 7879 jarFile.close(); 7880 } catch (IOException ignore) {} 7881 } 7882 return false; 7883 } 7884 7885 /** 7886 * Enforces code policy for the package. This ensures that if an APK has 7887 * declared hasCode="true" in its manifest that the APK actually contains 7888 * code. 7889 * 7890 * @throws PackageManagerException If bytecode could not be found when it should exist 7891 */ 7892 private static void enforceCodePolicy(PackageParser.Package pkg) 7893 throws PackageManagerException { 7894 final boolean shouldHaveCode = 7895 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 7896 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 7897 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7898 "Package " + pkg.baseCodePath + " code is missing"); 7899 } 7900 7901 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 7902 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 7903 final boolean splitShouldHaveCode = 7904 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 7905 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 7906 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7907 "Package " + pkg.splitCodePaths[i] + " code is missing"); 7908 } 7909 } 7910 } 7911 } 7912 7913 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 7914 final int policyFlags, final int scanFlags, long currentTime, UserHandle user) 7915 throws PackageManagerException { 7916 final File scanFile = new File(pkg.codePath); 7917 if (pkg.applicationInfo.getCodePath() == null || 7918 pkg.applicationInfo.getResourcePath() == null) { 7919 // Bail out. The resource and code paths haven't been set. 7920 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7921 "Code and resource paths haven't been set correctly"); 7922 } 7923 7924 // Apply policy 7925 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 7926 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 7927 if (pkg.applicationInfo.isDirectBootAware()) { 7928 // we're direct boot aware; set for all components 7929 for (PackageParser.Service s : pkg.services) { 7930 s.info.encryptionAware = s.info.directBootAware = true; 7931 } 7932 for (PackageParser.Provider p : pkg.providers) { 7933 p.info.encryptionAware = p.info.directBootAware = true; 7934 } 7935 for (PackageParser.Activity a : pkg.activities) { 7936 a.info.encryptionAware = a.info.directBootAware = true; 7937 } 7938 for (PackageParser.Activity r : pkg.receivers) { 7939 r.info.encryptionAware = r.info.directBootAware = true; 7940 } 7941 } 7942 } else { 7943 // Only allow system apps to be flagged as core apps. 7944 pkg.coreApp = false; 7945 // clear flags not applicable to regular apps 7946 pkg.applicationInfo.privateFlags &= 7947 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 7948 pkg.applicationInfo.privateFlags &= 7949 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 7950 } 7951 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 7952 7953 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 7954 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7955 } 7956 7957 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 7958 enforceCodePolicy(pkg); 7959 } 7960 7961 if (mCustomResolverComponentName != null && 7962 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 7963 setUpCustomResolverActivity(pkg); 7964 } 7965 7966 if (pkg.packageName.equals("android")) { 7967 synchronized (mPackages) { 7968 if (mAndroidApplication != null) { 7969 Slog.w(TAG, "*************************************************"); 7970 Slog.w(TAG, "Core android package being redefined. Skipping."); 7971 Slog.w(TAG, " file=" + scanFile); 7972 Slog.w(TAG, "*************************************************"); 7973 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7974 "Core android package being redefined. Skipping."); 7975 } 7976 7977 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7978 // Set up information for our fall-back user intent resolution activity. 7979 mPlatformPackage = pkg; 7980 pkg.mVersionCode = mSdkVersion; 7981 mAndroidApplication = pkg.applicationInfo; 7982 7983 if (!mResolverReplaced) { 7984 mResolveActivity.applicationInfo = mAndroidApplication; 7985 mResolveActivity.name = ResolverActivity.class.getName(); 7986 mResolveActivity.packageName = mAndroidApplication.packageName; 7987 mResolveActivity.processName = "system:ui"; 7988 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7989 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 7990 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 7991 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 7992 mResolveActivity.exported = true; 7993 mResolveActivity.enabled = true; 7994 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 7995 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 7996 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 7997 | ActivityInfo.CONFIG_SCREEN_LAYOUT 7998 | ActivityInfo.CONFIG_ORIENTATION 7999 | ActivityInfo.CONFIG_KEYBOARD 8000 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 8001 mResolveInfo.activityInfo = mResolveActivity; 8002 mResolveInfo.priority = 0; 8003 mResolveInfo.preferredOrder = 0; 8004 mResolveInfo.match = 0; 8005 mResolveComponentName = new ComponentName( 8006 mAndroidApplication.packageName, mResolveActivity.name); 8007 } 8008 } 8009 } 8010 } 8011 8012 if (DEBUG_PACKAGE_SCANNING) { 8013 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8014 Log.d(TAG, "Scanning package " + pkg.packageName); 8015 } 8016 8017 synchronized (mPackages) { 8018 if (mPackages.containsKey(pkg.packageName) 8019 || mSharedLibraries.containsKey(pkg.packageName)) { 8020 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 8021 "Application package " + pkg.packageName 8022 + " already installed. Skipping duplicate."); 8023 } 8024 8025 // If we're only installing presumed-existing packages, require that the 8026 // scanned APK is both already known and at the path previously established 8027 // for it. Previously unknown packages we pick up normally, but if we have an 8028 // a priori expectation about this package's install presence, enforce it. 8029 // With a singular exception for new system packages. When an OTA contains 8030 // a new system package, we allow the codepath to change from a system location 8031 // to the user-installed location. If we don't allow this change, any newer, 8032 // user-installed version of the application will be ignored. 8033 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 8034 if (mExpectingBetter.containsKey(pkg.packageName)) { 8035 logCriticalInfo(Log.WARN, 8036 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 8037 } else { 8038 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 8039 if (known != null) { 8040 if (DEBUG_PACKAGE_SCANNING) { 8041 Log.d(TAG, "Examining " + pkg.codePath 8042 + " and requiring known paths " + known.codePathString 8043 + " & " + known.resourcePathString); 8044 } 8045 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 8046 || !pkg.applicationInfo.getResourcePath().equals( 8047 known.resourcePathString)) { 8048 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 8049 "Application package " + pkg.packageName 8050 + " found at " + pkg.applicationInfo.getCodePath() 8051 + " but expected at " + known.codePathString 8052 + "; ignoring."); 8053 } 8054 } 8055 } 8056 } 8057 } 8058 8059 // Initialize package source and resource directories 8060 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 8061 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 8062 8063 SharedUserSetting suid = null; 8064 PackageSetting pkgSetting = null; 8065 8066 if (!isSystemApp(pkg)) { 8067 // Only system apps can use these features. 8068 pkg.mOriginalPackages = null; 8069 pkg.mRealPackage = null; 8070 pkg.mAdoptPermissions = null; 8071 } 8072 8073 // Getting the package setting may have a side-effect, so if we 8074 // are only checking if scan would succeed, stash a copy of the 8075 // old setting to restore at the end. 8076 PackageSetting nonMutatedPs = null; 8077 8078 // writer 8079 synchronized (mPackages) { 8080 if (pkg.mSharedUserId != null) { 8081 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 8082 if (suid == null) { 8083 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8084 "Creating application package " + pkg.packageName 8085 + " for shared user failed"); 8086 } 8087 if (DEBUG_PACKAGE_SCANNING) { 8088 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8089 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 8090 + "): packages=" + suid.packages); 8091 } 8092 } 8093 8094 // Check if we are renaming from an original package name. 8095 PackageSetting origPackage = null; 8096 String realName = null; 8097 if (pkg.mOriginalPackages != null) { 8098 // This package may need to be renamed to a previously 8099 // installed name. Let's check on that... 8100 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 8101 if (pkg.mOriginalPackages.contains(renamed)) { 8102 // This package had originally been installed as the 8103 // original name, and we have already taken care of 8104 // transitioning to the new one. Just update the new 8105 // one to continue using the old name. 8106 realName = pkg.mRealPackage; 8107 if (!pkg.packageName.equals(renamed)) { 8108 // Callers into this function may have already taken 8109 // care of renaming the package; only do it here if 8110 // it is not already done. 8111 pkg.setPackageName(renamed); 8112 } 8113 8114 } else { 8115 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 8116 if ((origPackage = mSettings.peekPackageLPr( 8117 pkg.mOriginalPackages.get(i))) != null) { 8118 // We do have the package already installed under its 8119 // original name... should we use it? 8120 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 8121 // New package is not compatible with original. 8122 origPackage = null; 8123 continue; 8124 } else if (origPackage.sharedUser != null) { 8125 // Make sure uid is compatible between packages. 8126 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 8127 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 8128 + " to " + pkg.packageName + ": old uid " 8129 + origPackage.sharedUser.name 8130 + " differs from " + pkg.mSharedUserId); 8131 origPackage = null; 8132 continue; 8133 } 8134 // TODO: Add case when shared user id is added [b/28144775] 8135 } else { 8136 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 8137 + pkg.packageName + " to old name " + origPackage.name); 8138 } 8139 break; 8140 } 8141 } 8142 } 8143 } 8144 8145 if (mTransferedPackages.contains(pkg.packageName)) { 8146 Slog.w(TAG, "Package " + pkg.packageName 8147 + " was transferred to another, but its .apk remains"); 8148 } 8149 8150 // See comments in nonMutatedPs declaration 8151 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8152 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 8153 if (foundPs != null) { 8154 nonMutatedPs = new PackageSetting(foundPs); 8155 } 8156 } 8157 8158 // Just create the setting, don't add it yet. For already existing packages 8159 // the PkgSetting exists already and doesn't have to be created. 8160 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 8161 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 8162 pkg.applicationInfo.primaryCpuAbi, 8163 pkg.applicationInfo.secondaryCpuAbi, 8164 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 8165 user, false); 8166 if (pkgSetting == null) { 8167 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8168 "Creating application package " + pkg.packageName + " failed"); 8169 } 8170 8171 if (pkgSetting.origPackage != null) { 8172 // If we are first transitioning from an original package, 8173 // fix up the new package's name now. We need to do this after 8174 // looking up the package under its new name, so getPackageLP 8175 // can take care of fiddling things correctly. 8176 pkg.setPackageName(origPackage.name); 8177 8178 // File a report about this. 8179 String msg = "New package " + pkgSetting.realName 8180 + " renamed to replace old package " + pkgSetting.name; 8181 reportSettingsProblem(Log.WARN, msg); 8182 8183 // Make a note of it. 8184 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8185 mTransferedPackages.add(origPackage.name); 8186 } 8187 8188 // No longer need to retain this. 8189 pkgSetting.origPackage = null; 8190 } 8191 8192 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 8193 // Make a note of it. 8194 mTransferedPackages.add(pkg.packageName); 8195 } 8196 8197 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 8198 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 8199 } 8200 8201 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8202 // Check all shared libraries and map to their actual file path. 8203 // We only do this here for apps not on a system dir, because those 8204 // are the only ones that can fail an install due to this. We 8205 // will take care of the system apps by updating all of their 8206 // library paths after the scan is done. 8207 updateSharedLibrariesLPw(pkg, null); 8208 } 8209 8210 if (mFoundPolicyFile) { 8211 SELinuxMMAC.assignSeinfoValue(pkg); 8212 } 8213 8214 pkg.applicationInfo.uid = pkgSetting.appId; 8215 pkg.mExtras = pkgSetting; 8216 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 8217 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 8218 // We just determined the app is signed correctly, so bring 8219 // over the latest parsed certs. 8220 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8221 } else { 8222 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8223 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8224 "Package " + pkg.packageName + " upgrade keys do not match the " 8225 + "previously installed version"); 8226 } else { 8227 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8228 String msg = "System package " + pkg.packageName 8229 + " signature changed; retaining data."; 8230 reportSettingsProblem(Log.WARN, msg); 8231 } 8232 } 8233 } else { 8234 try { 8235 verifySignaturesLP(pkgSetting, pkg); 8236 // We just determined the app is signed correctly, so bring 8237 // over the latest parsed certs. 8238 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8239 } catch (PackageManagerException e) { 8240 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8241 throw e; 8242 } 8243 // The signature has changed, but this package is in the system 8244 // image... let's recover! 8245 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8246 // However... if this package is part of a shared user, but it 8247 // doesn't match the signature of the shared user, let's fail. 8248 // What this means is that you can't change the signatures 8249 // associated with an overall shared user, which doesn't seem all 8250 // that unreasonable. 8251 if (pkgSetting.sharedUser != null) { 8252 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8253 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 8254 throw new PackageManagerException( 8255 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 8256 "Signature mismatch for shared user: " 8257 + pkgSetting.sharedUser); 8258 } 8259 } 8260 // File a report about this. 8261 String msg = "System package " + pkg.packageName 8262 + " signature changed; retaining data."; 8263 reportSettingsProblem(Log.WARN, msg); 8264 } 8265 } 8266 // Verify that this new package doesn't have any content providers 8267 // that conflict with existing packages. Only do this if the 8268 // package isn't already installed, since we don't want to break 8269 // things that are installed. 8270 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 8271 final int N = pkg.providers.size(); 8272 int i; 8273 for (i=0; i<N; i++) { 8274 PackageParser.Provider p = pkg.providers.get(i); 8275 if (p.info.authority != null) { 8276 String names[] = p.info.authority.split(";"); 8277 for (int j = 0; j < names.length; j++) { 8278 if (mProvidersByAuthority.containsKey(names[j])) { 8279 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8280 final String otherPackageName = 8281 ((other != null && other.getComponentName() != null) ? 8282 other.getComponentName().getPackageName() : "?"); 8283 throw new PackageManagerException( 8284 INSTALL_FAILED_CONFLICTING_PROVIDER, 8285 "Can't install because provider name " + names[j] 8286 + " (in package " + pkg.applicationInfo.packageName 8287 + ") is already used by " + otherPackageName); 8288 } 8289 } 8290 } 8291 } 8292 } 8293 8294 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 8295 // This package wants to adopt ownership of permissions from 8296 // another package. 8297 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 8298 final String origName = pkg.mAdoptPermissions.get(i); 8299 final PackageSetting orig = mSettings.peekPackageLPr(origName); 8300 if (orig != null) { 8301 if (verifyPackageUpdateLPr(orig, pkg)) { 8302 Slog.i(TAG, "Adopting permissions from " + origName + " to " 8303 + pkg.packageName); 8304 mSettings.transferPermissionsLPw(origName, pkg.packageName); 8305 } 8306 } 8307 } 8308 } 8309 } 8310 8311 final String pkgName = pkg.packageName; 8312 8313 final long scanFileTime = scanFile.lastModified(); 8314 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 8315 pkg.applicationInfo.processName = fixProcessName( 8316 pkg.applicationInfo.packageName, 8317 pkg.applicationInfo.processName, 8318 pkg.applicationInfo.uid); 8319 8320 if (pkg != mPlatformPackage) { 8321 // Get all of our default paths setup 8322 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 8323 } 8324 8325 final String path = scanFile.getPath(); 8326 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 8327 8328 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 8329 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 8330 8331 // Some system apps still use directory structure for native libraries 8332 // in which case we might end up not detecting abi solely based on apk 8333 // structure. Try to detect abi based on directory structure. 8334 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 8335 pkg.applicationInfo.primaryCpuAbi == null) { 8336 setBundledAppAbisAndRoots(pkg, pkgSetting); 8337 setNativeLibraryPaths(pkg); 8338 } 8339 8340 } else { 8341 if ((scanFlags & SCAN_MOVE) != 0) { 8342 // We haven't run dex-opt for this move (since we've moved the compiled output too) 8343 // but we already have this packages package info in the PackageSetting. We just 8344 // use that and derive the native library path based on the new codepath. 8345 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 8346 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 8347 } 8348 8349 // Set native library paths again. For moves, the path will be updated based on the 8350 // ABIs we've determined above. For non-moves, the path will be updated based on the 8351 // ABIs we determined during compilation, but the path will depend on the final 8352 // package path (after the rename away from the stage path). 8353 setNativeLibraryPaths(pkg); 8354 } 8355 8356 // This is a special case for the "system" package, where the ABI is 8357 // dictated by the zygote configuration (and init.rc). We should keep track 8358 // of this ABI so that we can deal with "normal" applications that run under 8359 // the same UID correctly. 8360 if (mPlatformPackage == pkg) { 8361 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 8362 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 8363 } 8364 8365 // If there's a mismatch between the abi-override in the package setting 8366 // and the abiOverride specified for the install. Warn about this because we 8367 // would've already compiled the app without taking the package setting into 8368 // account. 8369 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 8370 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 8371 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 8372 " for package " + pkg.packageName); 8373 } 8374 } 8375 8376 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8377 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8378 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 8379 8380 // Copy the derived override back to the parsed package, so that we can 8381 // update the package settings accordingly. 8382 pkg.cpuAbiOverride = cpuAbiOverride; 8383 8384 if (DEBUG_ABI_SELECTION) { 8385 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 8386 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 8387 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 8388 } 8389 8390 // Push the derived path down into PackageSettings so we know what to 8391 // clean up at uninstall time. 8392 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 8393 8394 if (DEBUG_ABI_SELECTION) { 8395 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 8396 " primary=" + pkg.applicationInfo.primaryCpuAbi + 8397 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 8398 } 8399 8400 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 8401 // We don't do this here during boot because we can do it all 8402 // at once after scanning all existing packages. 8403 // 8404 // We also do this *before* we perform dexopt on this package, so that 8405 // we can avoid redundant dexopts, and also to make sure we've got the 8406 // code and package path correct. 8407 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 8408 pkg, true /* boot complete */); 8409 } 8410 8411 if (mFactoryTest && pkg.requestedPermissions.contains( 8412 android.Manifest.permission.FACTORY_TEST)) { 8413 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 8414 } 8415 8416 ArrayList<PackageParser.Package> clientLibPkgs = null; 8417 8418 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8419 if (nonMutatedPs != null) { 8420 synchronized (mPackages) { 8421 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 8422 } 8423 } 8424 return pkg; 8425 } 8426 8427 // Only privileged apps and updated privileged apps can add child packages. 8428 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 8429 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 8430 throw new PackageManagerException("Only privileged apps and updated " 8431 + "privileged apps can add child packages. Ignoring package " 8432 + pkg.packageName); 8433 } 8434 final int childCount = pkg.childPackages.size(); 8435 for (int i = 0; i < childCount; i++) { 8436 PackageParser.Package childPkg = pkg.childPackages.get(i); 8437 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 8438 childPkg.packageName)) { 8439 throw new PackageManagerException("Cannot override a child package of " 8440 + "another disabled system app. Ignoring package " + pkg.packageName); 8441 } 8442 } 8443 } 8444 8445 // writer 8446 synchronized (mPackages) { 8447 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8448 // Only system apps can add new shared libraries. 8449 if (pkg.libraryNames != null) { 8450 for (int i=0; i<pkg.libraryNames.size(); i++) { 8451 String name = pkg.libraryNames.get(i); 8452 boolean allowed = false; 8453 if (pkg.isUpdatedSystemApp()) { 8454 // New library entries can only be added through the 8455 // system image. This is important to get rid of a lot 8456 // of nasty edge cases: for example if we allowed a non- 8457 // system update of the app to add a library, then uninstalling 8458 // the update would make the library go away, and assumptions 8459 // we made such as through app install filtering would now 8460 // have allowed apps on the device which aren't compatible 8461 // with it. Better to just have the restriction here, be 8462 // conservative, and create many fewer cases that can negatively 8463 // impact the user experience. 8464 final PackageSetting sysPs = mSettings 8465 .getDisabledSystemPkgLPr(pkg.packageName); 8466 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 8467 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 8468 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 8469 allowed = true; 8470 break; 8471 } 8472 } 8473 } 8474 } else { 8475 allowed = true; 8476 } 8477 if (allowed) { 8478 if (!mSharedLibraries.containsKey(name)) { 8479 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 8480 } else if (!name.equals(pkg.packageName)) { 8481 Slog.w(TAG, "Package " + pkg.packageName + " library " 8482 + name + " already exists; skipping"); 8483 } 8484 } else { 8485 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 8486 + name + " that is not declared on system image; skipping"); 8487 } 8488 } 8489 if ((scanFlags & SCAN_BOOTING) == 0) { 8490 // If we are not booting, we need to update any applications 8491 // that are clients of our shared library. If we are booting, 8492 // this will all be done once the scan is complete. 8493 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 8494 } 8495 } 8496 } 8497 } 8498 8499 if ((scanFlags & SCAN_BOOTING) != 0) { 8500 // No apps can run during boot scan, so they don't need to be frozen 8501 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 8502 // Caller asked to not kill app, so it's probably not frozen 8503 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 8504 // Caller asked us to ignore frozen check for some reason; they 8505 // probably didn't know the package name 8506 } else { 8507 // We're doing major surgery on this package, so it better be frozen 8508 // right now to keep it from launching 8509 checkPackageFrozen(pkgName); 8510 } 8511 8512 // Also need to kill any apps that are dependent on the library. 8513 if (clientLibPkgs != null) { 8514 for (int i=0; i<clientLibPkgs.size(); i++) { 8515 PackageParser.Package clientPkg = clientLibPkgs.get(i); 8516 killApplication(clientPkg.applicationInfo.packageName, 8517 clientPkg.applicationInfo.uid, "update lib"); 8518 } 8519 } 8520 8521 // Make sure we're not adding any bogus keyset info 8522 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8523 ksms.assertScannedPackageValid(pkg); 8524 8525 // writer 8526 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 8527 8528 boolean createIdmapFailed = false; 8529 synchronized (mPackages) { 8530 // We don't expect installation to fail beyond this point 8531 8532 // Add the new setting to mSettings 8533 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 8534 // Add the new setting to mPackages 8535 mPackages.put(pkg.applicationInfo.packageName, pkg); 8536 // Make sure we don't accidentally delete its data. 8537 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 8538 while (iter.hasNext()) { 8539 PackageCleanItem item = iter.next(); 8540 if (pkgName.equals(item.packageName)) { 8541 iter.remove(); 8542 } 8543 } 8544 8545 // Take care of first install / last update times. 8546 if (currentTime != 0) { 8547 if (pkgSetting.firstInstallTime == 0) { 8548 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8549 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 8550 pkgSetting.lastUpdateTime = currentTime; 8551 } 8552 } else if (pkgSetting.firstInstallTime == 0) { 8553 // We need *something*. Take time time stamp of the file. 8554 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8555 } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8556 if (scanFileTime != pkgSetting.timeStamp) { 8557 // A package on the system image has changed; consider this 8558 // to be an update. 8559 pkgSetting.lastUpdateTime = scanFileTime; 8560 } 8561 } 8562 8563 // Add the package's KeySets to the global KeySetManagerService 8564 ksms.addScannedPackageLPw(pkg); 8565 8566 int N = pkg.providers.size(); 8567 StringBuilder r = null; 8568 int i; 8569 for (i=0; i<N; i++) { 8570 PackageParser.Provider p = pkg.providers.get(i); 8571 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 8572 p.info.processName, pkg.applicationInfo.uid); 8573 mProviders.addProvider(p); 8574 p.syncable = p.info.isSyncable; 8575 if (p.info.authority != null) { 8576 String names[] = p.info.authority.split(";"); 8577 p.info.authority = null; 8578 for (int j = 0; j < names.length; j++) { 8579 if (j == 1 && p.syncable) { 8580 // We only want the first authority for a provider to possibly be 8581 // syncable, so if we already added this provider using a different 8582 // authority clear the syncable flag. We copy the provider before 8583 // changing it because the mProviders object contains a reference 8584 // to a provider that we don't want to change. 8585 // Only do this for the second authority since the resulting provider 8586 // object can be the same for all future authorities for this provider. 8587 p = new PackageParser.Provider(p); 8588 p.syncable = false; 8589 } 8590 if (!mProvidersByAuthority.containsKey(names[j])) { 8591 mProvidersByAuthority.put(names[j], p); 8592 if (p.info.authority == null) { 8593 p.info.authority = names[j]; 8594 } else { 8595 p.info.authority = p.info.authority + ";" + names[j]; 8596 } 8597 if (DEBUG_PACKAGE_SCANNING) { 8598 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8599 Log.d(TAG, "Registered content provider: " + names[j] 8600 + ", className = " + p.info.name + ", isSyncable = " 8601 + p.info.isSyncable); 8602 } 8603 } else { 8604 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8605 Slog.w(TAG, "Skipping provider name " + names[j] + 8606 " (in package " + pkg.applicationInfo.packageName + 8607 "): name already used by " 8608 + ((other != null && other.getComponentName() != null) 8609 ? other.getComponentName().getPackageName() : "?")); 8610 } 8611 } 8612 } 8613 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8614 if (r == null) { 8615 r = new StringBuilder(256); 8616 } else { 8617 r.append(' '); 8618 } 8619 r.append(p.info.name); 8620 } 8621 } 8622 if (r != null) { 8623 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8624 } 8625 8626 N = pkg.services.size(); 8627 r = null; 8628 for (i=0; i<N; i++) { 8629 PackageParser.Service s = pkg.services.get(i); 8630 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8631 s.info.processName, pkg.applicationInfo.uid); 8632 mServices.addService(s); 8633 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8634 if (r == null) { 8635 r = new StringBuilder(256); 8636 } else { 8637 r.append(' '); 8638 } 8639 r.append(s.info.name); 8640 } 8641 } 8642 if (r != null) { 8643 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8644 } 8645 8646 N = pkg.receivers.size(); 8647 r = null; 8648 for (i=0; i<N; i++) { 8649 PackageParser.Activity a = pkg.receivers.get(i); 8650 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8651 a.info.processName, pkg.applicationInfo.uid); 8652 mReceivers.addActivity(a, "receiver"); 8653 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8654 if (r == null) { 8655 r = new StringBuilder(256); 8656 } else { 8657 r.append(' '); 8658 } 8659 r.append(a.info.name); 8660 } 8661 } 8662 if (r != null) { 8663 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8664 } 8665 8666 N = pkg.activities.size(); 8667 r = null; 8668 for (i=0; i<N; i++) { 8669 PackageParser.Activity a = pkg.activities.get(i); 8670 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8671 a.info.processName, pkg.applicationInfo.uid); 8672 mActivities.addActivity(a, "activity"); 8673 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8674 if (r == null) { 8675 r = new StringBuilder(256); 8676 } else { 8677 r.append(' '); 8678 } 8679 r.append(a.info.name); 8680 } 8681 } 8682 if (r != null) { 8683 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8684 } 8685 8686 N = pkg.permissionGroups.size(); 8687 r = null; 8688 for (i=0; i<N; i++) { 8689 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8690 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8691 if (cur == null) { 8692 mPermissionGroups.put(pg.info.name, pg); 8693 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8694 if (r == null) { 8695 r = new StringBuilder(256); 8696 } else { 8697 r.append(' '); 8698 } 8699 r.append(pg.info.name); 8700 } 8701 } else { 8702 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8703 + pg.info.packageName + " ignored: original from " 8704 + cur.info.packageName); 8705 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8706 if (r == null) { 8707 r = new StringBuilder(256); 8708 } else { 8709 r.append(' '); 8710 } 8711 r.append("DUP:"); 8712 r.append(pg.info.name); 8713 } 8714 } 8715 } 8716 if (r != null) { 8717 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8718 } 8719 8720 N = pkg.permissions.size(); 8721 r = null; 8722 for (i=0; i<N; i++) { 8723 PackageParser.Permission p = pkg.permissions.get(i); 8724 8725 // Assume by default that we did not install this permission into the system. 8726 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8727 8728 // Now that permission groups have a special meaning, we ignore permission 8729 // groups for legacy apps to prevent unexpected behavior. In particular, 8730 // permissions for one app being granted to someone just becase they happen 8731 // to be in a group defined by another app (before this had no implications). 8732 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8733 p.group = mPermissionGroups.get(p.info.group); 8734 // Warn for a permission in an unknown group. 8735 if (p.info.group != null && p.group == null) { 8736 Slog.w(TAG, "Permission " + p.info.name + " from package " 8737 + p.info.packageName + " in an unknown group " + p.info.group); 8738 } 8739 } 8740 8741 ArrayMap<String, BasePermission> permissionMap = 8742 p.tree ? mSettings.mPermissionTrees 8743 : mSettings.mPermissions; 8744 BasePermission bp = permissionMap.get(p.info.name); 8745 8746 // Allow system apps to redefine non-system permissions 8747 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8748 final boolean currentOwnerIsSystem = (bp.perm != null 8749 && isSystemApp(bp.perm.owner)); 8750 if (isSystemApp(p.owner)) { 8751 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8752 // It's a built-in permission and no owner, take ownership now 8753 bp.packageSetting = pkgSetting; 8754 bp.perm = p; 8755 bp.uid = pkg.applicationInfo.uid; 8756 bp.sourcePackage = p.info.packageName; 8757 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8758 } else if (!currentOwnerIsSystem) { 8759 String msg = "New decl " + p.owner + " of permission " 8760 + p.info.name + " is system; overriding " + bp.sourcePackage; 8761 reportSettingsProblem(Log.WARN, msg); 8762 bp = null; 8763 } 8764 } 8765 } 8766 8767 if (bp == null) { 8768 bp = new BasePermission(p.info.name, p.info.packageName, 8769 BasePermission.TYPE_NORMAL); 8770 permissionMap.put(p.info.name, bp); 8771 } 8772 8773 if (bp.perm == null) { 8774 if (bp.sourcePackage == null 8775 || bp.sourcePackage.equals(p.info.packageName)) { 8776 BasePermission tree = findPermissionTreeLP(p.info.name); 8777 if (tree == null 8778 || tree.sourcePackage.equals(p.info.packageName)) { 8779 bp.packageSetting = pkgSetting; 8780 bp.perm = p; 8781 bp.uid = pkg.applicationInfo.uid; 8782 bp.sourcePackage = p.info.packageName; 8783 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8784 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8785 if (r == null) { 8786 r = new StringBuilder(256); 8787 } else { 8788 r.append(' '); 8789 } 8790 r.append(p.info.name); 8791 } 8792 } else { 8793 Slog.w(TAG, "Permission " + p.info.name + " from package " 8794 + p.info.packageName + " ignored: base tree " 8795 + tree.name + " is from package " 8796 + tree.sourcePackage); 8797 } 8798 } else { 8799 Slog.w(TAG, "Permission " + p.info.name + " from package " 8800 + p.info.packageName + " ignored: original from " 8801 + bp.sourcePackage); 8802 } 8803 } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8804 if (r == null) { 8805 r = new StringBuilder(256); 8806 } else { 8807 r.append(' '); 8808 } 8809 r.append("DUP:"); 8810 r.append(p.info.name); 8811 } 8812 if (bp.perm == p) { 8813 bp.protectionLevel = p.info.protectionLevel; 8814 } 8815 } 8816 8817 if (r != null) { 8818 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 8819 } 8820 8821 N = pkg.instrumentation.size(); 8822 r = null; 8823 for (i=0; i<N; i++) { 8824 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8825 a.info.packageName = pkg.applicationInfo.packageName; 8826 a.info.sourceDir = pkg.applicationInfo.sourceDir; 8827 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 8828 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 8829 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 8830 a.info.dataDir = pkg.applicationInfo.dataDir; 8831 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 8832 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 8833 8834 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 8835 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 8836 mInstrumentation.put(a.getComponentName(), a); 8837 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8838 if (r == null) { 8839 r = new StringBuilder(256); 8840 } else { 8841 r.append(' '); 8842 } 8843 r.append(a.info.name); 8844 } 8845 } 8846 if (r != null) { 8847 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 8848 } 8849 8850 if (pkg.protectedBroadcasts != null) { 8851 N = pkg.protectedBroadcasts.size(); 8852 for (i=0; i<N; i++) { 8853 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 8854 } 8855 } 8856 8857 pkgSetting.setTimeStamp(scanFileTime); 8858 8859 // Create idmap files for pairs of (packages, overlay packages). 8860 // Note: "android", ie framework-res.apk, is handled by native layers. 8861 if (pkg.mOverlayTarget != null) { 8862 // This is an overlay package. 8863 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 8864 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 8865 mOverlays.put(pkg.mOverlayTarget, 8866 new ArrayMap<String, PackageParser.Package>()); 8867 } 8868 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 8869 map.put(pkg.packageName, pkg); 8870 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 8871 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 8872 createIdmapFailed = true; 8873 } 8874 } 8875 } else if (mOverlays.containsKey(pkg.packageName) && 8876 !pkg.packageName.equals("android")) { 8877 // This is a regular package, with one or more known overlay packages. 8878 createIdmapsForPackageLI(pkg); 8879 } 8880 } 8881 8882 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8883 8884 if (createIdmapFailed) { 8885 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8886 "scanPackageLI failed to createIdmap"); 8887 } 8888 return pkg; 8889 } 8890 8891 /** 8892 * Derive the ABI of a non-system package located at {@code scanFile}. This information 8893 * is derived purely on the basis of the contents of {@code scanFile} and 8894 * {@code cpuAbiOverride}. 8895 * 8896 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 8897 */ 8898 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 8899 String cpuAbiOverride, boolean extractLibs) 8900 throws PackageManagerException { 8901 // TODO: We can probably be smarter about this stuff. For installed apps, 8902 // we can calculate this information at install time once and for all. For 8903 // system apps, we can probably assume that this information doesn't change 8904 // after the first boot scan. As things stand, we do lots of unnecessary work. 8905 8906 // Give ourselves some initial paths; we'll come back for another 8907 // pass once we've determined ABI below. 8908 setNativeLibraryPaths(pkg); 8909 8910 // We would never need to extract libs for forward-locked and external packages, 8911 // since the container service will do it for us. We shouldn't attempt to 8912 // extract libs from system app when it was not updated. 8913 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 8914 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 8915 extractLibs = false; 8916 } 8917 8918 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 8919 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 8920 8921 NativeLibraryHelper.Handle handle = null; 8922 try { 8923 handle = NativeLibraryHelper.Handle.create(pkg); 8924 // TODO(multiArch): This can be null for apps that didn't go through the 8925 // usual installation process. We can calculate it again, like we 8926 // do during install time. 8927 // 8928 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 8929 // unnecessary. 8930 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 8931 8932 // Null out the abis so that they can be recalculated. 8933 pkg.applicationInfo.primaryCpuAbi = null; 8934 pkg.applicationInfo.secondaryCpuAbi = null; 8935 if (isMultiArch(pkg.applicationInfo)) { 8936 // Warn if we've set an abiOverride for multi-lib packages.. 8937 // By definition, we need to copy both 32 and 64 bit libraries for 8938 // such packages. 8939 if (pkg.cpuAbiOverride != null 8940 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 8941 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 8942 } 8943 8944 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 8945 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 8946 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 8947 if (extractLibs) { 8948 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8949 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 8950 useIsaSpecificSubdirs); 8951 } else { 8952 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 8953 } 8954 } 8955 8956 maybeThrowExceptionForMultiArchCopy( 8957 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 8958 8959 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 8960 if (extractLibs) { 8961 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8962 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 8963 useIsaSpecificSubdirs); 8964 } else { 8965 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 8966 } 8967 } 8968 8969 maybeThrowExceptionForMultiArchCopy( 8970 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 8971 8972 if (abi64 >= 0) { 8973 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 8974 } 8975 8976 if (abi32 >= 0) { 8977 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 8978 if (abi64 >= 0) { 8979 if (pkg.use32bitAbi) { 8980 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 8981 pkg.applicationInfo.primaryCpuAbi = abi; 8982 } else { 8983 pkg.applicationInfo.secondaryCpuAbi = abi; 8984 } 8985 } else { 8986 pkg.applicationInfo.primaryCpuAbi = abi; 8987 } 8988 } 8989 8990 } else { 8991 String[] abiList = (cpuAbiOverride != null) ? 8992 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 8993 8994 // Enable gross and lame hacks for apps that are built with old 8995 // SDK tools. We must scan their APKs for renderscript bitcode and 8996 // not launch them if it's present. Don't bother checking on devices 8997 // that don't have 64 bit support. 8998 boolean needsRenderScriptOverride = false; 8999 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 9000 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 9001 abiList = Build.SUPPORTED_32_BIT_ABIS; 9002 needsRenderScriptOverride = true; 9003 } 9004 9005 final int copyRet; 9006 if (extractLibs) { 9007 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9008 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 9009 } else { 9010 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 9011 } 9012 9013 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 9014 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 9015 "Error unpackaging native libs for app, errorCode=" + copyRet); 9016 } 9017 9018 if (copyRet >= 0) { 9019 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 9020 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 9021 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 9022 } else if (needsRenderScriptOverride) { 9023 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 9024 } 9025 } 9026 } catch (IOException ioe) { 9027 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 9028 } finally { 9029 IoUtils.closeQuietly(handle); 9030 } 9031 9032 // Now that we've calculated the ABIs and determined if it's an internal app, 9033 // we will go ahead and populate the nativeLibraryPath. 9034 setNativeLibraryPaths(pkg); 9035 } 9036 9037 /** 9038 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 9039 * i.e, so that all packages can be run inside a single process if required. 9040 * 9041 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 9042 * this function will either try and make the ABI for all packages in {@code packagesForUser} 9043 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 9044 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 9045 * updating a package that belongs to a shared user. 9046 * 9047 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 9048 * adds unnecessary complexity. 9049 */ 9050 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 9051 PackageParser.Package scannedPackage, boolean bootComplete) { 9052 String requiredInstructionSet = null; 9053 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 9054 requiredInstructionSet = VMRuntime.getInstructionSet( 9055 scannedPackage.applicationInfo.primaryCpuAbi); 9056 } 9057 9058 PackageSetting requirer = null; 9059 for (PackageSetting ps : packagesForUser) { 9060 // If packagesForUser contains scannedPackage, we skip it. This will happen 9061 // when scannedPackage is an update of an existing package. Without this check, 9062 // we will never be able to change the ABI of any package belonging to a shared 9063 // user, even if it's compatible with other packages. 9064 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9065 if (ps.primaryCpuAbiString == null) { 9066 continue; 9067 } 9068 9069 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 9070 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 9071 // We have a mismatch between instruction sets (say arm vs arm64) warn about 9072 // this but there's not much we can do. 9073 String errorMessage = "Instruction set mismatch, " 9074 + ((requirer == null) ? "[caller]" : requirer) 9075 + " requires " + requiredInstructionSet + " whereas " + ps 9076 + " requires " + instructionSet; 9077 Slog.w(TAG, errorMessage); 9078 } 9079 9080 if (requiredInstructionSet == null) { 9081 requiredInstructionSet = instructionSet; 9082 requirer = ps; 9083 } 9084 } 9085 } 9086 9087 if (requiredInstructionSet != null) { 9088 String adjustedAbi; 9089 if (requirer != null) { 9090 // requirer != null implies that either scannedPackage was null or that scannedPackage 9091 // did not require an ABI, in which case we have to adjust scannedPackage to match 9092 // the ABI of the set (which is the same as requirer's ABI) 9093 adjustedAbi = requirer.primaryCpuAbiString; 9094 if (scannedPackage != null) { 9095 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 9096 } 9097 } else { 9098 // requirer == null implies that we're updating all ABIs in the set to 9099 // match scannedPackage. 9100 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 9101 } 9102 9103 for (PackageSetting ps : packagesForUser) { 9104 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9105 if (ps.primaryCpuAbiString != null) { 9106 continue; 9107 } 9108 9109 ps.primaryCpuAbiString = adjustedAbi; 9110 if (ps.pkg != null && ps.pkg.applicationInfo != null && 9111 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 9112 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 9113 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 9114 + " (requirer=" 9115 + (requirer == null ? "null" : requirer.pkg.packageName) 9116 + ", scannedPackage=" 9117 + (scannedPackage != null ? scannedPackage.packageName : "null") 9118 + ")"); 9119 try { 9120 mInstaller.rmdex(ps.codePathString, 9121 getDexCodeInstructionSet(getPreferredInstructionSet())); 9122 } catch (InstallerException ignored) { 9123 } 9124 } 9125 } 9126 } 9127 } 9128 } 9129 9130 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 9131 synchronized (mPackages) { 9132 mResolverReplaced = true; 9133 // Set up information for custom user intent resolution activity. 9134 mResolveActivity.applicationInfo = pkg.applicationInfo; 9135 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 9136 mResolveActivity.packageName = pkg.applicationInfo.packageName; 9137 mResolveActivity.processName = pkg.applicationInfo.packageName; 9138 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9139 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9140 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9141 mResolveActivity.theme = 0; 9142 mResolveActivity.exported = true; 9143 mResolveActivity.enabled = true; 9144 mResolveInfo.activityInfo = mResolveActivity; 9145 mResolveInfo.priority = 0; 9146 mResolveInfo.preferredOrder = 0; 9147 mResolveInfo.match = 0; 9148 mResolveComponentName = mCustomResolverComponentName; 9149 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 9150 mResolveComponentName); 9151 } 9152 } 9153 9154 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 9155 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 9156 9157 // Set up information for ephemeral installer activity 9158 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 9159 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 9160 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 9161 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 9162 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9163 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9164 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9165 mEphemeralInstallerActivity.theme = 0; 9166 mEphemeralInstallerActivity.exported = true; 9167 mEphemeralInstallerActivity.enabled = true; 9168 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 9169 mEphemeralInstallerInfo.priority = 0; 9170 mEphemeralInstallerInfo.preferredOrder = 0; 9171 mEphemeralInstallerInfo.match = 0; 9172 9173 if (DEBUG_EPHEMERAL) { 9174 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 9175 } 9176 } 9177 9178 private static String calculateBundledApkRoot(final String codePathString) { 9179 final File codePath = new File(codePathString); 9180 final File codeRoot; 9181 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 9182 codeRoot = Environment.getRootDirectory(); 9183 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 9184 codeRoot = Environment.getOemDirectory(); 9185 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 9186 codeRoot = Environment.getVendorDirectory(); 9187 } else { 9188 // Unrecognized code path; take its top real segment as the apk root: 9189 // e.g. /something/app/blah.apk => /something 9190 try { 9191 File f = codePath.getCanonicalFile(); 9192 File parent = f.getParentFile(); // non-null because codePath is a file 9193 File tmp; 9194 while ((tmp = parent.getParentFile()) != null) { 9195 f = parent; 9196 parent = tmp; 9197 } 9198 codeRoot = f; 9199 Slog.w(TAG, "Unrecognized code path " 9200 + codePath + " - using " + codeRoot); 9201 } catch (IOException e) { 9202 // Can't canonicalize the code path -- shenanigans? 9203 Slog.w(TAG, "Can't canonicalize code path " + codePath); 9204 return Environment.getRootDirectory().getPath(); 9205 } 9206 } 9207 return codeRoot.getPath(); 9208 } 9209 9210 /** 9211 * Derive and set the location of native libraries for the given package, 9212 * which varies depending on where and how the package was installed. 9213 */ 9214 private void setNativeLibraryPaths(PackageParser.Package pkg) { 9215 final ApplicationInfo info = pkg.applicationInfo; 9216 final String codePath = pkg.codePath; 9217 final File codeFile = new File(codePath); 9218 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 9219 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 9220 9221 info.nativeLibraryRootDir = null; 9222 info.nativeLibraryRootRequiresIsa = false; 9223 info.nativeLibraryDir = null; 9224 info.secondaryNativeLibraryDir = null; 9225 9226 if (isApkFile(codeFile)) { 9227 // Monolithic install 9228 if (bundledApp) { 9229 // If "/system/lib64/apkname" exists, assume that is the per-package 9230 // native library directory to use; otherwise use "/system/lib/apkname". 9231 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 9232 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 9233 getPrimaryInstructionSet(info)); 9234 9235 // This is a bundled system app so choose the path based on the ABI. 9236 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 9237 // is just the default path. 9238 final String apkName = deriveCodePathName(codePath); 9239 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 9240 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 9241 apkName).getAbsolutePath(); 9242 9243 if (info.secondaryCpuAbi != null) { 9244 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 9245 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 9246 secondaryLibDir, apkName).getAbsolutePath(); 9247 } 9248 } else if (asecApp) { 9249 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 9250 .getAbsolutePath(); 9251 } else { 9252 final String apkName = deriveCodePathName(codePath); 9253 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 9254 .getAbsolutePath(); 9255 } 9256 9257 info.nativeLibraryRootRequiresIsa = false; 9258 info.nativeLibraryDir = info.nativeLibraryRootDir; 9259 } else { 9260 // Cluster install 9261 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 9262 info.nativeLibraryRootRequiresIsa = true; 9263 9264 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 9265 getPrimaryInstructionSet(info)).getAbsolutePath(); 9266 9267 if (info.secondaryCpuAbi != null) { 9268 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 9269 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 9270 } 9271 } 9272 } 9273 9274 /** 9275 * Calculate the abis and roots for a bundled app. These can uniquely 9276 * be determined from the contents of the system partition, i.e whether 9277 * it contains 64 or 32 bit shared libraries etc. We do not validate any 9278 * of this information, and instead assume that the system was built 9279 * sensibly. 9280 */ 9281 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 9282 PackageSetting pkgSetting) { 9283 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 9284 9285 // If "/system/lib64/apkname" exists, assume that is the per-package 9286 // native library directory to use; otherwise use "/system/lib/apkname". 9287 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 9288 setBundledAppAbi(pkg, apkRoot, apkName); 9289 // pkgSetting might be null during rescan following uninstall of updates 9290 // to a bundled app, so accommodate that possibility. The settings in 9291 // that case will be established later from the parsed package. 9292 // 9293 // If the settings aren't null, sync them up with what we've just derived. 9294 // note that apkRoot isn't stored in the package settings. 9295 if (pkgSetting != null) { 9296 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9297 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9298 } 9299 } 9300 9301 /** 9302 * Deduces the ABI of a bundled app and sets the relevant fields on the 9303 * parsed pkg object. 9304 * 9305 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 9306 * under which system libraries are installed. 9307 * @param apkName the name of the installed package. 9308 */ 9309 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 9310 final File codeFile = new File(pkg.codePath); 9311 9312 final boolean has64BitLibs; 9313 final boolean has32BitLibs; 9314 if (isApkFile(codeFile)) { 9315 // Monolithic install 9316 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 9317 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 9318 } else { 9319 // Cluster install 9320 final File rootDir = new File(codeFile, LIB_DIR_NAME); 9321 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 9322 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 9323 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 9324 has64BitLibs = (new File(rootDir, isa)).exists(); 9325 } else { 9326 has64BitLibs = false; 9327 } 9328 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 9329 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 9330 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 9331 has32BitLibs = (new File(rootDir, isa)).exists(); 9332 } else { 9333 has32BitLibs = false; 9334 } 9335 } 9336 9337 if (has64BitLibs && !has32BitLibs) { 9338 // The package has 64 bit libs, but not 32 bit libs. Its primary 9339 // ABI should be 64 bit. We can safely assume here that the bundled 9340 // native libraries correspond to the most preferred ABI in the list. 9341 9342 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9343 pkg.applicationInfo.secondaryCpuAbi = null; 9344 } else if (has32BitLibs && !has64BitLibs) { 9345 // The package has 32 bit libs but not 64 bit libs. Its primary 9346 // ABI should be 32 bit. 9347 9348 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9349 pkg.applicationInfo.secondaryCpuAbi = null; 9350 } else if (has32BitLibs && has64BitLibs) { 9351 // The application has both 64 and 32 bit bundled libraries. We check 9352 // here that the app declares multiArch support, and warn if it doesn't. 9353 // 9354 // We will be lenient here and record both ABIs. The primary will be the 9355 // ABI that's higher on the list, i.e, a device that's configured to prefer 9356 // 64 bit apps will see a 64 bit primary ABI, 9357 9358 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 9359 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 9360 } 9361 9362 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 9363 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9364 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9365 } else { 9366 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9367 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9368 } 9369 } else { 9370 pkg.applicationInfo.primaryCpuAbi = null; 9371 pkg.applicationInfo.secondaryCpuAbi = null; 9372 } 9373 } 9374 9375 private void killApplication(String pkgName, int appId, String reason) { 9376 // Request the ActivityManager to kill the process(only for existing packages) 9377 // so that we do not end up in a confused state while the user is still using the older 9378 // version of the application while the new one gets installed. 9379 final long token = Binder.clearCallingIdentity(); 9380 try { 9381 IActivityManager am = ActivityManagerNative.getDefault(); 9382 if (am != null) { 9383 try { 9384 am.killApplicationWithAppId(pkgName, appId, reason); 9385 } catch (RemoteException e) { 9386 } 9387 } 9388 } finally { 9389 Binder.restoreCallingIdentity(token); 9390 } 9391 } 9392 9393 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 9394 // Remove the parent package setting 9395 PackageSetting ps = (PackageSetting) pkg.mExtras; 9396 if (ps != null) { 9397 removePackageLI(ps, chatty); 9398 } 9399 // Remove the child package setting 9400 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9401 for (int i = 0; i < childCount; i++) { 9402 PackageParser.Package childPkg = pkg.childPackages.get(i); 9403 ps = (PackageSetting) childPkg.mExtras; 9404 if (ps != null) { 9405 removePackageLI(ps, chatty); 9406 } 9407 } 9408 } 9409 9410 void removePackageLI(PackageSetting ps, boolean chatty) { 9411 if (DEBUG_INSTALL) { 9412 if (chatty) 9413 Log.d(TAG, "Removing package " + ps.name); 9414 } 9415 9416 // writer 9417 synchronized (mPackages) { 9418 mPackages.remove(ps.name); 9419 final PackageParser.Package pkg = ps.pkg; 9420 if (pkg != null) { 9421 cleanPackageDataStructuresLILPw(pkg, chatty); 9422 } 9423 } 9424 } 9425 9426 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 9427 if (DEBUG_INSTALL) { 9428 if (chatty) 9429 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 9430 } 9431 9432 // writer 9433 synchronized (mPackages) { 9434 // Remove the parent package 9435 mPackages.remove(pkg.applicationInfo.packageName); 9436 cleanPackageDataStructuresLILPw(pkg, chatty); 9437 9438 // Remove the child packages 9439 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9440 for (int i = 0; i < childCount; i++) { 9441 PackageParser.Package childPkg = pkg.childPackages.get(i); 9442 mPackages.remove(childPkg.applicationInfo.packageName); 9443 cleanPackageDataStructuresLILPw(childPkg, chatty); 9444 } 9445 } 9446 } 9447 9448 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 9449 int N = pkg.providers.size(); 9450 StringBuilder r = null; 9451 int i; 9452 for (i=0; i<N; i++) { 9453 PackageParser.Provider p = pkg.providers.get(i); 9454 mProviders.removeProvider(p); 9455 if (p.info.authority == null) { 9456 9457 /* There was another ContentProvider with this authority when 9458 * this app was installed so this authority is null, 9459 * Ignore it as we don't have to unregister the provider. 9460 */ 9461 continue; 9462 } 9463 String names[] = p.info.authority.split(";"); 9464 for (int j = 0; j < names.length; j++) { 9465 if (mProvidersByAuthority.get(names[j]) == p) { 9466 mProvidersByAuthority.remove(names[j]); 9467 if (DEBUG_REMOVE) { 9468 if (chatty) 9469 Log.d(TAG, "Unregistered content provider: " + names[j] 9470 + ", className = " + p.info.name + ", isSyncable = " 9471 + p.info.isSyncable); 9472 } 9473 } 9474 } 9475 if (DEBUG_REMOVE && chatty) { 9476 if (r == null) { 9477 r = new StringBuilder(256); 9478 } else { 9479 r.append(' '); 9480 } 9481 r.append(p.info.name); 9482 } 9483 } 9484 if (r != null) { 9485 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 9486 } 9487 9488 N = pkg.services.size(); 9489 r = null; 9490 for (i=0; i<N; i++) { 9491 PackageParser.Service s = pkg.services.get(i); 9492 mServices.removeService(s); 9493 if (chatty) { 9494 if (r == null) { 9495 r = new StringBuilder(256); 9496 } else { 9497 r.append(' '); 9498 } 9499 r.append(s.info.name); 9500 } 9501 } 9502 if (r != null) { 9503 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 9504 } 9505 9506 N = pkg.receivers.size(); 9507 r = null; 9508 for (i=0; i<N; i++) { 9509 PackageParser.Activity a = pkg.receivers.get(i); 9510 mReceivers.removeActivity(a, "receiver"); 9511 if (DEBUG_REMOVE && chatty) { 9512 if (r == null) { 9513 r = new StringBuilder(256); 9514 } else { 9515 r.append(' '); 9516 } 9517 r.append(a.info.name); 9518 } 9519 } 9520 if (r != null) { 9521 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 9522 } 9523 9524 N = pkg.activities.size(); 9525 r = null; 9526 for (i=0; i<N; i++) { 9527 PackageParser.Activity a = pkg.activities.get(i); 9528 mActivities.removeActivity(a, "activity"); 9529 if (DEBUG_REMOVE && chatty) { 9530 if (r == null) { 9531 r = new StringBuilder(256); 9532 } else { 9533 r.append(' '); 9534 } 9535 r.append(a.info.name); 9536 } 9537 } 9538 if (r != null) { 9539 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 9540 } 9541 9542 N = pkg.permissions.size(); 9543 r = null; 9544 for (i=0; i<N; i++) { 9545 PackageParser.Permission p = pkg.permissions.get(i); 9546 BasePermission bp = mSettings.mPermissions.get(p.info.name); 9547 if (bp == null) { 9548 bp = mSettings.mPermissionTrees.get(p.info.name); 9549 } 9550 if (bp != null && bp.perm == p) { 9551 bp.perm = null; 9552 if (DEBUG_REMOVE && chatty) { 9553 if (r == null) { 9554 r = new StringBuilder(256); 9555 } else { 9556 r.append(' '); 9557 } 9558 r.append(p.info.name); 9559 } 9560 } 9561 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9562 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 9563 if (appOpPkgs != null) { 9564 appOpPkgs.remove(pkg.packageName); 9565 } 9566 } 9567 } 9568 if (r != null) { 9569 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9570 } 9571 9572 N = pkg.requestedPermissions.size(); 9573 r = null; 9574 for (i=0; i<N; i++) { 9575 String perm = pkg.requestedPermissions.get(i); 9576 BasePermission bp = mSettings.mPermissions.get(perm); 9577 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9578 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 9579 if (appOpPkgs != null) { 9580 appOpPkgs.remove(pkg.packageName); 9581 if (appOpPkgs.isEmpty()) { 9582 mAppOpPermissionPackages.remove(perm); 9583 } 9584 } 9585 } 9586 } 9587 if (r != null) { 9588 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9589 } 9590 9591 N = pkg.instrumentation.size(); 9592 r = null; 9593 for (i=0; i<N; i++) { 9594 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9595 mInstrumentation.remove(a.getComponentName()); 9596 if (DEBUG_REMOVE && chatty) { 9597 if (r == null) { 9598 r = new StringBuilder(256); 9599 } else { 9600 r.append(' '); 9601 } 9602 r.append(a.info.name); 9603 } 9604 } 9605 if (r != null) { 9606 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9607 } 9608 9609 r = null; 9610 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9611 // Only system apps can hold shared libraries. 9612 if (pkg.libraryNames != null) { 9613 for (i=0; i<pkg.libraryNames.size(); i++) { 9614 String name = pkg.libraryNames.get(i); 9615 SharedLibraryEntry cur = mSharedLibraries.get(name); 9616 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9617 mSharedLibraries.remove(name); 9618 if (DEBUG_REMOVE && chatty) { 9619 if (r == null) { 9620 r = new StringBuilder(256); 9621 } else { 9622 r.append(' '); 9623 } 9624 r.append(name); 9625 } 9626 } 9627 } 9628 } 9629 } 9630 if (r != null) { 9631 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9632 } 9633 } 9634 9635 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9636 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9637 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9638 return true; 9639 } 9640 } 9641 return false; 9642 } 9643 9644 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9645 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9646 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9647 9648 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9649 // Update the parent permissions 9650 updatePermissionsLPw(pkg.packageName, pkg, flags); 9651 // Update the child permissions 9652 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9653 for (int i = 0; i < childCount; i++) { 9654 PackageParser.Package childPkg = pkg.childPackages.get(i); 9655 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9656 } 9657 } 9658 9659 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9660 int flags) { 9661 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9662 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9663 } 9664 9665 private void updatePermissionsLPw(String changingPkg, 9666 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9667 // Make sure there are no dangling permission trees. 9668 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9669 while (it.hasNext()) { 9670 final BasePermission bp = it.next(); 9671 if (bp.packageSetting == null) { 9672 // We may not yet have parsed the package, so just see if 9673 // we still know about its settings. 9674 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9675 } 9676 if (bp.packageSetting == null) { 9677 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9678 + " from package " + bp.sourcePackage); 9679 it.remove(); 9680 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9681 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9682 Slog.i(TAG, "Removing old permission tree: " + bp.name 9683 + " from package " + bp.sourcePackage); 9684 flags |= UPDATE_PERMISSIONS_ALL; 9685 it.remove(); 9686 } 9687 } 9688 } 9689 9690 // Make sure all dynamic permissions have been assigned to a package, 9691 // and make sure there are no dangling permissions. 9692 it = mSettings.mPermissions.values().iterator(); 9693 while (it.hasNext()) { 9694 final BasePermission bp = it.next(); 9695 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9696 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9697 + bp.name + " pkg=" + bp.sourcePackage 9698 + " info=" + bp.pendingInfo); 9699 if (bp.packageSetting == null && bp.pendingInfo != null) { 9700 final BasePermission tree = findPermissionTreeLP(bp.name); 9701 if (tree != null && tree.perm != null) { 9702 bp.packageSetting = tree.packageSetting; 9703 bp.perm = new PackageParser.Permission(tree.perm.owner, 9704 new PermissionInfo(bp.pendingInfo)); 9705 bp.perm.info.packageName = tree.perm.info.packageName; 9706 bp.perm.info.name = bp.name; 9707 bp.uid = tree.uid; 9708 } 9709 } 9710 } 9711 if (bp.packageSetting == null) { 9712 // We may not yet have parsed the package, so just see if 9713 // we still know about its settings. 9714 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9715 } 9716 if (bp.packageSetting == null) { 9717 Slog.w(TAG, "Removing dangling permission: " + bp.name 9718 + " from package " + bp.sourcePackage); 9719 it.remove(); 9720 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9721 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9722 Slog.i(TAG, "Removing old permission: " + bp.name 9723 + " from package " + bp.sourcePackage); 9724 flags |= UPDATE_PERMISSIONS_ALL; 9725 it.remove(); 9726 } 9727 } 9728 } 9729 9730 // Now update the permissions for all packages, in particular 9731 // replace the granted permissions of the system packages. 9732 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9733 for (PackageParser.Package pkg : mPackages.values()) { 9734 if (pkg != pkgInfo) { 9735 // Only replace for packages on requested volume 9736 final String volumeUuid = getVolumeUuidForPackage(pkg); 9737 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9738 && Objects.equals(replaceVolumeUuid, volumeUuid); 9739 grantPermissionsLPw(pkg, replace, changingPkg); 9740 } 9741 } 9742 } 9743 9744 if (pkgInfo != null) { 9745 // Only replace for packages on requested volume 9746 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9747 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9748 && Objects.equals(replaceVolumeUuid, volumeUuid); 9749 grantPermissionsLPw(pkgInfo, replace, changingPkg); 9750 } 9751 } 9752 9753 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 9754 String packageOfInterest) { 9755 // IMPORTANT: There are two types of permissions: install and runtime. 9756 // Install time permissions are granted when the app is installed to 9757 // all device users and users added in the future. Runtime permissions 9758 // are granted at runtime explicitly to specific users. Normal and signature 9759 // protected permissions are install time permissions. Dangerous permissions 9760 // are install permissions if the app's target SDK is Lollipop MR1 or older, 9761 // otherwise they are runtime permissions. This function does not manage 9762 // runtime permissions except for the case an app targeting Lollipop MR1 9763 // being upgraded to target a newer SDK, in which case dangerous permissions 9764 // are transformed from install time to runtime ones. 9765 9766 final PackageSetting ps = (PackageSetting) pkg.mExtras; 9767 if (ps == null) { 9768 return; 9769 } 9770 9771 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 9772 9773 PermissionsState permissionsState = ps.getPermissionsState(); 9774 PermissionsState origPermissions = permissionsState; 9775 9776 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 9777 9778 boolean runtimePermissionsRevoked = false; 9779 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 9780 9781 boolean changedInstallPermission = false; 9782 9783 if (replace) { 9784 ps.installPermissionsFixed = false; 9785 if (!ps.isSharedUser()) { 9786 origPermissions = new PermissionsState(permissionsState); 9787 permissionsState.reset(); 9788 } else { 9789 // We need to know only about runtime permission changes since the 9790 // calling code always writes the install permissions state but 9791 // the runtime ones are written only if changed. The only cases of 9792 // changed runtime permissions here are promotion of an install to 9793 // runtime and revocation of a runtime from a shared user. 9794 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 9795 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 9796 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 9797 runtimePermissionsRevoked = true; 9798 } 9799 } 9800 } 9801 9802 permissionsState.setGlobalGids(mGlobalGids); 9803 9804 final int N = pkg.requestedPermissions.size(); 9805 for (int i=0; i<N; i++) { 9806 final String name = pkg.requestedPermissions.get(i); 9807 final BasePermission bp = mSettings.mPermissions.get(name); 9808 9809 if (DEBUG_INSTALL) { 9810 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 9811 } 9812 9813 if (bp == null || bp.packageSetting == null) { 9814 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9815 Slog.w(TAG, "Unknown permission " + name 9816 + " in package " + pkg.packageName); 9817 } 9818 continue; 9819 } 9820 9821 final String perm = bp.name; 9822 boolean allowedSig = false; 9823 int grant = GRANT_DENIED; 9824 9825 // Keep track of app op permissions. 9826 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9827 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 9828 if (pkgs == null) { 9829 pkgs = new ArraySet<>(); 9830 mAppOpPermissionPackages.put(bp.name, pkgs); 9831 } 9832 pkgs.add(pkg.packageName); 9833 } 9834 9835 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 9836 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 9837 >= Build.VERSION_CODES.M; 9838 switch (level) { 9839 case PermissionInfo.PROTECTION_NORMAL: { 9840 // For all apps normal permissions are install time ones. 9841 grant = GRANT_INSTALL; 9842 } break; 9843 9844 case PermissionInfo.PROTECTION_DANGEROUS: { 9845 // If a permission review is required for legacy apps we represent 9846 // their permissions as always granted runtime ones since we need 9847 // to keep the review required permission flag per user while an 9848 // install permission's state is shared across all users. 9849 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 9850 // For legacy apps dangerous permissions are install time ones. 9851 grant = GRANT_INSTALL; 9852 } else if (origPermissions.hasInstallPermission(bp.name)) { 9853 // For legacy apps that became modern, install becomes runtime. 9854 grant = GRANT_UPGRADE; 9855 } else if (mPromoteSystemApps 9856 && isSystemApp(ps) 9857 && mExistingSystemPackages.contains(ps.name)) { 9858 // For legacy system apps, install becomes runtime. 9859 // We cannot check hasInstallPermission() for system apps since those 9860 // permissions were granted implicitly and not persisted pre-M. 9861 grant = GRANT_UPGRADE; 9862 } else { 9863 // For modern apps keep runtime permissions unchanged. 9864 grant = GRANT_RUNTIME; 9865 } 9866 } break; 9867 9868 case PermissionInfo.PROTECTION_SIGNATURE: { 9869 // For all apps signature permissions are install time ones. 9870 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 9871 if (allowedSig) { 9872 grant = GRANT_INSTALL; 9873 } 9874 } break; 9875 } 9876 9877 if (DEBUG_INSTALL) { 9878 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 9879 } 9880 9881 if (grant != GRANT_DENIED) { 9882 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 9883 // If this is an existing, non-system package, then 9884 // we can't add any new permissions to it. 9885 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 9886 // Except... if this is a permission that was added 9887 // to the platform (note: need to only do this when 9888 // updating the platform). 9889 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 9890 grant = GRANT_DENIED; 9891 } 9892 } 9893 } 9894 9895 switch (grant) { 9896 case GRANT_INSTALL: { 9897 // Revoke this as runtime permission to handle the case of 9898 // a runtime permission being downgraded to an install one. 9899 // Also in permission review mode we keep dangerous permissions 9900 // for legacy apps 9901 for (int userId : UserManagerService.getInstance().getUserIds()) { 9902 if (origPermissions.getRuntimePermissionState( 9903 bp.name, userId) != null) { 9904 // Revoke the runtime permission and clear the flags. 9905 origPermissions.revokeRuntimePermission(bp, userId); 9906 origPermissions.updatePermissionFlags(bp, userId, 9907 PackageManager.MASK_PERMISSION_FLAGS, 0); 9908 // If we revoked a permission permission, we have to write. 9909 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9910 changedRuntimePermissionUserIds, userId); 9911 } 9912 } 9913 // Grant an install permission. 9914 if (permissionsState.grantInstallPermission(bp) != 9915 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9916 changedInstallPermission = true; 9917 } 9918 } break; 9919 9920 case GRANT_RUNTIME: { 9921 // Grant previously granted runtime permissions. 9922 for (int userId : UserManagerService.getInstance().getUserIds()) { 9923 PermissionState permissionState = origPermissions 9924 .getRuntimePermissionState(bp.name, userId); 9925 int flags = permissionState != null 9926 ? permissionState.getFlags() : 0; 9927 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 9928 if (permissionsState.grantRuntimePermission(bp, userId) == 9929 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9930 // If we cannot put the permission as it was, we have to write. 9931 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9932 changedRuntimePermissionUserIds, userId); 9933 } 9934 // If the app supports runtime permissions no need for a review. 9935 if (Build.PERMISSIONS_REVIEW_REQUIRED 9936 && appSupportsRuntimePermissions 9937 && (flags & PackageManager 9938 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 9939 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 9940 // Since we changed the flags, we have to write. 9941 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9942 changedRuntimePermissionUserIds, userId); 9943 } 9944 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 9945 && !appSupportsRuntimePermissions) { 9946 // For legacy apps that need a permission review, every new 9947 // runtime permission is granted but it is pending a review. 9948 // We also need to review only platform defined runtime 9949 // permissions as these are the only ones the platform knows 9950 // how to disable the API to simulate revocation as legacy 9951 // apps don't expect to run with revoked permissions. 9952 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 9953 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 9954 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 9955 // We changed the flags, hence have to write. 9956 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9957 changedRuntimePermissionUserIds, userId); 9958 } 9959 } 9960 if (permissionsState.grantRuntimePermission(bp, userId) 9961 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 9962 // We changed the permission, hence have to write. 9963 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9964 changedRuntimePermissionUserIds, userId); 9965 } 9966 } 9967 // Propagate the permission flags. 9968 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 9969 } 9970 } break; 9971 9972 case GRANT_UPGRADE: { 9973 // Grant runtime permissions for a previously held install permission. 9974 PermissionState permissionState = origPermissions 9975 .getInstallPermissionState(bp.name); 9976 final int flags = permissionState != null ? permissionState.getFlags() : 0; 9977 9978 if (origPermissions.revokeInstallPermission(bp) 9979 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 9980 // We will be transferring the permission flags, so clear them. 9981 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 9982 PackageManager.MASK_PERMISSION_FLAGS, 0); 9983 changedInstallPermission = true; 9984 } 9985 9986 // If the permission is not to be promoted to runtime we ignore it and 9987 // also its other flags as they are not applicable to install permissions. 9988 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 9989 for (int userId : currentUserIds) { 9990 if (permissionsState.grantRuntimePermission(bp, userId) != 9991 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9992 // Transfer the permission flags. 9993 permissionsState.updatePermissionFlags(bp, userId, 9994 flags, flags); 9995 // If we granted the permission, we have to write. 9996 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9997 changedRuntimePermissionUserIds, userId); 9998 } 9999 } 10000 } 10001 } break; 10002 10003 default: { 10004 if (packageOfInterest == null 10005 || packageOfInterest.equals(pkg.packageName)) { 10006 Slog.w(TAG, "Not granting permission " + perm 10007 + " to package " + pkg.packageName 10008 + " because it was previously installed without"); 10009 } 10010 } break; 10011 } 10012 } else { 10013 if (permissionsState.revokeInstallPermission(bp) != 10014 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10015 // Also drop the permission flags. 10016 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 10017 PackageManager.MASK_PERMISSION_FLAGS, 0); 10018 changedInstallPermission = true; 10019 Slog.i(TAG, "Un-granting permission " + perm 10020 + " from package " + pkg.packageName 10021 + " (protectionLevel=" + bp.protectionLevel 10022 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10023 + ")"); 10024 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 10025 // Don't print warning for app op permissions, since it is fine for them 10026 // not to be granted, there is a UI for the user to decide. 10027 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 10028 Slog.w(TAG, "Not granting permission " + perm 10029 + " to package " + pkg.packageName 10030 + " (protectionLevel=" + bp.protectionLevel 10031 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10032 + ")"); 10033 } 10034 } 10035 } 10036 } 10037 10038 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 10039 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 10040 // This is the first that we have heard about this package, so the 10041 // permissions we have now selected are fixed until explicitly 10042 // changed. 10043 ps.installPermissionsFixed = true; 10044 } 10045 10046 // Persist the runtime permissions state for users with changes. If permissions 10047 // were revoked because no app in the shared user declares them we have to 10048 // write synchronously to avoid losing runtime permissions state. 10049 for (int userId : changedRuntimePermissionUserIds) { 10050 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 10051 } 10052 10053 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10054 } 10055 10056 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 10057 boolean allowed = false; 10058 final int NP = PackageParser.NEW_PERMISSIONS.length; 10059 for (int ip=0; ip<NP; ip++) { 10060 final PackageParser.NewPermissionInfo npi 10061 = PackageParser.NEW_PERMISSIONS[ip]; 10062 if (npi.name.equals(perm) 10063 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 10064 allowed = true; 10065 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 10066 + pkg.packageName); 10067 break; 10068 } 10069 } 10070 return allowed; 10071 } 10072 10073 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 10074 BasePermission bp, PermissionsState origPermissions) { 10075 boolean allowed; 10076 allowed = (compareSignatures( 10077 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 10078 == PackageManager.SIGNATURE_MATCH) 10079 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 10080 == PackageManager.SIGNATURE_MATCH); 10081 if (!allowed && (bp.protectionLevel 10082 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 10083 if (isSystemApp(pkg)) { 10084 // For updated system applications, a system permission 10085 // is granted only if it had been defined by the original application. 10086 if (pkg.isUpdatedSystemApp()) { 10087 final PackageSetting sysPs = mSettings 10088 .getDisabledSystemPkgLPr(pkg.packageName); 10089 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 10090 // If the original was granted this permission, we take 10091 // that grant decision as read and propagate it to the 10092 // update. 10093 if (sysPs.isPrivileged()) { 10094 allowed = true; 10095 } 10096 } else { 10097 // The system apk may have been updated with an older 10098 // version of the one on the data partition, but which 10099 // granted a new system permission that it didn't have 10100 // before. In this case we do want to allow the app to 10101 // now get the new permission if the ancestral apk is 10102 // privileged to get it. 10103 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 10104 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 10105 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 10106 allowed = true; 10107 break; 10108 } 10109 } 10110 } 10111 // Also if a privileged parent package on the system image or any of 10112 // its children requested a privileged permission, the updated child 10113 // packages can also get the permission. 10114 if (pkg.parentPackage != null) { 10115 final PackageSetting disabledSysParentPs = mSettings 10116 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 10117 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 10118 && disabledSysParentPs.isPrivileged()) { 10119 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 10120 allowed = true; 10121 } else if (disabledSysParentPs.pkg.childPackages != null) { 10122 final int count = disabledSysParentPs.pkg.childPackages.size(); 10123 for (int i = 0; i < count; i++) { 10124 PackageParser.Package disabledSysChildPkg = 10125 disabledSysParentPs.pkg.childPackages.get(i); 10126 if (isPackageRequestingPermission(disabledSysChildPkg, 10127 perm)) { 10128 allowed = true; 10129 break; 10130 } 10131 } 10132 } 10133 } 10134 } 10135 } 10136 } else { 10137 allowed = isPrivilegedApp(pkg); 10138 } 10139 } 10140 } 10141 if (!allowed) { 10142 if (!allowed && (bp.protectionLevel 10143 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 10144 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 10145 // If this was a previously normal/dangerous permission that got moved 10146 // to a system permission as part of the runtime permission redesign, then 10147 // we still want to blindly grant it to old apps. 10148 allowed = true; 10149 } 10150 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 10151 && pkg.packageName.equals(mRequiredInstallerPackage)) { 10152 // If this permission is to be granted to the system installer and 10153 // this app is an installer, then it gets the permission. 10154 allowed = true; 10155 } 10156 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 10157 && pkg.packageName.equals(mRequiredVerifierPackage)) { 10158 // If this permission is to be granted to the system verifier and 10159 // this app is a verifier, then it gets the permission. 10160 allowed = true; 10161 } 10162 if (!allowed && (bp.protectionLevel 10163 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 10164 && isSystemApp(pkg)) { 10165 // Any pre-installed system app is allowed to get this permission. 10166 allowed = true; 10167 } 10168 if (!allowed && (bp.protectionLevel 10169 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 10170 // For development permissions, a development permission 10171 // is granted only if it was already granted. 10172 allowed = origPermissions.hasInstallPermission(perm); 10173 } 10174 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 10175 && pkg.packageName.equals(mSetupWizardPackage)) { 10176 // If this permission is to be granted to the system setup wizard and 10177 // this app is a setup wizard, then it gets the permission. 10178 allowed = true; 10179 } 10180 } 10181 return allowed; 10182 } 10183 10184 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 10185 final int permCount = pkg.requestedPermissions.size(); 10186 for (int j = 0; j < permCount; j++) { 10187 String requestedPermission = pkg.requestedPermissions.get(j); 10188 if (permission.equals(requestedPermission)) { 10189 return true; 10190 } 10191 } 10192 return false; 10193 } 10194 10195 final class ActivityIntentResolver 10196 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 10197 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10198 boolean defaultOnly, int userId) { 10199 if (!sUserManager.exists(userId)) return null; 10200 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10201 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10202 } 10203 10204 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10205 int userId) { 10206 if (!sUserManager.exists(userId)) return null; 10207 mFlags = flags; 10208 return super.queryIntent(intent, resolvedType, 10209 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10210 } 10211 10212 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10213 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 10214 if (!sUserManager.exists(userId)) return null; 10215 if (packageActivities == null) { 10216 return null; 10217 } 10218 mFlags = flags; 10219 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10220 final int N = packageActivities.size(); 10221 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 10222 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 10223 10224 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 10225 for (int i = 0; i < N; ++i) { 10226 intentFilters = packageActivities.get(i).intents; 10227 if (intentFilters != null && intentFilters.size() > 0) { 10228 PackageParser.ActivityIntentInfo[] array = 10229 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 10230 intentFilters.toArray(array); 10231 listCut.add(array); 10232 } 10233 } 10234 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10235 } 10236 10237 /** 10238 * Finds a privileged activity that matches the specified activity names. 10239 */ 10240 private PackageParser.Activity findMatchingActivity( 10241 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 10242 for (PackageParser.Activity sysActivity : activityList) { 10243 if (sysActivity.info.name.equals(activityInfo.name)) { 10244 return sysActivity; 10245 } 10246 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 10247 return sysActivity; 10248 } 10249 if (sysActivity.info.targetActivity != null) { 10250 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 10251 return sysActivity; 10252 } 10253 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 10254 return sysActivity; 10255 } 10256 } 10257 } 10258 return null; 10259 } 10260 10261 public class IterGenerator<E> { 10262 public Iterator<E> generate(ActivityIntentInfo info) { 10263 return null; 10264 } 10265 } 10266 10267 public class ActionIterGenerator extends IterGenerator<String> { 10268 @Override 10269 public Iterator<String> generate(ActivityIntentInfo info) { 10270 return info.actionsIterator(); 10271 } 10272 } 10273 10274 public class CategoriesIterGenerator extends IterGenerator<String> { 10275 @Override 10276 public Iterator<String> generate(ActivityIntentInfo info) { 10277 return info.categoriesIterator(); 10278 } 10279 } 10280 10281 public class SchemesIterGenerator extends IterGenerator<String> { 10282 @Override 10283 public Iterator<String> generate(ActivityIntentInfo info) { 10284 return info.schemesIterator(); 10285 } 10286 } 10287 10288 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 10289 @Override 10290 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 10291 return info.authoritiesIterator(); 10292 } 10293 } 10294 10295 /** 10296 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 10297 * MODIFIED. Do not pass in a list that should not be changed. 10298 */ 10299 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 10300 IterGenerator<T> generator, Iterator<T> searchIterator) { 10301 // loop through the set of actions; every one must be found in the intent filter 10302 while (searchIterator.hasNext()) { 10303 // we must have at least one filter in the list to consider a match 10304 if (intentList.size() == 0) { 10305 break; 10306 } 10307 10308 final T searchAction = searchIterator.next(); 10309 10310 // loop through the set of intent filters 10311 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 10312 while (intentIter.hasNext()) { 10313 final ActivityIntentInfo intentInfo = intentIter.next(); 10314 boolean selectionFound = false; 10315 10316 // loop through the intent filter's selection criteria; at least one 10317 // of them must match the searched criteria 10318 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 10319 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 10320 final T intentSelection = intentSelectionIter.next(); 10321 if (intentSelection != null && intentSelection.equals(searchAction)) { 10322 selectionFound = true; 10323 break; 10324 } 10325 } 10326 10327 // the selection criteria wasn't found in this filter's set; this filter 10328 // is not a potential match 10329 if (!selectionFound) { 10330 intentIter.remove(); 10331 } 10332 } 10333 } 10334 } 10335 10336 private boolean isProtectedAction(ActivityIntentInfo filter) { 10337 final Iterator<String> actionsIter = filter.actionsIterator(); 10338 while (actionsIter != null && actionsIter.hasNext()) { 10339 final String filterAction = actionsIter.next(); 10340 if (PROTECTED_ACTIONS.contains(filterAction)) { 10341 return true; 10342 } 10343 } 10344 return false; 10345 } 10346 10347 /** 10348 * Adjusts the priority of the given intent filter according to policy. 10349 * <p> 10350 * <ul> 10351 * <li>The priority for non privileged applications is capped to '0'</li> 10352 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 10353 * <li>The priority for unbundled updates to privileged applications is capped to the 10354 * priority defined on the system partition</li> 10355 * </ul> 10356 * <p> 10357 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 10358 * allowed to obtain any priority on any action. 10359 */ 10360 private void adjustPriority( 10361 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 10362 // nothing to do; priority is fine as-is 10363 if (intent.getPriority() <= 0) { 10364 return; 10365 } 10366 10367 final ActivityInfo activityInfo = intent.activity.info; 10368 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 10369 10370 final boolean privilegedApp = 10371 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 10372 if (!privilegedApp) { 10373 // non-privileged applications can never define a priority >0 10374 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 10375 + " package: " + applicationInfo.packageName 10376 + " activity: " + intent.activity.className 10377 + " origPrio: " + intent.getPriority()); 10378 intent.setPriority(0); 10379 return; 10380 } 10381 10382 if (systemActivities == null) { 10383 // the system package is not disabled; we're parsing the system partition 10384 if (isProtectedAction(intent)) { 10385 if (mDeferProtectedFilters) { 10386 // We can't deal with these just yet. No component should ever obtain a 10387 // >0 priority for a protected actions, with ONE exception -- the setup 10388 // wizard. The setup wizard, however, cannot be known until we're able to 10389 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 10390 // until all intent filters have been processed. Chicken, meet egg. 10391 // Let the filter temporarily have a high priority and rectify the 10392 // priorities after all system packages have been scanned. 10393 mProtectedFilters.add(intent); 10394 if (DEBUG_FILTERS) { 10395 Slog.i(TAG, "Protected action; save for later;" 10396 + " package: " + applicationInfo.packageName 10397 + " activity: " + intent.activity.className 10398 + " origPrio: " + intent.getPriority()); 10399 } 10400 return; 10401 } else { 10402 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 10403 Slog.i(TAG, "No setup wizard;" 10404 + " All protected intents capped to priority 0"); 10405 } 10406 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 10407 if (DEBUG_FILTERS) { 10408 Slog.i(TAG, "Found setup wizard;" 10409 + " allow priority " + intent.getPriority() + ";" 10410 + " package: " + intent.activity.info.packageName 10411 + " activity: " + intent.activity.className 10412 + " priority: " + intent.getPriority()); 10413 } 10414 // setup wizard gets whatever it wants 10415 return; 10416 } 10417 Slog.w(TAG, "Protected action; cap priority to 0;" 10418 + " package: " + intent.activity.info.packageName 10419 + " activity: " + intent.activity.className 10420 + " origPrio: " + intent.getPriority()); 10421 intent.setPriority(0); 10422 return; 10423 } 10424 } 10425 // privileged apps on the system image get whatever priority they request 10426 return; 10427 } 10428 10429 // privileged app unbundled update ... try to find the same activity 10430 final PackageParser.Activity foundActivity = 10431 findMatchingActivity(systemActivities, activityInfo); 10432 if (foundActivity == null) { 10433 // this is a new activity; it cannot obtain >0 priority 10434 if (DEBUG_FILTERS) { 10435 Slog.i(TAG, "New activity; cap priority to 0;" 10436 + " package: " + applicationInfo.packageName 10437 + " activity: " + intent.activity.className 10438 + " origPrio: " + intent.getPriority()); 10439 } 10440 intent.setPriority(0); 10441 return; 10442 } 10443 10444 // found activity, now check for filter equivalence 10445 10446 // a shallow copy is enough; we modify the list, not its contents 10447 final List<ActivityIntentInfo> intentListCopy = 10448 new ArrayList<>(foundActivity.intents); 10449 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 10450 10451 // find matching action subsets 10452 final Iterator<String> actionsIterator = intent.actionsIterator(); 10453 if (actionsIterator != null) { 10454 getIntentListSubset( 10455 intentListCopy, new ActionIterGenerator(), actionsIterator); 10456 if (intentListCopy.size() == 0) { 10457 // no more intents to match; we're not equivalent 10458 if (DEBUG_FILTERS) { 10459 Slog.i(TAG, "Mismatched action; cap priority to 0;" 10460 + " package: " + applicationInfo.packageName 10461 + " activity: " + intent.activity.className 10462 + " origPrio: " + intent.getPriority()); 10463 } 10464 intent.setPriority(0); 10465 return; 10466 } 10467 } 10468 10469 // find matching category subsets 10470 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 10471 if (categoriesIterator != null) { 10472 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 10473 categoriesIterator); 10474 if (intentListCopy.size() == 0) { 10475 // no more intents to match; we're not equivalent 10476 if (DEBUG_FILTERS) { 10477 Slog.i(TAG, "Mismatched category; cap priority to 0;" 10478 + " package: " + applicationInfo.packageName 10479 + " activity: " + intent.activity.className 10480 + " origPrio: " + intent.getPriority()); 10481 } 10482 intent.setPriority(0); 10483 return; 10484 } 10485 } 10486 10487 // find matching schemes subsets 10488 final Iterator<String> schemesIterator = intent.schemesIterator(); 10489 if (schemesIterator != null) { 10490 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 10491 schemesIterator); 10492 if (intentListCopy.size() == 0) { 10493 // no more intents to match; we're not equivalent 10494 if (DEBUG_FILTERS) { 10495 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 10496 + " package: " + applicationInfo.packageName 10497 + " activity: " + intent.activity.className 10498 + " origPrio: " + intent.getPriority()); 10499 } 10500 intent.setPriority(0); 10501 return; 10502 } 10503 } 10504 10505 // find matching authorities subsets 10506 final Iterator<IntentFilter.AuthorityEntry> 10507 authoritiesIterator = intent.authoritiesIterator(); 10508 if (authoritiesIterator != null) { 10509 getIntentListSubset(intentListCopy, 10510 new AuthoritiesIterGenerator(), 10511 authoritiesIterator); 10512 if (intentListCopy.size() == 0) { 10513 // no more intents to match; we're not equivalent 10514 if (DEBUG_FILTERS) { 10515 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 10516 + " package: " + applicationInfo.packageName 10517 + " activity: " + intent.activity.className 10518 + " origPrio: " + intent.getPriority()); 10519 } 10520 intent.setPriority(0); 10521 return; 10522 } 10523 } 10524 10525 // we found matching filter(s); app gets the max priority of all intents 10526 int cappedPriority = 0; 10527 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 10528 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 10529 } 10530 if (intent.getPriority() > cappedPriority) { 10531 if (DEBUG_FILTERS) { 10532 Slog.i(TAG, "Found matching filter(s);" 10533 + " cap priority to " + cappedPriority + ";" 10534 + " package: " + applicationInfo.packageName 10535 + " activity: " + intent.activity.className 10536 + " origPrio: " + intent.getPriority()); 10537 } 10538 intent.setPriority(cappedPriority); 10539 return; 10540 } 10541 // all this for nothing; the requested priority was <= what was on the system 10542 } 10543 10544 public final void addActivity(PackageParser.Activity a, String type) { 10545 mActivities.put(a.getComponentName(), a); 10546 if (DEBUG_SHOW_INFO) 10547 Log.v( 10548 TAG, " " + type + " " + 10549 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 10550 if (DEBUG_SHOW_INFO) 10551 Log.v(TAG, " Class=" + a.info.name); 10552 final int NI = a.intents.size(); 10553 for (int j=0; j<NI; j++) { 10554 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10555 if ("activity".equals(type)) { 10556 final PackageSetting ps = 10557 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 10558 final List<PackageParser.Activity> systemActivities = 10559 ps != null && ps.pkg != null ? ps.pkg.activities : null; 10560 adjustPriority(systemActivities, intent); 10561 } 10562 if (DEBUG_SHOW_INFO) { 10563 Log.v(TAG, " IntentFilter:"); 10564 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10565 } 10566 if (!intent.debugCheck()) { 10567 Log.w(TAG, "==> For Activity " + a.info.name); 10568 } 10569 addFilter(intent); 10570 } 10571 } 10572 10573 public final void removeActivity(PackageParser.Activity a, String type) { 10574 mActivities.remove(a.getComponentName()); 10575 if (DEBUG_SHOW_INFO) { 10576 Log.v(TAG, " " + type + " " 10577 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 10578 : a.info.name) + ":"); 10579 Log.v(TAG, " Class=" + a.info.name); 10580 } 10581 final int NI = a.intents.size(); 10582 for (int j=0; j<NI; j++) { 10583 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10584 if (DEBUG_SHOW_INFO) { 10585 Log.v(TAG, " IntentFilter:"); 10586 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10587 } 10588 removeFilter(intent); 10589 } 10590 } 10591 10592 @Override 10593 protected boolean allowFilterResult( 10594 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 10595 ActivityInfo filterAi = filter.activity.info; 10596 for (int i=dest.size()-1; i>=0; i--) { 10597 ActivityInfo destAi = dest.get(i).activityInfo; 10598 if (destAi.name == filterAi.name 10599 && destAi.packageName == filterAi.packageName) { 10600 return false; 10601 } 10602 } 10603 return true; 10604 } 10605 10606 @Override 10607 protected ActivityIntentInfo[] newArray(int size) { 10608 return new ActivityIntentInfo[size]; 10609 } 10610 10611 @Override 10612 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 10613 if (!sUserManager.exists(userId)) return true; 10614 PackageParser.Package p = filter.activity.owner; 10615 if (p != null) { 10616 PackageSetting ps = (PackageSetting)p.mExtras; 10617 if (ps != null) { 10618 // System apps are never considered stopped for purposes of 10619 // filtering, because there may be no way for the user to 10620 // actually re-launch them. 10621 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 10622 && ps.getStopped(userId); 10623 } 10624 } 10625 return false; 10626 } 10627 10628 @Override 10629 protected boolean isPackageForFilter(String packageName, 10630 PackageParser.ActivityIntentInfo info) { 10631 return packageName.equals(info.activity.owner.packageName); 10632 } 10633 10634 @Override 10635 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 10636 int match, int userId) { 10637 if (!sUserManager.exists(userId)) return null; 10638 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 10639 return null; 10640 } 10641 final PackageParser.Activity activity = info.activity; 10642 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 10643 if (ps == null) { 10644 return null; 10645 } 10646 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 10647 ps.readUserState(userId), userId); 10648 if (ai == null) { 10649 return null; 10650 } 10651 final ResolveInfo res = new ResolveInfo(); 10652 res.activityInfo = ai; 10653 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10654 res.filter = info; 10655 } 10656 if (info != null) { 10657 res.handleAllWebDataURI = info.handleAllWebDataURI(); 10658 } 10659 res.priority = info.getPriority(); 10660 res.preferredOrder = activity.owner.mPreferredOrder; 10661 //System.out.println("Result: " + res.activityInfo.className + 10662 // " = " + res.priority); 10663 res.match = match; 10664 res.isDefault = info.hasDefault; 10665 res.labelRes = info.labelRes; 10666 res.nonLocalizedLabel = info.nonLocalizedLabel; 10667 if (userNeedsBadging(userId)) { 10668 res.noResourceId = true; 10669 } else { 10670 res.icon = info.icon; 10671 } 10672 res.iconResourceId = info.icon; 10673 res.system = res.activityInfo.applicationInfo.isSystemApp(); 10674 return res; 10675 } 10676 10677 @Override 10678 protected void sortResults(List<ResolveInfo> results) { 10679 Collections.sort(results, mResolvePrioritySorter); 10680 } 10681 10682 @Override 10683 protected void dumpFilter(PrintWriter out, String prefix, 10684 PackageParser.ActivityIntentInfo filter) { 10685 out.print(prefix); out.print( 10686 Integer.toHexString(System.identityHashCode(filter.activity))); 10687 out.print(' '); 10688 filter.activity.printComponentShortName(out); 10689 out.print(" filter "); 10690 out.println(Integer.toHexString(System.identityHashCode(filter))); 10691 } 10692 10693 @Override 10694 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 10695 return filter.activity; 10696 } 10697 10698 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10699 PackageParser.Activity activity = (PackageParser.Activity)label; 10700 out.print(prefix); out.print( 10701 Integer.toHexString(System.identityHashCode(activity))); 10702 out.print(' '); 10703 activity.printComponentShortName(out); 10704 if (count > 1) { 10705 out.print(" ("); out.print(count); out.print(" filters)"); 10706 } 10707 out.println(); 10708 } 10709 10710 // Keys are String (activity class name), values are Activity. 10711 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 10712 = new ArrayMap<ComponentName, PackageParser.Activity>(); 10713 private int mFlags; 10714 } 10715 10716 private final class ServiceIntentResolver 10717 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 10718 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10719 boolean defaultOnly, int userId) { 10720 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10721 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10722 } 10723 10724 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10725 int userId) { 10726 if (!sUserManager.exists(userId)) return null; 10727 mFlags = flags; 10728 return super.queryIntent(intent, resolvedType, 10729 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10730 } 10731 10732 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10733 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 10734 if (!sUserManager.exists(userId)) return null; 10735 if (packageServices == null) { 10736 return null; 10737 } 10738 mFlags = flags; 10739 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10740 final int N = packageServices.size(); 10741 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 10742 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 10743 10744 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 10745 for (int i = 0; i < N; ++i) { 10746 intentFilters = packageServices.get(i).intents; 10747 if (intentFilters != null && intentFilters.size() > 0) { 10748 PackageParser.ServiceIntentInfo[] array = 10749 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 10750 intentFilters.toArray(array); 10751 listCut.add(array); 10752 } 10753 } 10754 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10755 } 10756 10757 public final void addService(PackageParser.Service s) { 10758 mServices.put(s.getComponentName(), s); 10759 if (DEBUG_SHOW_INFO) { 10760 Log.v(TAG, " " 10761 + (s.info.nonLocalizedLabel != null 10762 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10763 Log.v(TAG, " Class=" + s.info.name); 10764 } 10765 final int NI = s.intents.size(); 10766 int j; 10767 for (j=0; j<NI; j++) { 10768 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10769 if (DEBUG_SHOW_INFO) { 10770 Log.v(TAG, " IntentFilter:"); 10771 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10772 } 10773 if (!intent.debugCheck()) { 10774 Log.w(TAG, "==> For Service " + s.info.name); 10775 } 10776 addFilter(intent); 10777 } 10778 } 10779 10780 public final void removeService(PackageParser.Service s) { 10781 mServices.remove(s.getComponentName()); 10782 if (DEBUG_SHOW_INFO) { 10783 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 10784 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10785 Log.v(TAG, " Class=" + s.info.name); 10786 } 10787 final int NI = s.intents.size(); 10788 int j; 10789 for (j=0; j<NI; j++) { 10790 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10791 if (DEBUG_SHOW_INFO) { 10792 Log.v(TAG, " IntentFilter:"); 10793 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10794 } 10795 removeFilter(intent); 10796 } 10797 } 10798 10799 @Override 10800 protected boolean allowFilterResult( 10801 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 10802 ServiceInfo filterSi = filter.service.info; 10803 for (int i=dest.size()-1; i>=0; i--) { 10804 ServiceInfo destAi = dest.get(i).serviceInfo; 10805 if (destAi.name == filterSi.name 10806 && destAi.packageName == filterSi.packageName) { 10807 return false; 10808 } 10809 } 10810 return true; 10811 } 10812 10813 @Override 10814 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 10815 return new PackageParser.ServiceIntentInfo[size]; 10816 } 10817 10818 @Override 10819 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 10820 if (!sUserManager.exists(userId)) return true; 10821 PackageParser.Package p = filter.service.owner; 10822 if (p != null) { 10823 PackageSetting ps = (PackageSetting)p.mExtras; 10824 if (ps != null) { 10825 // System apps are never considered stopped for purposes of 10826 // filtering, because there may be no way for the user to 10827 // actually re-launch them. 10828 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10829 && ps.getStopped(userId); 10830 } 10831 } 10832 return false; 10833 } 10834 10835 @Override 10836 protected boolean isPackageForFilter(String packageName, 10837 PackageParser.ServiceIntentInfo info) { 10838 return packageName.equals(info.service.owner.packageName); 10839 } 10840 10841 @Override 10842 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 10843 int match, int userId) { 10844 if (!sUserManager.exists(userId)) return null; 10845 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 10846 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 10847 return null; 10848 } 10849 final PackageParser.Service service = info.service; 10850 PackageSetting ps = (PackageSetting) service.owner.mExtras; 10851 if (ps == null) { 10852 return null; 10853 } 10854 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 10855 ps.readUserState(userId), userId); 10856 if (si == null) { 10857 return null; 10858 } 10859 final ResolveInfo res = new ResolveInfo(); 10860 res.serviceInfo = si; 10861 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10862 res.filter = filter; 10863 } 10864 res.priority = info.getPriority(); 10865 res.preferredOrder = service.owner.mPreferredOrder; 10866 res.match = match; 10867 res.isDefault = info.hasDefault; 10868 res.labelRes = info.labelRes; 10869 res.nonLocalizedLabel = info.nonLocalizedLabel; 10870 res.icon = info.icon; 10871 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 10872 return res; 10873 } 10874 10875 @Override 10876 protected void sortResults(List<ResolveInfo> results) { 10877 Collections.sort(results, mResolvePrioritySorter); 10878 } 10879 10880 @Override 10881 protected void dumpFilter(PrintWriter out, String prefix, 10882 PackageParser.ServiceIntentInfo filter) { 10883 out.print(prefix); out.print( 10884 Integer.toHexString(System.identityHashCode(filter.service))); 10885 out.print(' '); 10886 filter.service.printComponentShortName(out); 10887 out.print(" filter "); 10888 out.println(Integer.toHexString(System.identityHashCode(filter))); 10889 } 10890 10891 @Override 10892 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 10893 return filter.service; 10894 } 10895 10896 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10897 PackageParser.Service service = (PackageParser.Service)label; 10898 out.print(prefix); out.print( 10899 Integer.toHexString(System.identityHashCode(service))); 10900 out.print(' '); 10901 service.printComponentShortName(out); 10902 if (count > 1) { 10903 out.print(" ("); out.print(count); out.print(" filters)"); 10904 } 10905 out.println(); 10906 } 10907 10908// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 10909// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 10910// final List<ResolveInfo> retList = Lists.newArrayList(); 10911// while (i.hasNext()) { 10912// final ResolveInfo resolveInfo = (ResolveInfo) i; 10913// if (isEnabledLP(resolveInfo.serviceInfo)) { 10914// retList.add(resolveInfo); 10915// } 10916// } 10917// return retList; 10918// } 10919 10920 // Keys are String (activity class name), values are Activity. 10921 private final ArrayMap<ComponentName, PackageParser.Service> mServices 10922 = new ArrayMap<ComponentName, PackageParser.Service>(); 10923 private int mFlags; 10924 }; 10925 10926 private final class ProviderIntentResolver 10927 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 10928 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10929 boolean defaultOnly, int userId) { 10930 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10931 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10932 } 10933 10934 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10935 int userId) { 10936 if (!sUserManager.exists(userId)) 10937 return null; 10938 mFlags = flags; 10939 return super.queryIntent(intent, resolvedType, 10940 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10941 } 10942 10943 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10944 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 10945 if (!sUserManager.exists(userId)) 10946 return null; 10947 if (packageProviders == null) { 10948 return null; 10949 } 10950 mFlags = flags; 10951 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 10952 final int N = packageProviders.size(); 10953 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 10954 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 10955 10956 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 10957 for (int i = 0; i < N; ++i) { 10958 intentFilters = packageProviders.get(i).intents; 10959 if (intentFilters != null && intentFilters.size() > 0) { 10960 PackageParser.ProviderIntentInfo[] array = 10961 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 10962 intentFilters.toArray(array); 10963 listCut.add(array); 10964 } 10965 } 10966 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10967 } 10968 10969 public final void addProvider(PackageParser.Provider p) { 10970 if (mProviders.containsKey(p.getComponentName())) { 10971 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 10972 return; 10973 } 10974 10975 mProviders.put(p.getComponentName(), p); 10976 if (DEBUG_SHOW_INFO) { 10977 Log.v(TAG, " " 10978 + (p.info.nonLocalizedLabel != null 10979 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10980 Log.v(TAG, " Class=" + p.info.name); 10981 } 10982 final int NI = p.intents.size(); 10983 int j; 10984 for (j = 0; j < NI; j++) { 10985 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10986 if (DEBUG_SHOW_INFO) { 10987 Log.v(TAG, " IntentFilter:"); 10988 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10989 } 10990 if (!intent.debugCheck()) { 10991 Log.w(TAG, "==> For Provider " + p.info.name); 10992 } 10993 addFilter(intent); 10994 } 10995 } 10996 10997 public final void removeProvider(PackageParser.Provider p) { 10998 mProviders.remove(p.getComponentName()); 10999 if (DEBUG_SHOW_INFO) { 11000 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 11001 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11002 Log.v(TAG, " Class=" + p.info.name); 11003 } 11004 final int NI = p.intents.size(); 11005 int j; 11006 for (j = 0; j < NI; j++) { 11007 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11008 if (DEBUG_SHOW_INFO) { 11009 Log.v(TAG, " IntentFilter:"); 11010 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11011 } 11012 removeFilter(intent); 11013 } 11014 } 11015 11016 @Override 11017 protected boolean allowFilterResult( 11018 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 11019 ProviderInfo filterPi = filter.provider.info; 11020 for (int i = dest.size() - 1; i >= 0; i--) { 11021 ProviderInfo destPi = dest.get(i).providerInfo; 11022 if (destPi.name == filterPi.name 11023 && destPi.packageName == filterPi.packageName) { 11024 return false; 11025 } 11026 } 11027 return true; 11028 } 11029 11030 @Override 11031 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 11032 return new PackageParser.ProviderIntentInfo[size]; 11033 } 11034 11035 @Override 11036 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 11037 if (!sUserManager.exists(userId)) 11038 return true; 11039 PackageParser.Package p = filter.provider.owner; 11040 if (p != null) { 11041 PackageSetting ps = (PackageSetting) p.mExtras; 11042 if (ps != null) { 11043 // System apps are never considered stopped for purposes of 11044 // filtering, because there may be no way for the user to 11045 // actually re-launch them. 11046 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 11047 && ps.getStopped(userId); 11048 } 11049 } 11050 return false; 11051 } 11052 11053 @Override 11054 protected boolean isPackageForFilter(String packageName, 11055 PackageParser.ProviderIntentInfo info) { 11056 return packageName.equals(info.provider.owner.packageName); 11057 } 11058 11059 @Override 11060 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 11061 int match, int userId) { 11062 if (!sUserManager.exists(userId)) 11063 return null; 11064 final PackageParser.ProviderIntentInfo info = filter; 11065 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 11066 return null; 11067 } 11068 final PackageParser.Provider provider = info.provider; 11069 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 11070 if (ps == null) { 11071 return null; 11072 } 11073 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 11074 ps.readUserState(userId), userId); 11075 if (pi == null) { 11076 return null; 11077 } 11078 final ResolveInfo res = new ResolveInfo(); 11079 res.providerInfo = pi; 11080 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 11081 res.filter = filter; 11082 } 11083 res.priority = info.getPriority(); 11084 res.preferredOrder = provider.owner.mPreferredOrder; 11085 res.match = match; 11086 res.isDefault = info.hasDefault; 11087 res.labelRes = info.labelRes; 11088 res.nonLocalizedLabel = info.nonLocalizedLabel; 11089 res.icon = info.icon; 11090 res.system = res.providerInfo.applicationInfo.isSystemApp(); 11091 return res; 11092 } 11093 11094 @Override 11095 protected void sortResults(List<ResolveInfo> results) { 11096 Collections.sort(results, mResolvePrioritySorter); 11097 } 11098 11099 @Override 11100 protected void dumpFilter(PrintWriter out, String prefix, 11101 PackageParser.ProviderIntentInfo filter) { 11102 out.print(prefix); 11103 out.print( 11104 Integer.toHexString(System.identityHashCode(filter.provider))); 11105 out.print(' '); 11106 filter.provider.printComponentShortName(out); 11107 out.print(" filter "); 11108 out.println(Integer.toHexString(System.identityHashCode(filter))); 11109 } 11110 11111 @Override 11112 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 11113 return filter.provider; 11114 } 11115 11116 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11117 PackageParser.Provider provider = (PackageParser.Provider)label; 11118 out.print(prefix); out.print( 11119 Integer.toHexString(System.identityHashCode(provider))); 11120 out.print(' '); 11121 provider.printComponentShortName(out); 11122 if (count > 1) { 11123 out.print(" ("); out.print(count); out.print(" filters)"); 11124 } 11125 out.println(); 11126 } 11127 11128 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 11129 = new ArrayMap<ComponentName, PackageParser.Provider>(); 11130 private int mFlags; 11131 } 11132 11133 private static final class EphemeralIntentResolver 11134 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 11135 @Override 11136 protected EphemeralResolveIntentInfo[] newArray(int size) { 11137 return new EphemeralResolveIntentInfo[size]; 11138 } 11139 11140 @Override 11141 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 11142 return true; 11143 } 11144 11145 @Override 11146 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 11147 int userId) { 11148 if (!sUserManager.exists(userId)) { 11149 return null; 11150 } 11151 return info.getEphemeralResolveInfo(); 11152 } 11153 } 11154 11155 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 11156 new Comparator<ResolveInfo>() { 11157 public int compare(ResolveInfo r1, ResolveInfo r2) { 11158 int v1 = r1.priority; 11159 int v2 = r2.priority; 11160 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 11161 if (v1 != v2) { 11162 return (v1 > v2) ? -1 : 1; 11163 } 11164 v1 = r1.preferredOrder; 11165 v2 = r2.preferredOrder; 11166 if (v1 != v2) { 11167 return (v1 > v2) ? -1 : 1; 11168 } 11169 if (r1.isDefault != r2.isDefault) { 11170 return r1.isDefault ? -1 : 1; 11171 } 11172 v1 = r1.match; 11173 v2 = r2.match; 11174 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 11175 if (v1 != v2) { 11176 return (v1 > v2) ? -1 : 1; 11177 } 11178 if (r1.system != r2.system) { 11179 return r1.system ? -1 : 1; 11180 } 11181 if (r1.activityInfo != null) { 11182 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 11183 } 11184 if (r1.serviceInfo != null) { 11185 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 11186 } 11187 if (r1.providerInfo != null) { 11188 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 11189 } 11190 return 0; 11191 } 11192 }; 11193 11194 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 11195 new Comparator<ProviderInfo>() { 11196 public int compare(ProviderInfo p1, ProviderInfo p2) { 11197 final int v1 = p1.initOrder; 11198 final int v2 = p2.initOrder; 11199 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 11200 } 11201 }; 11202 11203 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 11204 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 11205 final int[] userIds) { 11206 mHandler.post(new Runnable() { 11207 @Override 11208 public void run() { 11209 try { 11210 final IActivityManager am = ActivityManagerNative.getDefault(); 11211 if (am == null) return; 11212 final int[] resolvedUserIds; 11213 if (userIds == null) { 11214 resolvedUserIds = am.getRunningUserIds(); 11215 } else { 11216 resolvedUserIds = userIds; 11217 } 11218 for (int id : resolvedUserIds) { 11219 final Intent intent = new Intent(action, 11220 pkg != null ? Uri.fromParts("package", pkg, null) : null); 11221 if (extras != null) { 11222 intent.putExtras(extras); 11223 } 11224 if (targetPkg != null) { 11225 intent.setPackage(targetPkg); 11226 } 11227 // Modify the UID when posting to other users 11228 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 11229 if (uid > 0 && UserHandle.getUserId(uid) != id) { 11230 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 11231 intent.putExtra(Intent.EXTRA_UID, uid); 11232 } 11233 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 11234 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 11235 if (DEBUG_BROADCASTS) { 11236 RuntimeException here = new RuntimeException("here"); 11237 here.fillInStackTrace(); 11238 Slog.d(TAG, "Sending to user " + id + ": " 11239 + intent.toShortString(false, true, false, false) 11240 + " " + intent.getExtras(), here); 11241 } 11242 am.broadcastIntent(null, intent, null, finishedReceiver, 11243 0, null, null, null, android.app.AppOpsManager.OP_NONE, 11244 null, finishedReceiver != null, false, id); 11245 } 11246 } catch (RemoteException ex) { 11247 } 11248 } 11249 }); 11250 } 11251 11252 /** 11253 * Check if the external storage media is available. This is true if there 11254 * is a mounted external storage medium or if the external storage is 11255 * emulated. 11256 */ 11257 private boolean isExternalMediaAvailable() { 11258 return mMediaMounted || Environment.isExternalStorageEmulated(); 11259 } 11260 11261 @Override 11262 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 11263 // writer 11264 synchronized (mPackages) { 11265 if (!isExternalMediaAvailable()) { 11266 // If the external storage is no longer mounted at this point, 11267 // the caller may not have been able to delete all of this 11268 // packages files and can not delete any more. Bail. 11269 return null; 11270 } 11271 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 11272 if (lastPackage != null) { 11273 pkgs.remove(lastPackage); 11274 } 11275 if (pkgs.size() > 0) { 11276 return pkgs.get(0); 11277 } 11278 } 11279 return null; 11280 } 11281 11282 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 11283 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 11284 userId, andCode ? 1 : 0, packageName); 11285 if (mSystemReady) { 11286 msg.sendToTarget(); 11287 } else { 11288 if (mPostSystemReadyMessages == null) { 11289 mPostSystemReadyMessages = new ArrayList<>(); 11290 } 11291 mPostSystemReadyMessages.add(msg); 11292 } 11293 } 11294 11295 void startCleaningPackages() { 11296 // reader 11297 if (!isExternalMediaAvailable()) { 11298 return; 11299 } 11300 synchronized (mPackages) { 11301 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 11302 return; 11303 } 11304 } 11305 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 11306 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 11307 IActivityManager am = ActivityManagerNative.getDefault(); 11308 if (am != null) { 11309 try { 11310 am.startService(null, intent, null, mContext.getOpPackageName(), 11311 UserHandle.USER_SYSTEM); 11312 } catch (RemoteException e) { 11313 } 11314 } 11315 } 11316 11317 @Override 11318 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 11319 int installFlags, String installerPackageName, int userId) { 11320 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 11321 11322 final int callingUid = Binder.getCallingUid(); 11323 enforceCrossUserPermission(callingUid, userId, 11324 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 11325 11326 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11327 try { 11328 if (observer != null) { 11329 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 11330 } 11331 } catch (RemoteException re) { 11332 } 11333 return; 11334 } 11335 11336 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 11337 installFlags |= PackageManager.INSTALL_FROM_ADB; 11338 11339 } else { 11340 // Caller holds INSTALL_PACKAGES permission, so we're less strict 11341 // about installerPackageName. 11342 11343 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 11344 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 11345 } 11346 11347 UserHandle user; 11348 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 11349 user = UserHandle.ALL; 11350 } else { 11351 user = new UserHandle(userId); 11352 } 11353 11354 // Only system components can circumvent runtime permissions when installing. 11355 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 11356 && mContext.checkCallingOrSelfPermission(Manifest.permission 11357 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 11358 throw new SecurityException("You need the " 11359 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 11360 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 11361 } 11362 11363 final File originFile = new File(originPath); 11364 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 11365 11366 final Message msg = mHandler.obtainMessage(INIT_COPY); 11367 final VerificationInfo verificationInfo = new VerificationInfo( 11368 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 11369 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 11370 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 11371 null /*packageAbiOverride*/, null /*grantedPermissions*/, 11372 null /*certificates*/); 11373 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 11374 msg.obj = params; 11375 11376 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 11377 System.identityHashCode(msg.obj)); 11378 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11379 System.identityHashCode(msg.obj)); 11380 11381 mHandler.sendMessage(msg); 11382 } 11383 11384 void installStage(String packageName, File stagedDir, String stagedCid, 11385 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 11386 String installerPackageName, int installerUid, UserHandle user, 11387 Certificate[][] certificates) { 11388 if (DEBUG_EPHEMERAL) { 11389 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11390 Slog.d(TAG, "Ephemeral install of " + packageName); 11391 } 11392 } 11393 final VerificationInfo verificationInfo = new VerificationInfo( 11394 sessionParams.originatingUri, sessionParams.referrerUri, 11395 sessionParams.originatingUid, installerUid); 11396 11397 final OriginInfo origin; 11398 if (stagedDir != null) { 11399 origin = OriginInfo.fromStagedFile(stagedDir); 11400 } else { 11401 origin = OriginInfo.fromStagedContainer(stagedCid); 11402 } 11403 11404 final Message msg = mHandler.obtainMessage(INIT_COPY); 11405 final InstallParams params = new InstallParams(origin, null, observer, 11406 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 11407 verificationInfo, user, sessionParams.abiOverride, 11408 sessionParams.grantedRuntimePermissions, certificates); 11409 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 11410 msg.obj = params; 11411 11412 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 11413 System.identityHashCode(msg.obj)); 11414 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11415 System.identityHashCode(msg.obj)); 11416 11417 mHandler.sendMessage(msg); 11418 } 11419 11420 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 11421 int userId) { 11422 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 11423 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId); 11424 } 11425 11426 private void sendPackageAddedForUser(String packageName, boolean isSystem, 11427 int appId, int userId) { 11428 Bundle extras = new Bundle(1); 11429 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId)); 11430 11431 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 11432 packageName, extras, 0, null, null, new int[] {userId}); 11433 try { 11434 IActivityManager am = ActivityManagerNative.getDefault(); 11435 if (isSystem && am.isUserRunning(userId, 0)) { 11436 // The just-installed/enabled app is bundled on the system, so presumed 11437 // to be able to run automatically without needing an explicit launch. 11438 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 11439 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 11440 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 11441 .setPackage(packageName); 11442 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 11443 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 11444 } 11445 } catch (RemoteException e) { 11446 // shouldn't happen 11447 Slog.w(TAG, "Unable to bootstrap installed package", e); 11448 } 11449 } 11450 11451 @Override 11452 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 11453 int userId) { 11454 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11455 PackageSetting pkgSetting; 11456 final int uid = Binder.getCallingUid(); 11457 enforceCrossUserPermission(uid, userId, 11458 true /* requireFullPermission */, true /* checkShell */, 11459 "setApplicationHiddenSetting for user " + userId); 11460 11461 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 11462 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 11463 return false; 11464 } 11465 11466 long callingId = Binder.clearCallingIdentity(); 11467 try { 11468 boolean sendAdded = false; 11469 boolean sendRemoved = false; 11470 // writer 11471 synchronized (mPackages) { 11472 pkgSetting = mSettings.mPackages.get(packageName); 11473 if (pkgSetting == null) { 11474 return false; 11475 } 11476 if (pkgSetting.getHidden(userId) != hidden) { 11477 pkgSetting.setHidden(hidden, userId); 11478 mSettings.writePackageRestrictionsLPr(userId); 11479 if (hidden) { 11480 sendRemoved = true; 11481 } else { 11482 sendAdded = true; 11483 } 11484 } 11485 } 11486 if (sendAdded) { 11487 sendPackageAddedForUser(packageName, pkgSetting, userId); 11488 return true; 11489 } 11490 if (sendRemoved) { 11491 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 11492 "hiding pkg"); 11493 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 11494 return true; 11495 } 11496 } finally { 11497 Binder.restoreCallingIdentity(callingId); 11498 } 11499 return false; 11500 } 11501 11502 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 11503 int userId) { 11504 final PackageRemovedInfo info = new PackageRemovedInfo(); 11505 info.removedPackage = packageName; 11506 info.removedUsers = new int[] {userId}; 11507 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 11508 info.sendPackageRemovedBroadcasts(true /*killApp*/); 11509 } 11510 11511 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 11512 if (pkgList.length > 0) { 11513 Bundle extras = new Bundle(1); 11514 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 11515 11516 sendPackageBroadcast( 11517 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 11518 : Intent.ACTION_PACKAGES_UNSUSPENDED, 11519 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 11520 new int[] {userId}); 11521 } 11522 } 11523 11524 /** 11525 * Returns true if application is not found or there was an error. Otherwise it returns 11526 * the hidden state of the package for the given user. 11527 */ 11528 @Override 11529 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 11530 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11531 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11532 true /* requireFullPermission */, false /* checkShell */, 11533 "getApplicationHidden for user " + userId); 11534 PackageSetting pkgSetting; 11535 long callingId = Binder.clearCallingIdentity(); 11536 try { 11537 // writer 11538 synchronized (mPackages) { 11539 pkgSetting = mSettings.mPackages.get(packageName); 11540 if (pkgSetting == null) { 11541 return true; 11542 } 11543 return pkgSetting.getHidden(userId); 11544 } 11545 } finally { 11546 Binder.restoreCallingIdentity(callingId); 11547 } 11548 } 11549 11550 /** 11551 * @hide 11552 */ 11553 @Override 11554 public int installExistingPackageAsUser(String packageName, int userId) { 11555 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 11556 null); 11557 PackageSetting pkgSetting; 11558 final int uid = Binder.getCallingUid(); 11559 enforceCrossUserPermission(uid, userId, 11560 true /* requireFullPermission */, true /* checkShell */, 11561 "installExistingPackage for user " + userId); 11562 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11563 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 11564 } 11565 11566 long callingId = Binder.clearCallingIdentity(); 11567 try { 11568 boolean installed = false; 11569 11570 // writer 11571 synchronized (mPackages) { 11572 pkgSetting = mSettings.mPackages.get(packageName); 11573 if (pkgSetting == null) { 11574 return PackageManager.INSTALL_FAILED_INVALID_URI; 11575 } 11576 if (!pkgSetting.getInstalled(userId)) { 11577 pkgSetting.setInstalled(true, userId); 11578 pkgSetting.setHidden(false, userId); 11579 mSettings.writePackageRestrictionsLPr(userId); 11580 installed = true; 11581 } 11582 } 11583 11584 if (installed) { 11585 if (pkgSetting.pkg != null) { 11586 synchronized (mInstallLock) { 11587 // We don't need to freeze for a brand new install 11588 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 11589 } 11590 } 11591 sendPackageAddedForUser(packageName, pkgSetting, userId); 11592 } 11593 } finally { 11594 Binder.restoreCallingIdentity(callingId); 11595 } 11596 11597 return PackageManager.INSTALL_SUCCEEDED; 11598 } 11599 11600 boolean isUserRestricted(int userId, String restrictionKey) { 11601 Bundle restrictions = sUserManager.getUserRestrictions(userId); 11602 if (restrictions.getBoolean(restrictionKey, false)) { 11603 Log.w(TAG, "User is restricted: " + restrictionKey); 11604 return true; 11605 } 11606 return false; 11607 } 11608 11609 @Override 11610 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 11611 int userId) { 11612 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11613 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11614 true /* requireFullPermission */, true /* checkShell */, 11615 "setPackagesSuspended for user " + userId); 11616 11617 if (ArrayUtils.isEmpty(packageNames)) { 11618 return packageNames; 11619 } 11620 11621 // List of package names for whom the suspended state has changed. 11622 List<String> changedPackages = new ArrayList<>(packageNames.length); 11623 // List of package names for whom the suspended state is not set as requested in this 11624 // method. 11625 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 11626 long callingId = Binder.clearCallingIdentity(); 11627 try { 11628 for (int i = 0; i < packageNames.length; i++) { 11629 String packageName = packageNames[i]; 11630 boolean changed = false; 11631 final int appId; 11632 synchronized (mPackages) { 11633 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11634 if (pkgSetting == null) { 11635 Slog.w(TAG, "Could not find package setting for package \"" + packageName 11636 + "\". Skipping suspending/un-suspending."); 11637 unactionedPackages.add(packageName); 11638 continue; 11639 } 11640 appId = pkgSetting.appId; 11641 if (pkgSetting.getSuspended(userId) != suspended) { 11642 if (!canSuspendPackageForUserLocked(packageName, userId)) { 11643 unactionedPackages.add(packageName); 11644 continue; 11645 } 11646 pkgSetting.setSuspended(suspended, userId); 11647 mSettings.writePackageRestrictionsLPr(userId); 11648 changed = true; 11649 changedPackages.add(packageName); 11650 } 11651 } 11652 11653 if (changed && suspended) { 11654 killApplication(packageName, UserHandle.getUid(userId, appId), 11655 "suspending package"); 11656 } 11657 } 11658 } finally { 11659 Binder.restoreCallingIdentity(callingId); 11660 } 11661 11662 if (!changedPackages.isEmpty()) { 11663 sendPackagesSuspendedForUser(changedPackages.toArray( 11664 new String[changedPackages.size()]), userId, suspended); 11665 } 11666 11667 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 11668 } 11669 11670 @Override 11671 public boolean isPackageSuspendedForUser(String packageName, int userId) { 11672 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11673 true /* requireFullPermission */, false /* checkShell */, 11674 "isPackageSuspendedForUser for user " + userId); 11675 synchronized (mPackages) { 11676 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11677 if (pkgSetting == null) { 11678 throw new IllegalArgumentException("Unknown target package: " + packageName); 11679 } 11680 return pkgSetting.getSuspended(userId); 11681 } 11682 } 11683 11684 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 11685 if (isPackageDeviceAdmin(packageName, userId)) { 11686 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11687 + "\": has an active device admin"); 11688 return false; 11689 } 11690 11691 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 11692 if (packageName.equals(activeLauncherPackageName)) { 11693 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11694 + "\": contains the active launcher"); 11695 return false; 11696 } 11697 11698 if (packageName.equals(mRequiredInstallerPackage)) { 11699 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11700 + "\": required for package installation"); 11701 return false; 11702 } 11703 11704 if (packageName.equals(mRequiredVerifierPackage)) { 11705 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11706 + "\": required for package verification"); 11707 return false; 11708 } 11709 11710 if (packageName.equals(getDefaultDialerPackageName(userId))) { 11711 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11712 + "\": is the default dialer"); 11713 return false; 11714 } 11715 11716 return true; 11717 } 11718 11719 private String getActiveLauncherPackageName(int userId) { 11720 Intent intent = new Intent(Intent.ACTION_MAIN); 11721 intent.addCategory(Intent.CATEGORY_HOME); 11722 ResolveInfo resolveInfo = resolveIntent( 11723 intent, 11724 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 11725 PackageManager.MATCH_DEFAULT_ONLY, 11726 userId); 11727 11728 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 11729 } 11730 11731 private String getDefaultDialerPackageName(int userId) { 11732 synchronized (mPackages) { 11733 return mSettings.getDefaultDialerPackageNameLPw(userId); 11734 } 11735 } 11736 11737 @Override 11738 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 11739 mContext.enforceCallingOrSelfPermission( 11740 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11741 "Only package verification agents can verify applications"); 11742 11743 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11744 final PackageVerificationResponse response = new PackageVerificationResponse( 11745 verificationCode, Binder.getCallingUid()); 11746 msg.arg1 = id; 11747 msg.obj = response; 11748 mHandler.sendMessage(msg); 11749 } 11750 11751 @Override 11752 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 11753 long millisecondsToDelay) { 11754 mContext.enforceCallingOrSelfPermission( 11755 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11756 "Only package verification agents can extend verification timeouts"); 11757 11758 final PackageVerificationState state = mPendingVerification.get(id); 11759 final PackageVerificationResponse response = new PackageVerificationResponse( 11760 verificationCodeAtTimeout, Binder.getCallingUid()); 11761 11762 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 11763 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 11764 } 11765 if (millisecondsToDelay < 0) { 11766 millisecondsToDelay = 0; 11767 } 11768 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 11769 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 11770 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 11771 } 11772 11773 if ((state != null) && !state.timeoutExtended()) { 11774 state.extendTimeout(); 11775 11776 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11777 msg.arg1 = id; 11778 msg.obj = response; 11779 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 11780 } 11781 } 11782 11783 private void broadcastPackageVerified(int verificationId, Uri packageUri, 11784 int verificationCode, UserHandle user) { 11785 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 11786 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 11787 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11788 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11789 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 11790 11791 mContext.sendBroadcastAsUser(intent, user, 11792 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 11793 } 11794 11795 private ComponentName matchComponentForVerifier(String packageName, 11796 List<ResolveInfo> receivers) { 11797 ActivityInfo targetReceiver = null; 11798 11799 final int NR = receivers.size(); 11800 for (int i = 0; i < NR; i++) { 11801 final ResolveInfo info = receivers.get(i); 11802 if (info.activityInfo == null) { 11803 continue; 11804 } 11805 11806 if (packageName.equals(info.activityInfo.packageName)) { 11807 targetReceiver = info.activityInfo; 11808 break; 11809 } 11810 } 11811 11812 if (targetReceiver == null) { 11813 return null; 11814 } 11815 11816 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 11817 } 11818 11819 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 11820 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 11821 if (pkgInfo.verifiers.length == 0) { 11822 return null; 11823 } 11824 11825 final int N = pkgInfo.verifiers.length; 11826 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 11827 for (int i = 0; i < N; i++) { 11828 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 11829 11830 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 11831 receivers); 11832 if (comp == null) { 11833 continue; 11834 } 11835 11836 final int verifierUid = getUidForVerifier(verifierInfo); 11837 if (verifierUid == -1) { 11838 continue; 11839 } 11840 11841 if (DEBUG_VERIFY) { 11842 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 11843 + " with the correct signature"); 11844 } 11845 sufficientVerifiers.add(comp); 11846 verificationState.addSufficientVerifier(verifierUid); 11847 } 11848 11849 return sufficientVerifiers; 11850 } 11851 11852 private int getUidForVerifier(VerifierInfo verifierInfo) { 11853 synchronized (mPackages) { 11854 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 11855 if (pkg == null) { 11856 return -1; 11857 } else if (pkg.mSignatures.length != 1) { 11858 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11859 + " has more than one signature; ignoring"); 11860 return -1; 11861 } 11862 11863 /* 11864 * If the public key of the package's signature does not match 11865 * our expected public key, then this is a different package and 11866 * we should skip. 11867 */ 11868 11869 final byte[] expectedPublicKey; 11870 try { 11871 final Signature verifierSig = pkg.mSignatures[0]; 11872 final PublicKey publicKey = verifierSig.getPublicKey(); 11873 expectedPublicKey = publicKey.getEncoded(); 11874 } catch (CertificateException e) { 11875 return -1; 11876 } 11877 11878 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 11879 11880 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 11881 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11882 + " does not have the expected public key; ignoring"); 11883 return -1; 11884 } 11885 11886 return pkg.applicationInfo.uid; 11887 } 11888 } 11889 11890 @Override 11891 public void finishPackageInstall(int token, boolean didLaunch) { 11892 enforceSystemOrRoot("Only the system is allowed to finish installs"); 11893 11894 if (DEBUG_INSTALL) { 11895 Slog.v(TAG, "BM finishing package install for " + token); 11896 } 11897 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 11898 11899 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 11900 mHandler.sendMessage(msg); 11901 } 11902 11903 /** 11904 * Get the verification agent timeout. 11905 * 11906 * @return verification timeout in milliseconds 11907 */ 11908 private long getVerificationTimeout() { 11909 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 11910 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 11911 DEFAULT_VERIFICATION_TIMEOUT); 11912 } 11913 11914 /** 11915 * Get the default verification agent response code. 11916 * 11917 * @return default verification response code 11918 */ 11919 private int getDefaultVerificationResponse() { 11920 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11921 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 11922 DEFAULT_VERIFICATION_RESPONSE); 11923 } 11924 11925 /** 11926 * Check whether or not package verification has been enabled. 11927 * 11928 * @return true if verification should be performed 11929 */ 11930 private boolean isVerificationEnabled(int userId, int installFlags) { 11931 if (!DEFAULT_VERIFY_ENABLE) { 11932 return false; 11933 } 11934 // Ephemeral apps don't get the full verification treatment 11935 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11936 if (DEBUG_EPHEMERAL) { 11937 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 11938 } 11939 return false; 11940 } 11941 11942 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 11943 11944 // Check if installing from ADB 11945 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 11946 // Do not run verification in a test harness environment 11947 if (ActivityManager.isRunningInTestHarness()) { 11948 return false; 11949 } 11950 if (ensureVerifyAppsEnabled) { 11951 return true; 11952 } 11953 // Check if the developer does not want package verification for ADB installs 11954 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11955 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 11956 return false; 11957 } 11958 } 11959 11960 if (ensureVerifyAppsEnabled) { 11961 return true; 11962 } 11963 11964 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11965 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 11966 } 11967 11968 @Override 11969 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 11970 throws RemoteException { 11971 mContext.enforceCallingOrSelfPermission( 11972 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 11973 "Only intentfilter verification agents can verify applications"); 11974 11975 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 11976 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 11977 Binder.getCallingUid(), verificationCode, failedDomains); 11978 msg.arg1 = id; 11979 msg.obj = response; 11980 mHandler.sendMessage(msg); 11981 } 11982 11983 @Override 11984 public int getIntentVerificationStatus(String packageName, int userId) { 11985 synchronized (mPackages) { 11986 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 11987 } 11988 } 11989 11990 @Override 11991 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 11992 mContext.enforceCallingOrSelfPermission( 11993 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11994 11995 boolean result = false; 11996 synchronized (mPackages) { 11997 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 11998 } 11999 if (result) { 12000 scheduleWritePackageRestrictionsLocked(userId); 12001 } 12002 return result; 12003 } 12004 12005 @Override 12006 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 12007 String packageName) { 12008 synchronized (mPackages) { 12009 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 12010 } 12011 } 12012 12013 @Override 12014 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 12015 if (TextUtils.isEmpty(packageName)) { 12016 return ParceledListSlice.emptyList(); 12017 } 12018 synchronized (mPackages) { 12019 PackageParser.Package pkg = mPackages.get(packageName); 12020 if (pkg == null || pkg.activities == null) { 12021 return ParceledListSlice.emptyList(); 12022 } 12023 final int count = pkg.activities.size(); 12024 ArrayList<IntentFilter> result = new ArrayList<>(); 12025 for (int n=0; n<count; n++) { 12026 PackageParser.Activity activity = pkg.activities.get(n); 12027 if (activity.intents != null && activity.intents.size() > 0) { 12028 result.addAll(activity.intents); 12029 } 12030 } 12031 return new ParceledListSlice<>(result); 12032 } 12033 } 12034 12035 @Override 12036 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 12037 mContext.enforceCallingOrSelfPermission( 12038 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12039 12040 synchronized (mPackages) { 12041 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 12042 if (packageName != null) { 12043 result |= updateIntentVerificationStatus(packageName, 12044 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 12045 userId); 12046 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 12047 packageName, userId); 12048 } 12049 return result; 12050 } 12051 } 12052 12053 @Override 12054 public String getDefaultBrowserPackageName(int userId) { 12055 synchronized (mPackages) { 12056 return mSettings.getDefaultBrowserPackageNameLPw(userId); 12057 } 12058 } 12059 12060 /** 12061 * Get the "allow unknown sources" setting. 12062 * 12063 * @return the current "allow unknown sources" setting 12064 */ 12065 private int getUnknownSourcesSettings() { 12066 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 12067 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 12068 -1); 12069 } 12070 12071 @Override 12072 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 12073 final int uid = Binder.getCallingUid(); 12074 // writer 12075 synchronized (mPackages) { 12076 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 12077 if (targetPackageSetting == null) { 12078 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 12079 } 12080 12081 PackageSetting installerPackageSetting; 12082 if (installerPackageName != null) { 12083 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 12084 if (installerPackageSetting == null) { 12085 throw new IllegalArgumentException("Unknown installer package: " 12086 + installerPackageName); 12087 } 12088 } else { 12089 installerPackageSetting = null; 12090 } 12091 12092 Signature[] callerSignature; 12093 Object obj = mSettings.getUserIdLPr(uid); 12094 if (obj != null) { 12095 if (obj instanceof SharedUserSetting) { 12096 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 12097 } else if (obj instanceof PackageSetting) { 12098 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 12099 } else { 12100 throw new SecurityException("Bad object " + obj + " for uid " + uid); 12101 } 12102 } else { 12103 throw new SecurityException("Unknown calling UID: " + uid); 12104 } 12105 12106 // Verify: can't set installerPackageName to a package that is 12107 // not signed with the same cert as the caller. 12108 if (installerPackageSetting != null) { 12109 if (compareSignatures(callerSignature, 12110 installerPackageSetting.signatures.mSignatures) 12111 != PackageManager.SIGNATURE_MATCH) { 12112 throw new SecurityException( 12113 "Caller does not have same cert as new installer package " 12114 + installerPackageName); 12115 } 12116 } 12117 12118 // Verify: if target already has an installer package, it must 12119 // be signed with the same cert as the caller. 12120 if (targetPackageSetting.installerPackageName != null) { 12121 PackageSetting setting = mSettings.mPackages.get( 12122 targetPackageSetting.installerPackageName); 12123 // If the currently set package isn't valid, then it's always 12124 // okay to change it. 12125 if (setting != null) { 12126 if (compareSignatures(callerSignature, 12127 setting.signatures.mSignatures) 12128 != PackageManager.SIGNATURE_MATCH) { 12129 throw new SecurityException( 12130 "Caller does not have same cert as old installer package " 12131 + targetPackageSetting.installerPackageName); 12132 } 12133 } 12134 } 12135 12136 // Okay! 12137 targetPackageSetting.installerPackageName = installerPackageName; 12138 if (installerPackageName != null) { 12139 mSettings.mInstallerPackages.add(installerPackageName); 12140 } 12141 scheduleWriteSettingsLocked(); 12142 } 12143 } 12144 12145 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 12146 // Queue up an async operation since the package installation may take a little while. 12147 mHandler.post(new Runnable() { 12148 public void run() { 12149 mHandler.removeCallbacks(this); 12150 // Result object to be returned 12151 PackageInstalledInfo res = new PackageInstalledInfo(); 12152 res.setReturnCode(currentStatus); 12153 res.uid = -1; 12154 res.pkg = null; 12155 res.removedInfo = null; 12156 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12157 args.doPreInstall(res.returnCode); 12158 synchronized (mInstallLock) { 12159 installPackageTracedLI(args, res); 12160 } 12161 args.doPostInstall(res.returnCode, res.uid); 12162 } 12163 12164 // A restore should be performed at this point if (a) the install 12165 // succeeded, (b) the operation is not an update, and (c) the new 12166 // package has not opted out of backup participation. 12167 final boolean update = res.removedInfo != null 12168 && res.removedInfo.removedPackage != null; 12169 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 12170 boolean doRestore = !update 12171 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 12172 12173 // Set up the post-install work request bookkeeping. This will be used 12174 // and cleaned up by the post-install event handling regardless of whether 12175 // there's a restore pass performed. Token values are >= 1. 12176 int token; 12177 if (mNextInstallToken < 0) mNextInstallToken = 1; 12178 token = mNextInstallToken++; 12179 12180 PostInstallData data = new PostInstallData(args, res); 12181 mRunningInstalls.put(token, data); 12182 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 12183 12184 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 12185 // Pass responsibility to the Backup Manager. It will perform a 12186 // restore if appropriate, then pass responsibility back to the 12187 // Package Manager to run the post-install observer callbacks 12188 // and broadcasts. 12189 IBackupManager bm = IBackupManager.Stub.asInterface( 12190 ServiceManager.getService(Context.BACKUP_SERVICE)); 12191 if (bm != null) { 12192 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 12193 + " to BM for possible restore"); 12194 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12195 try { 12196 // TODO: http://b/22388012 12197 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 12198 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 12199 } else { 12200 doRestore = false; 12201 } 12202 } catch (RemoteException e) { 12203 // can't happen; the backup manager is local 12204 } catch (Exception e) { 12205 Slog.e(TAG, "Exception trying to enqueue restore", e); 12206 doRestore = false; 12207 } 12208 } else { 12209 Slog.e(TAG, "Backup Manager not found!"); 12210 doRestore = false; 12211 } 12212 } 12213 12214 if (!doRestore) { 12215 // No restore possible, or the Backup Manager was mysteriously not 12216 // available -- just fire the post-install work request directly. 12217 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 12218 12219 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 12220 12221 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 12222 mHandler.sendMessage(msg); 12223 } 12224 } 12225 }); 12226 } 12227 12228 /** 12229 * Callback from PackageSettings whenever an app is first transitioned out of the 12230 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 12231 * the app was "launched" for a restoreAtInstall operation. Therefore we check 12232 * here whether the app is the target of an ongoing install, and only send the 12233 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 12234 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 12235 * handling. 12236 */ 12237 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 12238 // Serialize this with the rest of the install-process message chain. In the 12239 // restore-at-install case, this Runnable will necessarily run before the 12240 // POST_INSTALL message is processed, so the contents of mRunningInstalls 12241 // are coherent. In the non-restore case, the app has already completed install 12242 // and been launched through some other means, so it is not in a problematic 12243 // state for observers to see the FIRST_LAUNCH signal. 12244 mHandler.post(new Runnable() { 12245 @Override 12246 public void run() { 12247 for (int i = 0; i < mRunningInstalls.size(); i++) { 12248 final PostInstallData data = mRunningInstalls.valueAt(i); 12249 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 12250 // right package; but is it for the right user? 12251 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 12252 if (userId == data.res.newUsers[uIndex]) { 12253 if (DEBUG_BACKUP) { 12254 Slog.i(TAG, "Package " + pkgName 12255 + " being restored so deferring FIRST_LAUNCH"); 12256 } 12257 return; 12258 } 12259 } 12260 } 12261 } 12262 // didn't find it, so not being restored 12263 if (DEBUG_BACKUP) { 12264 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 12265 } 12266 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 12267 } 12268 }); 12269 } 12270 12271 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 12272 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 12273 installerPkg, null, userIds); 12274 } 12275 12276 private abstract class HandlerParams { 12277 private static final int MAX_RETRIES = 4; 12278 12279 /** 12280 * Number of times startCopy() has been attempted and had a non-fatal 12281 * error. 12282 */ 12283 private int mRetries = 0; 12284 12285 /** User handle for the user requesting the information or installation. */ 12286 private final UserHandle mUser; 12287 String traceMethod; 12288 int traceCookie; 12289 12290 HandlerParams(UserHandle user) { 12291 mUser = user; 12292 } 12293 12294 UserHandle getUser() { 12295 return mUser; 12296 } 12297 12298 HandlerParams setTraceMethod(String traceMethod) { 12299 this.traceMethod = traceMethod; 12300 return this; 12301 } 12302 12303 HandlerParams setTraceCookie(int traceCookie) { 12304 this.traceCookie = traceCookie; 12305 return this; 12306 } 12307 12308 final boolean startCopy() { 12309 boolean res; 12310 try { 12311 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 12312 12313 if (++mRetries > MAX_RETRIES) { 12314 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 12315 mHandler.sendEmptyMessage(MCS_GIVE_UP); 12316 handleServiceError(); 12317 return false; 12318 } else { 12319 handleStartCopy(); 12320 res = true; 12321 } 12322 } catch (RemoteException e) { 12323 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 12324 mHandler.sendEmptyMessage(MCS_RECONNECT); 12325 res = false; 12326 } 12327 handleReturnCode(); 12328 return res; 12329 } 12330 12331 final void serviceError() { 12332 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 12333 handleServiceError(); 12334 handleReturnCode(); 12335 } 12336 12337 abstract void handleStartCopy() throws RemoteException; 12338 abstract void handleServiceError(); 12339 abstract void handleReturnCode(); 12340 } 12341 12342 class MeasureParams extends HandlerParams { 12343 private final PackageStats mStats; 12344 private boolean mSuccess; 12345 12346 private final IPackageStatsObserver mObserver; 12347 12348 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 12349 super(new UserHandle(stats.userHandle)); 12350 mObserver = observer; 12351 mStats = stats; 12352 } 12353 12354 @Override 12355 public String toString() { 12356 return "MeasureParams{" 12357 + Integer.toHexString(System.identityHashCode(this)) 12358 + " " + mStats.packageName + "}"; 12359 } 12360 12361 @Override 12362 void handleStartCopy() throws RemoteException { 12363 synchronized (mInstallLock) { 12364 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 12365 } 12366 12367 if (mSuccess) { 12368 final boolean mounted; 12369 if (Environment.isExternalStorageEmulated()) { 12370 mounted = true; 12371 } else { 12372 final String status = Environment.getExternalStorageState(); 12373 mounted = (Environment.MEDIA_MOUNTED.equals(status) 12374 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 12375 } 12376 12377 if (mounted) { 12378 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 12379 12380 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 12381 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 12382 12383 mStats.externalDataSize = calculateDirectorySize(mContainerService, 12384 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 12385 12386 // Always subtract cache size, since it's a subdirectory 12387 mStats.externalDataSize -= mStats.externalCacheSize; 12388 12389 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 12390 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 12391 12392 mStats.externalObbSize = calculateDirectorySize(mContainerService, 12393 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 12394 } 12395 } 12396 } 12397 12398 @Override 12399 void handleReturnCode() { 12400 if (mObserver != null) { 12401 try { 12402 mObserver.onGetStatsCompleted(mStats, mSuccess); 12403 } catch (RemoteException e) { 12404 Slog.i(TAG, "Observer no longer exists."); 12405 } 12406 } 12407 } 12408 12409 @Override 12410 void handleServiceError() { 12411 Slog.e(TAG, "Could not measure application " + mStats.packageName 12412 + " external storage"); 12413 } 12414 } 12415 12416 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 12417 throws RemoteException { 12418 long result = 0; 12419 for (File path : paths) { 12420 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 12421 } 12422 return result; 12423 } 12424 12425 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 12426 for (File path : paths) { 12427 try { 12428 mcs.clearDirectory(path.getAbsolutePath()); 12429 } catch (RemoteException e) { 12430 } 12431 } 12432 } 12433 12434 static class OriginInfo { 12435 /** 12436 * Location where install is coming from, before it has been 12437 * copied/renamed into place. This could be a single monolithic APK 12438 * file, or a cluster directory. This location may be untrusted. 12439 */ 12440 final File file; 12441 final String cid; 12442 12443 /** 12444 * Flag indicating that {@link #file} or {@link #cid} has already been 12445 * staged, meaning downstream users don't need to defensively copy the 12446 * contents. 12447 */ 12448 final boolean staged; 12449 12450 /** 12451 * Flag indicating that {@link #file} or {@link #cid} is an already 12452 * installed app that is being moved. 12453 */ 12454 final boolean existing; 12455 12456 final String resolvedPath; 12457 final File resolvedFile; 12458 12459 static OriginInfo fromNothing() { 12460 return new OriginInfo(null, null, false, false); 12461 } 12462 12463 static OriginInfo fromUntrustedFile(File file) { 12464 return new OriginInfo(file, null, false, false); 12465 } 12466 12467 static OriginInfo fromExistingFile(File file) { 12468 return new OriginInfo(file, null, false, true); 12469 } 12470 12471 static OriginInfo fromStagedFile(File file) { 12472 return new OriginInfo(file, null, true, false); 12473 } 12474 12475 static OriginInfo fromStagedContainer(String cid) { 12476 return new OriginInfo(null, cid, true, false); 12477 } 12478 12479 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 12480 this.file = file; 12481 this.cid = cid; 12482 this.staged = staged; 12483 this.existing = existing; 12484 12485 if (cid != null) { 12486 resolvedPath = PackageHelper.getSdDir(cid); 12487 resolvedFile = new File(resolvedPath); 12488 } else if (file != null) { 12489 resolvedPath = file.getAbsolutePath(); 12490 resolvedFile = file; 12491 } else { 12492 resolvedPath = null; 12493 resolvedFile = null; 12494 } 12495 } 12496 } 12497 12498 static class MoveInfo { 12499 final int moveId; 12500 final String fromUuid; 12501 final String toUuid; 12502 final String packageName; 12503 final String dataAppName; 12504 final int appId; 12505 final String seinfo; 12506 final int targetSdkVersion; 12507 12508 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 12509 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 12510 this.moveId = moveId; 12511 this.fromUuid = fromUuid; 12512 this.toUuid = toUuid; 12513 this.packageName = packageName; 12514 this.dataAppName = dataAppName; 12515 this.appId = appId; 12516 this.seinfo = seinfo; 12517 this.targetSdkVersion = targetSdkVersion; 12518 } 12519 } 12520 12521 static class VerificationInfo { 12522 /** A constant used to indicate that a uid value is not present. */ 12523 public static final int NO_UID = -1; 12524 12525 /** URI referencing where the package was downloaded from. */ 12526 final Uri originatingUri; 12527 12528 /** HTTP referrer URI associated with the originatingURI. */ 12529 final Uri referrer; 12530 12531 /** UID of the application that the install request originated from. */ 12532 final int originatingUid; 12533 12534 /** UID of application requesting the install */ 12535 final int installerUid; 12536 12537 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 12538 this.originatingUri = originatingUri; 12539 this.referrer = referrer; 12540 this.originatingUid = originatingUid; 12541 this.installerUid = installerUid; 12542 } 12543 } 12544 12545 class InstallParams extends HandlerParams { 12546 final OriginInfo origin; 12547 final MoveInfo move; 12548 final IPackageInstallObserver2 observer; 12549 int installFlags; 12550 final String installerPackageName; 12551 final String volumeUuid; 12552 private InstallArgs mArgs; 12553 private int mRet; 12554 final String packageAbiOverride; 12555 final String[] grantedRuntimePermissions; 12556 final VerificationInfo verificationInfo; 12557 final Certificate[][] certificates; 12558 12559 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12560 int installFlags, String installerPackageName, String volumeUuid, 12561 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 12562 String[] grantedPermissions, Certificate[][] certificates) { 12563 super(user); 12564 this.origin = origin; 12565 this.move = move; 12566 this.observer = observer; 12567 this.installFlags = installFlags; 12568 this.installerPackageName = installerPackageName; 12569 this.volumeUuid = volumeUuid; 12570 this.verificationInfo = verificationInfo; 12571 this.packageAbiOverride = packageAbiOverride; 12572 this.grantedRuntimePermissions = grantedPermissions; 12573 this.certificates = certificates; 12574 } 12575 12576 @Override 12577 public String toString() { 12578 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 12579 + " file=" + origin.file + " cid=" + origin.cid + "}"; 12580 } 12581 12582 private int installLocationPolicy(PackageInfoLite pkgLite) { 12583 String packageName = pkgLite.packageName; 12584 int installLocation = pkgLite.installLocation; 12585 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12586 // reader 12587 synchronized (mPackages) { 12588 // Currently installed package which the new package is attempting to replace or 12589 // null if no such package is installed. 12590 PackageParser.Package installedPkg = mPackages.get(packageName); 12591 // Package which currently owns the data which the new package will own if installed. 12592 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 12593 // will be null whereas dataOwnerPkg will contain information about the package 12594 // which was uninstalled while keeping its data. 12595 PackageParser.Package dataOwnerPkg = installedPkg; 12596 if (dataOwnerPkg == null) { 12597 PackageSetting ps = mSettings.mPackages.get(packageName); 12598 if (ps != null) { 12599 dataOwnerPkg = ps.pkg; 12600 } 12601 } 12602 12603 if (dataOwnerPkg != null) { 12604 // If installed, the package will get access to data left on the device by its 12605 // predecessor. As a security measure, this is permited only if this is not a 12606 // version downgrade or if the predecessor package is marked as debuggable and 12607 // a downgrade is explicitly requested. 12608 // 12609 // On debuggable platform builds, downgrades are permitted even for 12610 // non-debuggable packages to make testing easier. Debuggable platform builds do 12611 // not offer security guarantees and thus it's OK to disable some security 12612 // mechanisms to make debugging/testing easier on those builds. However, even on 12613 // debuggable builds downgrades of packages are permitted only if requested via 12614 // installFlags. This is because we aim to keep the behavior of debuggable 12615 // platform builds as close as possible to the behavior of non-debuggable 12616 // platform builds. 12617 final boolean downgradeRequested = 12618 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 12619 final boolean packageDebuggable = 12620 (dataOwnerPkg.applicationInfo.flags 12621 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 12622 final boolean downgradePermitted = 12623 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 12624 if (!downgradePermitted) { 12625 try { 12626 checkDowngrade(dataOwnerPkg, pkgLite); 12627 } catch (PackageManagerException e) { 12628 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 12629 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 12630 } 12631 } 12632 } 12633 12634 if (installedPkg != null) { 12635 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12636 // Check for updated system application. 12637 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 12638 if (onSd) { 12639 Slog.w(TAG, "Cannot install update to system app on sdcard"); 12640 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 12641 } 12642 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12643 } else { 12644 if (onSd) { 12645 // Install flag overrides everything. 12646 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12647 } 12648 // If current upgrade specifies particular preference 12649 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 12650 // Application explicitly specified internal. 12651 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12652 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 12653 // App explictly prefers external. Let policy decide 12654 } else { 12655 // Prefer previous location 12656 if (isExternal(installedPkg)) { 12657 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12658 } 12659 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12660 } 12661 } 12662 } else { 12663 // Invalid install. Return error code 12664 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 12665 } 12666 } 12667 } 12668 // All the special cases have been taken care of. 12669 // Return result based on recommended install location. 12670 if (onSd) { 12671 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12672 } 12673 return pkgLite.recommendedInstallLocation; 12674 } 12675 12676 /* 12677 * Invoke remote method to get package information and install 12678 * location values. Override install location based on default 12679 * policy if needed and then create install arguments based 12680 * on the install location. 12681 */ 12682 public void handleStartCopy() throws RemoteException { 12683 int ret = PackageManager.INSTALL_SUCCEEDED; 12684 12685 // If we're already staged, we've firmly committed to an install location 12686 if (origin.staged) { 12687 if (origin.file != null) { 12688 installFlags |= PackageManager.INSTALL_INTERNAL; 12689 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12690 } else if (origin.cid != null) { 12691 installFlags |= PackageManager.INSTALL_EXTERNAL; 12692 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12693 } else { 12694 throw new IllegalStateException("Invalid stage location"); 12695 } 12696 } 12697 12698 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12699 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 12700 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12701 PackageInfoLite pkgLite = null; 12702 12703 if (onInt && onSd) { 12704 // Check if both bits are set. 12705 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 12706 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12707 } else if (onSd && ephemeral) { 12708 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 12709 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12710 } else { 12711 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 12712 packageAbiOverride); 12713 12714 if (DEBUG_EPHEMERAL && ephemeral) { 12715 Slog.v(TAG, "pkgLite for install: " + pkgLite); 12716 } 12717 12718 /* 12719 * If we have too little free space, try to free cache 12720 * before giving up. 12721 */ 12722 if (!origin.staged && pkgLite.recommendedInstallLocation 12723 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12724 // TODO: focus freeing disk space on the target device 12725 final StorageManager storage = StorageManager.from(mContext); 12726 final long lowThreshold = storage.getStorageLowBytes( 12727 Environment.getDataDirectory()); 12728 12729 final long sizeBytes = mContainerService.calculateInstalledSize( 12730 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 12731 12732 try { 12733 mInstaller.freeCache(null, sizeBytes + lowThreshold); 12734 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 12735 installFlags, packageAbiOverride); 12736 } catch (InstallerException e) { 12737 Slog.w(TAG, "Failed to free cache", e); 12738 } 12739 12740 /* 12741 * The cache free must have deleted the file we 12742 * downloaded to install. 12743 * 12744 * TODO: fix the "freeCache" call to not delete 12745 * the file we care about. 12746 */ 12747 if (pkgLite.recommendedInstallLocation 12748 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12749 pkgLite.recommendedInstallLocation 12750 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 12751 } 12752 } 12753 } 12754 12755 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12756 int loc = pkgLite.recommendedInstallLocation; 12757 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 12758 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12759 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 12760 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 12761 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12762 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12763 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 12764 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 12765 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12766 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 12767 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 12768 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 12769 } else { 12770 // Override with defaults if needed. 12771 loc = installLocationPolicy(pkgLite); 12772 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 12773 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 12774 } else if (!onSd && !onInt) { 12775 // Override install location with flags 12776 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 12777 // Set the flag to install on external media. 12778 installFlags |= PackageManager.INSTALL_EXTERNAL; 12779 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12780 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 12781 if (DEBUG_EPHEMERAL) { 12782 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 12783 } 12784 installFlags |= PackageManager.INSTALL_EPHEMERAL; 12785 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 12786 |PackageManager.INSTALL_INTERNAL); 12787 } else { 12788 // Make sure the flag for installing on external 12789 // media is unset 12790 installFlags |= PackageManager.INSTALL_INTERNAL; 12791 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12792 } 12793 } 12794 } 12795 } 12796 12797 final InstallArgs args = createInstallArgs(this); 12798 mArgs = args; 12799 12800 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12801 // TODO: http://b/22976637 12802 // Apps installed for "all" users use the device owner to verify the app 12803 UserHandle verifierUser = getUser(); 12804 if (verifierUser == UserHandle.ALL) { 12805 verifierUser = UserHandle.SYSTEM; 12806 } 12807 12808 /* 12809 * Determine if we have any installed package verifiers. If we 12810 * do, then we'll defer to them to verify the packages. 12811 */ 12812 final int requiredUid = mRequiredVerifierPackage == null ? -1 12813 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 12814 verifierUser.getIdentifier()); 12815 if (!origin.existing && requiredUid != -1 12816 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 12817 final Intent verification = new Intent( 12818 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 12819 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 12820 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 12821 PACKAGE_MIME_TYPE); 12822 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 12823 12824 // Query all live verifiers based on current user state 12825 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 12826 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 12827 12828 if (DEBUG_VERIFY) { 12829 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 12830 + verification.toString() + " with " + pkgLite.verifiers.length 12831 + " optional verifiers"); 12832 } 12833 12834 final int verificationId = mPendingVerificationToken++; 12835 12836 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 12837 12838 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 12839 installerPackageName); 12840 12841 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 12842 installFlags); 12843 12844 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 12845 pkgLite.packageName); 12846 12847 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 12848 pkgLite.versionCode); 12849 12850 if (verificationInfo != null) { 12851 if (verificationInfo.originatingUri != null) { 12852 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 12853 verificationInfo.originatingUri); 12854 } 12855 if (verificationInfo.referrer != null) { 12856 verification.putExtra(Intent.EXTRA_REFERRER, 12857 verificationInfo.referrer); 12858 } 12859 if (verificationInfo.originatingUid >= 0) { 12860 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 12861 verificationInfo.originatingUid); 12862 } 12863 if (verificationInfo.installerUid >= 0) { 12864 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 12865 verificationInfo.installerUid); 12866 } 12867 } 12868 12869 final PackageVerificationState verificationState = new PackageVerificationState( 12870 requiredUid, args); 12871 12872 mPendingVerification.append(verificationId, verificationState); 12873 12874 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 12875 receivers, verificationState); 12876 12877 /* 12878 * If any sufficient verifiers were listed in the package 12879 * manifest, attempt to ask them. 12880 */ 12881 if (sufficientVerifiers != null) { 12882 final int N = sufficientVerifiers.size(); 12883 if (N == 0) { 12884 Slog.i(TAG, "Additional verifiers required, but none installed."); 12885 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 12886 } else { 12887 for (int i = 0; i < N; i++) { 12888 final ComponentName verifierComponent = sufficientVerifiers.get(i); 12889 12890 final Intent sufficientIntent = new Intent(verification); 12891 sufficientIntent.setComponent(verifierComponent); 12892 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 12893 } 12894 } 12895 } 12896 12897 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 12898 mRequiredVerifierPackage, receivers); 12899 if (ret == PackageManager.INSTALL_SUCCEEDED 12900 && mRequiredVerifierPackage != null) { 12901 Trace.asyncTraceBegin( 12902 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 12903 /* 12904 * Send the intent to the required verification agent, 12905 * but only start the verification timeout after the 12906 * target BroadcastReceivers have run. 12907 */ 12908 verification.setComponent(requiredVerifierComponent); 12909 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 12910 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12911 new BroadcastReceiver() { 12912 @Override 12913 public void onReceive(Context context, Intent intent) { 12914 final Message msg = mHandler 12915 .obtainMessage(CHECK_PENDING_VERIFICATION); 12916 msg.arg1 = verificationId; 12917 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 12918 } 12919 }, null, 0, null, null); 12920 12921 /* 12922 * We don't want the copy to proceed until verification 12923 * succeeds, so null out this field. 12924 */ 12925 mArgs = null; 12926 } 12927 } else { 12928 /* 12929 * No package verification is enabled, so immediately start 12930 * the remote call to initiate copy using temporary file. 12931 */ 12932 ret = args.copyApk(mContainerService, true); 12933 } 12934 } 12935 12936 mRet = ret; 12937 } 12938 12939 @Override 12940 void handleReturnCode() { 12941 // If mArgs is null, then MCS couldn't be reached. When it 12942 // reconnects, it will try again to install. At that point, this 12943 // will succeed. 12944 if (mArgs != null) { 12945 processPendingInstall(mArgs, mRet); 12946 } 12947 } 12948 12949 @Override 12950 void handleServiceError() { 12951 mArgs = createInstallArgs(this); 12952 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12953 } 12954 12955 public boolean isForwardLocked() { 12956 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12957 } 12958 } 12959 12960 /** 12961 * Used during creation of InstallArgs 12962 * 12963 * @param installFlags package installation flags 12964 * @return true if should be installed on external storage 12965 */ 12966 private static boolean installOnExternalAsec(int installFlags) { 12967 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 12968 return false; 12969 } 12970 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 12971 return true; 12972 } 12973 return false; 12974 } 12975 12976 /** 12977 * Used during creation of InstallArgs 12978 * 12979 * @param installFlags package installation flags 12980 * @return true if should be installed as forward locked 12981 */ 12982 private static boolean installForwardLocked(int installFlags) { 12983 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12984 } 12985 12986 private InstallArgs createInstallArgs(InstallParams params) { 12987 if (params.move != null) { 12988 return new MoveInstallArgs(params); 12989 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 12990 return new AsecInstallArgs(params); 12991 } else { 12992 return new FileInstallArgs(params); 12993 } 12994 } 12995 12996 /** 12997 * Create args that describe an existing installed package. Typically used 12998 * when cleaning up old installs, or used as a move source. 12999 */ 13000 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 13001 String resourcePath, String[] instructionSets) { 13002 final boolean isInAsec; 13003 if (installOnExternalAsec(installFlags)) { 13004 /* Apps on SD card are always in ASEC containers. */ 13005 isInAsec = true; 13006 } else if (installForwardLocked(installFlags) 13007 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 13008 /* 13009 * Forward-locked apps are only in ASEC containers if they're the 13010 * new style 13011 */ 13012 isInAsec = true; 13013 } else { 13014 isInAsec = false; 13015 } 13016 13017 if (isInAsec) { 13018 return new AsecInstallArgs(codePath, instructionSets, 13019 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 13020 } else { 13021 return new FileInstallArgs(codePath, resourcePath, instructionSets); 13022 } 13023 } 13024 13025 static abstract class InstallArgs { 13026 /** @see InstallParams#origin */ 13027 final OriginInfo origin; 13028 /** @see InstallParams#move */ 13029 final MoveInfo move; 13030 13031 final IPackageInstallObserver2 observer; 13032 // Always refers to PackageManager flags only 13033 final int installFlags; 13034 final String installerPackageName; 13035 final String volumeUuid; 13036 final UserHandle user; 13037 final String abiOverride; 13038 final String[] installGrantPermissions; 13039 /** If non-null, drop an async trace when the install completes */ 13040 final String traceMethod; 13041 final int traceCookie; 13042 final Certificate[][] certificates; 13043 13044 // The list of instruction sets supported by this app. This is currently 13045 // only used during the rmdex() phase to clean up resources. We can get rid of this 13046 // if we move dex files under the common app path. 13047 /* nullable */ String[] instructionSets; 13048 13049 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 13050 int installFlags, String installerPackageName, String volumeUuid, 13051 UserHandle user, String[] instructionSets, 13052 String abiOverride, String[] installGrantPermissions, 13053 String traceMethod, int traceCookie, Certificate[][] certificates) { 13054 this.origin = origin; 13055 this.move = move; 13056 this.installFlags = installFlags; 13057 this.observer = observer; 13058 this.installerPackageName = installerPackageName; 13059 this.volumeUuid = volumeUuid; 13060 this.user = user; 13061 this.instructionSets = instructionSets; 13062 this.abiOverride = abiOverride; 13063 this.installGrantPermissions = installGrantPermissions; 13064 this.traceMethod = traceMethod; 13065 this.traceCookie = traceCookie; 13066 this.certificates = certificates; 13067 } 13068 13069 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 13070 abstract int doPreInstall(int status); 13071 13072 /** 13073 * Rename package into final resting place. All paths on the given 13074 * scanned package should be updated to reflect the rename. 13075 */ 13076 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 13077 abstract int doPostInstall(int status, int uid); 13078 13079 /** @see PackageSettingBase#codePathString */ 13080 abstract String getCodePath(); 13081 /** @see PackageSettingBase#resourcePathString */ 13082 abstract String getResourcePath(); 13083 13084 // Need installer lock especially for dex file removal. 13085 abstract void cleanUpResourcesLI(); 13086 abstract boolean doPostDeleteLI(boolean delete); 13087 13088 /** 13089 * Called before the source arguments are copied. This is used mostly 13090 * for MoveParams when it needs to read the source file to put it in the 13091 * destination. 13092 */ 13093 int doPreCopy() { 13094 return PackageManager.INSTALL_SUCCEEDED; 13095 } 13096 13097 /** 13098 * Called after the source arguments are copied. This is used mostly for 13099 * MoveParams when it needs to read the source file to put it in the 13100 * destination. 13101 */ 13102 int doPostCopy(int uid) { 13103 return PackageManager.INSTALL_SUCCEEDED; 13104 } 13105 13106 protected boolean isFwdLocked() { 13107 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13108 } 13109 13110 protected boolean isExternalAsec() { 13111 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 13112 } 13113 13114 protected boolean isEphemeral() { 13115 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13116 } 13117 13118 UserHandle getUser() { 13119 return user; 13120 } 13121 } 13122 13123 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 13124 if (!allCodePaths.isEmpty()) { 13125 if (instructionSets == null) { 13126 throw new IllegalStateException("instructionSet == null"); 13127 } 13128 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 13129 for (String codePath : allCodePaths) { 13130 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 13131 try { 13132 mInstaller.rmdex(codePath, dexCodeInstructionSet); 13133 } catch (InstallerException ignored) { 13134 } 13135 } 13136 } 13137 } 13138 } 13139 13140 /** 13141 * Logic to handle installation of non-ASEC applications, including copying 13142 * and renaming logic. 13143 */ 13144 class FileInstallArgs extends InstallArgs { 13145 private File codeFile; 13146 private File resourceFile; 13147 13148 // Example topology: 13149 // /data/app/com.example/base.apk 13150 // /data/app/com.example/split_foo.apk 13151 // /data/app/com.example/lib/arm/libfoo.so 13152 // /data/app/com.example/lib/arm64/libfoo.so 13153 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 13154 13155 /** New install */ 13156 FileInstallArgs(InstallParams params) { 13157 super(params.origin, params.move, params.observer, params.installFlags, 13158 params.installerPackageName, params.volumeUuid, 13159 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 13160 params.grantedRuntimePermissions, 13161 params.traceMethod, params.traceCookie, params.certificates); 13162 if (isFwdLocked()) { 13163 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 13164 } 13165 } 13166 13167 /** Existing install */ 13168 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 13169 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 13170 null, null, null, 0, null /*certificates*/); 13171 this.codeFile = (codePath != null) ? new File(codePath) : null; 13172 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 13173 } 13174 13175 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13176 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 13177 try { 13178 return doCopyApk(imcs, temp); 13179 } finally { 13180 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13181 } 13182 } 13183 13184 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13185 if (origin.staged) { 13186 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 13187 codeFile = origin.file; 13188 resourceFile = origin.file; 13189 return PackageManager.INSTALL_SUCCEEDED; 13190 } 13191 13192 try { 13193 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13194 final File tempDir = 13195 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 13196 codeFile = tempDir; 13197 resourceFile = tempDir; 13198 } catch (IOException e) { 13199 Slog.w(TAG, "Failed to create copy file: " + e); 13200 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 13201 } 13202 13203 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 13204 @Override 13205 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 13206 if (!FileUtils.isValidExtFilename(name)) { 13207 throw new IllegalArgumentException("Invalid filename: " + name); 13208 } 13209 try { 13210 final File file = new File(codeFile, name); 13211 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 13212 O_RDWR | O_CREAT, 0644); 13213 Os.chmod(file.getAbsolutePath(), 0644); 13214 return new ParcelFileDescriptor(fd); 13215 } catch (ErrnoException e) { 13216 throw new RemoteException("Failed to open: " + e.getMessage()); 13217 } 13218 } 13219 }; 13220 13221 int ret = PackageManager.INSTALL_SUCCEEDED; 13222 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 13223 if (ret != PackageManager.INSTALL_SUCCEEDED) { 13224 Slog.e(TAG, "Failed to copy package"); 13225 return ret; 13226 } 13227 13228 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 13229 NativeLibraryHelper.Handle handle = null; 13230 try { 13231 handle = NativeLibraryHelper.Handle.create(codeFile); 13232 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 13233 abiOverride); 13234 } catch (IOException e) { 13235 Slog.e(TAG, "Copying native libraries failed", e); 13236 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13237 } finally { 13238 IoUtils.closeQuietly(handle); 13239 } 13240 13241 return ret; 13242 } 13243 13244 int doPreInstall(int status) { 13245 if (status != PackageManager.INSTALL_SUCCEEDED) { 13246 cleanUp(); 13247 } 13248 return status; 13249 } 13250 13251 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13252 if (status != PackageManager.INSTALL_SUCCEEDED) { 13253 cleanUp(); 13254 return false; 13255 } 13256 13257 final File targetDir = codeFile.getParentFile(); 13258 final File beforeCodeFile = codeFile; 13259 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 13260 13261 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 13262 try { 13263 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 13264 } catch (ErrnoException e) { 13265 Slog.w(TAG, "Failed to rename", e); 13266 return false; 13267 } 13268 13269 if (!SELinux.restoreconRecursive(afterCodeFile)) { 13270 Slog.w(TAG, "Failed to restorecon"); 13271 return false; 13272 } 13273 13274 // Reflect the rename internally 13275 codeFile = afterCodeFile; 13276 resourceFile = afterCodeFile; 13277 13278 // Reflect the rename in scanned details 13279 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13280 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13281 afterCodeFile, pkg.baseCodePath)); 13282 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13283 afterCodeFile, pkg.splitCodePaths)); 13284 13285 // Reflect the rename in app info 13286 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13287 pkg.setApplicationInfoCodePath(pkg.codePath); 13288 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13289 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13290 pkg.setApplicationInfoResourcePath(pkg.codePath); 13291 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13292 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13293 13294 return true; 13295 } 13296 13297 int doPostInstall(int status, int uid) { 13298 if (status != PackageManager.INSTALL_SUCCEEDED) { 13299 cleanUp(); 13300 } 13301 return status; 13302 } 13303 13304 @Override 13305 String getCodePath() { 13306 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13307 } 13308 13309 @Override 13310 String getResourcePath() { 13311 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13312 } 13313 13314 private boolean cleanUp() { 13315 if (codeFile == null || !codeFile.exists()) { 13316 return false; 13317 } 13318 13319 removeCodePathLI(codeFile); 13320 13321 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 13322 resourceFile.delete(); 13323 } 13324 13325 return true; 13326 } 13327 13328 void cleanUpResourcesLI() { 13329 // Try enumerating all code paths before deleting 13330 List<String> allCodePaths = Collections.EMPTY_LIST; 13331 if (codeFile != null && codeFile.exists()) { 13332 try { 13333 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13334 allCodePaths = pkg.getAllCodePaths(); 13335 } catch (PackageParserException e) { 13336 // Ignored; we tried our best 13337 } 13338 } 13339 13340 cleanUp(); 13341 removeDexFiles(allCodePaths, instructionSets); 13342 } 13343 13344 boolean doPostDeleteLI(boolean delete) { 13345 // XXX err, shouldn't we respect the delete flag? 13346 cleanUpResourcesLI(); 13347 return true; 13348 } 13349 } 13350 13351 private boolean isAsecExternal(String cid) { 13352 final String asecPath = PackageHelper.getSdFilesystem(cid); 13353 return !asecPath.startsWith(mAsecInternalPath); 13354 } 13355 13356 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 13357 PackageManagerException { 13358 if (copyRet < 0) { 13359 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 13360 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 13361 throw new PackageManagerException(copyRet, message); 13362 } 13363 } 13364 } 13365 13366 /** 13367 * Extract the MountService "container ID" from the full code path of an 13368 * .apk. 13369 */ 13370 static String cidFromCodePath(String fullCodePath) { 13371 int eidx = fullCodePath.lastIndexOf("/"); 13372 String subStr1 = fullCodePath.substring(0, eidx); 13373 int sidx = subStr1.lastIndexOf("/"); 13374 return subStr1.substring(sidx+1, eidx); 13375 } 13376 13377 /** 13378 * Logic to handle installation of ASEC applications, including copying and 13379 * renaming logic. 13380 */ 13381 class AsecInstallArgs extends InstallArgs { 13382 static final String RES_FILE_NAME = "pkg.apk"; 13383 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 13384 13385 String cid; 13386 String packagePath; 13387 String resourcePath; 13388 13389 /** New install */ 13390 AsecInstallArgs(InstallParams params) { 13391 super(params.origin, params.move, params.observer, params.installFlags, 13392 params.installerPackageName, params.volumeUuid, 13393 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13394 params.grantedRuntimePermissions, 13395 params.traceMethod, params.traceCookie, params.certificates); 13396 } 13397 13398 /** Existing install */ 13399 AsecInstallArgs(String fullCodePath, String[] instructionSets, 13400 boolean isExternal, boolean isForwardLocked) { 13401 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 13402 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13403 instructionSets, null, null, null, 0, null /*certificates*/); 13404 // Hackily pretend we're still looking at a full code path 13405 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 13406 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 13407 } 13408 13409 // Extract cid from fullCodePath 13410 int eidx = fullCodePath.lastIndexOf("/"); 13411 String subStr1 = fullCodePath.substring(0, eidx); 13412 int sidx = subStr1.lastIndexOf("/"); 13413 cid = subStr1.substring(sidx+1, eidx); 13414 setMountPath(subStr1); 13415 } 13416 13417 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 13418 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 13419 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13420 instructionSets, null, null, null, 0, null /*certificates*/); 13421 this.cid = cid; 13422 setMountPath(PackageHelper.getSdDir(cid)); 13423 } 13424 13425 void createCopyFile() { 13426 cid = mInstallerService.allocateExternalStageCidLegacy(); 13427 } 13428 13429 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13430 if (origin.staged && origin.cid != null) { 13431 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 13432 cid = origin.cid; 13433 setMountPath(PackageHelper.getSdDir(cid)); 13434 return PackageManager.INSTALL_SUCCEEDED; 13435 } 13436 13437 if (temp) { 13438 createCopyFile(); 13439 } else { 13440 /* 13441 * Pre-emptively destroy the container since it's destroyed if 13442 * copying fails due to it existing anyway. 13443 */ 13444 PackageHelper.destroySdDir(cid); 13445 } 13446 13447 final String newMountPath = imcs.copyPackageToContainer( 13448 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 13449 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 13450 13451 if (newMountPath != null) { 13452 setMountPath(newMountPath); 13453 return PackageManager.INSTALL_SUCCEEDED; 13454 } else { 13455 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13456 } 13457 } 13458 13459 @Override 13460 String getCodePath() { 13461 return packagePath; 13462 } 13463 13464 @Override 13465 String getResourcePath() { 13466 return resourcePath; 13467 } 13468 13469 int doPreInstall(int status) { 13470 if (status != PackageManager.INSTALL_SUCCEEDED) { 13471 // Destroy container 13472 PackageHelper.destroySdDir(cid); 13473 } else { 13474 boolean mounted = PackageHelper.isContainerMounted(cid); 13475 if (!mounted) { 13476 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 13477 Process.SYSTEM_UID); 13478 if (newMountPath != null) { 13479 setMountPath(newMountPath); 13480 } else { 13481 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13482 } 13483 } 13484 } 13485 return status; 13486 } 13487 13488 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13489 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 13490 String newMountPath = null; 13491 if (PackageHelper.isContainerMounted(cid)) { 13492 // Unmount the container 13493 if (!PackageHelper.unMountSdDir(cid)) { 13494 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 13495 return false; 13496 } 13497 } 13498 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13499 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 13500 " which might be stale. Will try to clean up."); 13501 // Clean up the stale container and proceed to recreate. 13502 if (!PackageHelper.destroySdDir(newCacheId)) { 13503 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 13504 return false; 13505 } 13506 // Successfully cleaned up stale container. Try to rename again. 13507 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13508 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 13509 + " inspite of cleaning it up."); 13510 return false; 13511 } 13512 } 13513 if (!PackageHelper.isContainerMounted(newCacheId)) { 13514 Slog.w(TAG, "Mounting container " + newCacheId); 13515 newMountPath = PackageHelper.mountSdDir(newCacheId, 13516 getEncryptKey(), Process.SYSTEM_UID); 13517 } else { 13518 newMountPath = PackageHelper.getSdDir(newCacheId); 13519 } 13520 if (newMountPath == null) { 13521 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 13522 return false; 13523 } 13524 Log.i(TAG, "Succesfully renamed " + cid + 13525 " to " + newCacheId + 13526 " at new path: " + newMountPath); 13527 cid = newCacheId; 13528 13529 final File beforeCodeFile = new File(packagePath); 13530 setMountPath(newMountPath); 13531 final File afterCodeFile = new File(packagePath); 13532 13533 // Reflect the rename in scanned details 13534 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13535 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13536 afterCodeFile, pkg.baseCodePath)); 13537 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13538 afterCodeFile, pkg.splitCodePaths)); 13539 13540 // Reflect the rename in app info 13541 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13542 pkg.setApplicationInfoCodePath(pkg.codePath); 13543 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13544 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13545 pkg.setApplicationInfoResourcePath(pkg.codePath); 13546 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13547 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13548 13549 return true; 13550 } 13551 13552 private void setMountPath(String mountPath) { 13553 final File mountFile = new File(mountPath); 13554 13555 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 13556 if (monolithicFile.exists()) { 13557 packagePath = monolithicFile.getAbsolutePath(); 13558 if (isFwdLocked()) { 13559 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 13560 } else { 13561 resourcePath = packagePath; 13562 } 13563 } else { 13564 packagePath = mountFile.getAbsolutePath(); 13565 resourcePath = packagePath; 13566 } 13567 } 13568 13569 int doPostInstall(int status, int uid) { 13570 if (status != PackageManager.INSTALL_SUCCEEDED) { 13571 cleanUp(); 13572 } else { 13573 final int groupOwner; 13574 final String protectedFile; 13575 if (isFwdLocked()) { 13576 groupOwner = UserHandle.getSharedAppGid(uid); 13577 protectedFile = RES_FILE_NAME; 13578 } else { 13579 groupOwner = -1; 13580 protectedFile = null; 13581 } 13582 13583 if (uid < Process.FIRST_APPLICATION_UID 13584 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 13585 Slog.e(TAG, "Failed to finalize " + cid); 13586 PackageHelper.destroySdDir(cid); 13587 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13588 } 13589 13590 boolean mounted = PackageHelper.isContainerMounted(cid); 13591 if (!mounted) { 13592 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 13593 } 13594 } 13595 return status; 13596 } 13597 13598 private void cleanUp() { 13599 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 13600 13601 // Destroy secure container 13602 PackageHelper.destroySdDir(cid); 13603 } 13604 13605 private List<String> getAllCodePaths() { 13606 final File codeFile = new File(getCodePath()); 13607 if (codeFile != null && codeFile.exists()) { 13608 try { 13609 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13610 return pkg.getAllCodePaths(); 13611 } catch (PackageParserException e) { 13612 // Ignored; we tried our best 13613 } 13614 } 13615 return Collections.EMPTY_LIST; 13616 } 13617 13618 void cleanUpResourcesLI() { 13619 // Enumerate all code paths before deleting 13620 cleanUpResourcesLI(getAllCodePaths()); 13621 } 13622 13623 private void cleanUpResourcesLI(List<String> allCodePaths) { 13624 cleanUp(); 13625 removeDexFiles(allCodePaths, instructionSets); 13626 } 13627 13628 String getPackageName() { 13629 return getAsecPackageName(cid); 13630 } 13631 13632 boolean doPostDeleteLI(boolean delete) { 13633 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 13634 final List<String> allCodePaths = getAllCodePaths(); 13635 boolean mounted = PackageHelper.isContainerMounted(cid); 13636 if (mounted) { 13637 // Unmount first 13638 if (PackageHelper.unMountSdDir(cid)) { 13639 mounted = false; 13640 } 13641 } 13642 if (!mounted && delete) { 13643 cleanUpResourcesLI(allCodePaths); 13644 } 13645 return !mounted; 13646 } 13647 13648 @Override 13649 int doPreCopy() { 13650 if (isFwdLocked()) { 13651 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 13652 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 13653 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13654 } 13655 } 13656 13657 return PackageManager.INSTALL_SUCCEEDED; 13658 } 13659 13660 @Override 13661 int doPostCopy(int uid) { 13662 if (isFwdLocked()) { 13663 if (uid < Process.FIRST_APPLICATION_UID 13664 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 13665 RES_FILE_NAME)) { 13666 Slog.e(TAG, "Failed to finalize " + cid); 13667 PackageHelper.destroySdDir(cid); 13668 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13669 } 13670 } 13671 13672 return PackageManager.INSTALL_SUCCEEDED; 13673 } 13674 } 13675 13676 /** 13677 * Logic to handle movement of existing installed applications. 13678 */ 13679 class MoveInstallArgs extends InstallArgs { 13680 private File codeFile; 13681 private File resourceFile; 13682 13683 /** New install */ 13684 MoveInstallArgs(InstallParams params) { 13685 super(params.origin, params.move, params.observer, params.installFlags, 13686 params.installerPackageName, params.volumeUuid, 13687 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13688 params.grantedRuntimePermissions, 13689 params.traceMethod, params.traceCookie, params.certificates); 13690 } 13691 13692 int copyApk(IMediaContainerService imcs, boolean temp) { 13693 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 13694 + move.fromUuid + " to " + move.toUuid); 13695 synchronized (mInstaller) { 13696 try { 13697 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 13698 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 13699 } catch (InstallerException e) { 13700 Slog.w(TAG, "Failed to move app", e); 13701 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13702 } 13703 } 13704 13705 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 13706 resourceFile = codeFile; 13707 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 13708 13709 return PackageManager.INSTALL_SUCCEEDED; 13710 } 13711 13712 int doPreInstall(int status) { 13713 if (status != PackageManager.INSTALL_SUCCEEDED) { 13714 cleanUp(move.toUuid); 13715 } 13716 return status; 13717 } 13718 13719 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13720 if (status != PackageManager.INSTALL_SUCCEEDED) { 13721 cleanUp(move.toUuid); 13722 return false; 13723 } 13724 13725 // Reflect the move in app info 13726 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13727 pkg.setApplicationInfoCodePath(pkg.codePath); 13728 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13729 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13730 pkg.setApplicationInfoResourcePath(pkg.codePath); 13731 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13732 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13733 13734 return true; 13735 } 13736 13737 int doPostInstall(int status, int uid) { 13738 if (status == PackageManager.INSTALL_SUCCEEDED) { 13739 cleanUp(move.fromUuid); 13740 } else { 13741 cleanUp(move.toUuid); 13742 } 13743 return status; 13744 } 13745 13746 @Override 13747 String getCodePath() { 13748 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13749 } 13750 13751 @Override 13752 String getResourcePath() { 13753 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13754 } 13755 13756 private boolean cleanUp(String volumeUuid) { 13757 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 13758 move.dataAppName); 13759 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 13760 final int[] userIds = sUserManager.getUserIds(); 13761 synchronized (mInstallLock) { 13762 // Clean up both app data and code 13763 // All package moves are frozen until finished 13764 for (int userId : userIds) { 13765 try { 13766 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 13767 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 13768 } catch (InstallerException e) { 13769 Slog.w(TAG, String.valueOf(e)); 13770 } 13771 } 13772 removeCodePathLI(codeFile); 13773 } 13774 return true; 13775 } 13776 13777 void cleanUpResourcesLI() { 13778 throw new UnsupportedOperationException(); 13779 } 13780 13781 boolean doPostDeleteLI(boolean delete) { 13782 throw new UnsupportedOperationException(); 13783 } 13784 } 13785 13786 static String getAsecPackageName(String packageCid) { 13787 int idx = packageCid.lastIndexOf("-"); 13788 if (idx == -1) { 13789 return packageCid; 13790 } 13791 return packageCid.substring(0, idx); 13792 } 13793 13794 // Utility method used to create code paths based on package name and available index. 13795 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 13796 String idxStr = ""; 13797 int idx = 1; 13798 // Fall back to default value of idx=1 if prefix is not 13799 // part of oldCodePath 13800 if (oldCodePath != null) { 13801 String subStr = oldCodePath; 13802 // Drop the suffix right away 13803 if (suffix != null && subStr.endsWith(suffix)) { 13804 subStr = subStr.substring(0, subStr.length() - suffix.length()); 13805 } 13806 // If oldCodePath already contains prefix find out the 13807 // ending index to either increment or decrement. 13808 int sidx = subStr.lastIndexOf(prefix); 13809 if (sidx != -1) { 13810 subStr = subStr.substring(sidx + prefix.length()); 13811 if (subStr != null) { 13812 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 13813 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 13814 } 13815 try { 13816 idx = Integer.parseInt(subStr); 13817 if (idx <= 1) { 13818 idx++; 13819 } else { 13820 idx--; 13821 } 13822 } catch(NumberFormatException e) { 13823 } 13824 } 13825 } 13826 } 13827 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 13828 return prefix + idxStr; 13829 } 13830 13831 private File getNextCodePath(File targetDir, String packageName) { 13832 int suffix = 1; 13833 File result; 13834 do { 13835 result = new File(targetDir, packageName + "-" + suffix); 13836 suffix++; 13837 } while (result.exists()); 13838 return result; 13839 } 13840 13841 // Utility method that returns the relative package path with respect 13842 // to the installation directory. Like say for /data/data/com.test-1.apk 13843 // string com.test-1 is returned. 13844 static String deriveCodePathName(String codePath) { 13845 if (codePath == null) { 13846 return null; 13847 } 13848 final File codeFile = new File(codePath); 13849 final String name = codeFile.getName(); 13850 if (codeFile.isDirectory()) { 13851 return name; 13852 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 13853 final int lastDot = name.lastIndexOf('.'); 13854 return name.substring(0, lastDot); 13855 } else { 13856 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 13857 return null; 13858 } 13859 } 13860 13861 static class PackageInstalledInfo { 13862 String name; 13863 int uid; 13864 // The set of users that originally had this package installed. 13865 int[] origUsers; 13866 // The set of users that now have this package installed. 13867 int[] newUsers; 13868 PackageParser.Package pkg; 13869 int returnCode; 13870 String returnMsg; 13871 PackageRemovedInfo removedInfo; 13872 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 13873 13874 public void setError(int code, String msg) { 13875 setReturnCode(code); 13876 setReturnMessage(msg); 13877 Slog.w(TAG, msg); 13878 } 13879 13880 public void setError(String msg, PackageParserException e) { 13881 setReturnCode(e.error); 13882 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13883 Slog.w(TAG, msg, e); 13884 } 13885 13886 public void setError(String msg, PackageManagerException e) { 13887 returnCode = e.error; 13888 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13889 Slog.w(TAG, msg, e); 13890 } 13891 13892 public void setReturnCode(int returnCode) { 13893 this.returnCode = returnCode; 13894 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13895 for (int i = 0; i < childCount; i++) { 13896 addedChildPackages.valueAt(i).returnCode = returnCode; 13897 } 13898 } 13899 13900 private void setReturnMessage(String returnMsg) { 13901 this.returnMsg = returnMsg; 13902 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13903 for (int i = 0; i < childCount; i++) { 13904 addedChildPackages.valueAt(i).returnMsg = returnMsg; 13905 } 13906 } 13907 13908 // In some error cases we want to convey more info back to the observer 13909 String origPackage; 13910 String origPermission; 13911 } 13912 13913 /* 13914 * Install a non-existing package. 13915 */ 13916 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 13917 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 13918 PackageInstalledInfo res) { 13919 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 13920 13921 // Remember this for later, in case we need to rollback this install 13922 String pkgName = pkg.packageName; 13923 13924 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 13925 13926 synchronized(mPackages) { 13927 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 13928 // A package with the same name is already installed, though 13929 // it has been renamed to an older name. The package we 13930 // are trying to install should be installed as an update to 13931 // the existing one, but that has not been requested, so bail. 13932 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13933 + " without first uninstalling package running as " 13934 + mSettings.mRenamedPackages.get(pkgName)); 13935 return; 13936 } 13937 if (mPackages.containsKey(pkgName)) { 13938 // Don't allow installation over an existing package with the same name. 13939 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13940 + " without first uninstalling."); 13941 return; 13942 } 13943 } 13944 13945 try { 13946 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 13947 System.currentTimeMillis(), user); 13948 13949 updateSettingsLI(newPackage, installerPackageName, null, res, user); 13950 13951 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13952 prepareAppDataAfterInstallLIF(newPackage); 13953 13954 } else { 13955 // Remove package from internal structures, but keep around any 13956 // data that might have already existed 13957 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 13958 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 13959 } 13960 } catch (PackageManagerException e) { 13961 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13962 } 13963 13964 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13965 } 13966 13967 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 13968 // Can't rotate keys during boot or if sharedUser. 13969 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 13970 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 13971 return false; 13972 } 13973 // app is using upgradeKeySets; make sure all are valid 13974 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13975 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 13976 for (int i = 0; i < upgradeKeySets.length; i++) { 13977 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 13978 Slog.wtf(TAG, "Package " 13979 + (oldPs.name != null ? oldPs.name : "<null>") 13980 + " contains upgrade-key-set reference to unknown key-set: " 13981 + upgradeKeySets[i] 13982 + " reverting to signatures check."); 13983 return false; 13984 } 13985 } 13986 return true; 13987 } 13988 13989 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 13990 // Upgrade keysets are being used. Determine if new package has a superset of the 13991 // required keys. 13992 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 13993 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13994 for (int i = 0; i < upgradeKeySets.length; i++) { 13995 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 13996 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 13997 return true; 13998 } 13999 } 14000 return false; 14001 } 14002 14003 private static void updateDigest(MessageDigest digest, File file) throws IOException { 14004 try (DigestInputStream digestStream = 14005 new DigestInputStream(new FileInputStream(file), digest)) { 14006 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 14007 } 14008 } 14009 14010 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 14011 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 14012 final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 14013 14014 final PackageParser.Package oldPackage; 14015 final String pkgName = pkg.packageName; 14016 final int[] allUsers; 14017 final int[] installedUsers; 14018 14019 synchronized(mPackages) { 14020 oldPackage = mPackages.get(pkgName); 14021 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 14022 14023 // don't allow upgrade to target a release SDK from a pre-release SDK 14024 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 14025 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14026 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 14027 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14028 if (oldTargetsPreRelease 14029 && !newTargetsPreRelease 14030 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 14031 Slog.w(TAG, "Can't install package targeting released sdk"); 14032 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 14033 return; 14034 } 14035 14036 // don't allow an upgrade from full to ephemeral 14037 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 14038 if (isEphemeral && !oldIsEphemeral) { 14039 // can't downgrade from full to ephemeral 14040 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 14041 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14042 return; 14043 } 14044 14045 // verify signatures are valid 14046 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14047 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14048 if (!checkUpgradeKeySetLP(ps, pkg)) { 14049 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14050 "New package not signed by keys specified by upgrade-keysets: " 14051 + pkgName); 14052 return; 14053 } 14054 } else { 14055 // default to original signature matching 14056 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 14057 != PackageManager.SIGNATURE_MATCH) { 14058 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14059 "New package has a different signature: " + pkgName); 14060 return; 14061 } 14062 } 14063 14064 // don't allow a system upgrade unless the upgrade hash matches 14065 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 14066 byte[] digestBytes = null; 14067 try { 14068 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 14069 updateDigest(digest, new File(pkg.baseCodePath)); 14070 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 14071 for (String path : pkg.splitCodePaths) { 14072 updateDigest(digest, new File(path)); 14073 } 14074 } 14075 digestBytes = digest.digest(); 14076 } catch (NoSuchAlgorithmException | IOException e) { 14077 res.setError(INSTALL_FAILED_INVALID_APK, 14078 "Could not compute hash: " + pkgName); 14079 return; 14080 } 14081 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 14082 res.setError(INSTALL_FAILED_INVALID_APK, 14083 "New package fails restrict-update check: " + pkgName); 14084 return; 14085 } 14086 // retain upgrade restriction 14087 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 14088 } 14089 14090 // Check for shared user id changes 14091 String invalidPackageName = 14092 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 14093 if (invalidPackageName != null) { 14094 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 14095 "Package " + invalidPackageName + " tried to change user " 14096 + oldPackage.mSharedUserId); 14097 return; 14098 } 14099 14100 // In case of rollback, remember per-user/profile install state 14101 allUsers = sUserManager.getUserIds(); 14102 installedUsers = ps.queryInstalledUsers(allUsers, true); 14103 } 14104 14105 // Update what is removed 14106 res.removedInfo = new PackageRemovedInfo(); 14107 res.removedInfo.uid = oldPackage.applicationInfo.uid; 14108 res.removedInfo.removedPackage = oldPackage.packageName; 14109 res.removedInfo.isUpdate = true; 14110 res.removedInfo.origUsers = installedUsers; 14111 final int childCount = (oldPackage.childPackages != null) 14112 ? oldPackage.childPackages.size() : 0; 14113 for (int i = 0; i < childCount; i++) { 14114 boolean childPackageUpdated = false; 14115 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 14116 if (res.addedChildPackages != null) { 14117 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14118 if (childRes != null) { 14119 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 14120 childRes.removedInfo.removedPackage = childPkg.packageName; 14121 childRes.removedInfo.isUpdate = true; 14122 childPackageUpdated = true; 14123 } 14124 } 14125 if (!childPackageUpdated) { 14126 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 14127 childRemovedRes.removedPackage = childPkg.packageName; 14128 childRemovedRes.isUpdate = false; 14129 childRemovedRes.dataRemoved = true; 14130 synchronized (mPackages) { 14131 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14132 if (childPs != null) { 14133 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 14134 } 14135 } 14136 if (res.removedInfo.removedChildPackages == null) { 14137 res.removedInfo.removedChildPackages = new ArrayMap<>(); 14138 } 14139 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 14140 } 14141 } 14142 14143 boolean sysPkg = (isSystemApp(oldPackage)); 14144 if (sysPkg) { 14145 // Set the system/privileged flags as needed 14146 final boolean privileged = 14147 (oldPackage.applicationInfo.privateFlags 14148 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14149 final int systemPolicyFlags = policyFlags 14150 | PackageParser.PARSE_IS_SYSTEM 14151 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 14152 14153 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 14154 user, allUsers, installerPackageName, res); 14155 } else { 14156 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 14157 user, allUsers, installerPackageName, res); 14158 } 14159 } 14160 14161 public List<String> getPreviousCodePaths(String packageName) { 14162 final PackageSetting ps = mSettings.mPackages.get(packageName); 14163 final List<String> result = new ArrayList<String>(); 14164 if (ps != null && ps.oldCodePaths != null) { 14165 result.addAll(ps.oldCodePaths); 14166 } 14167 return result; 14168 } 14169 14170 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 14171 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14172 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14173 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 14174 + deletedPackage); 14175 14176 String pkgName = deletedPackage.packageName; 14177 boolean deletedPkg = true; 14178 boolean addedPkg = false; 14179 boolean updatedSettings = false; 14180 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 14181 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 14182 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 14183 14184 final long origUpdateTime = (pkg.mExtras != null) 14185 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 14186 14187 // First delete the existing package while retaining the data directory 14188 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14189 res.removedInfo, true, pkg)) { 14190 // If the existing package wasn't successfully deleted 14191 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 14192 deletedPkg = false; 14193 } else { 14194 // Successfully deleted the old package; proceed with replace. 14195 14196 // If deleted package lived in a container, give users a chance to 14197 // relinquish resources before killing. 14198 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 14199 if (DEBUG_INSTALL) { 14200 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 14201 } 14202 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 14203 final ArrayList<String> pkgList = new ArrayList<String>(1); 14204 pkgList.add(deletedPackage.applicationInfo.packageName); 14205 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 14206 } 14207 14208 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14209 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14210 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14211 14212 try { 14213 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 14214 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 14215 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14216 14217 // Update the in-memory copy of the previous code paths. 14218 PackageSetting ps = mSettings.mPackages.get(pkgName); 14219 if (!killApp) { 14220 if (ps.oldCodePaths == null) { 14221 ps.oldCodePaths = new ArraySet<>(); 14222 } 14223 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 14224 if (deletedPackage.splitCodePaths != null) { 14225 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 14226 } 14227 } else { 14228 ps.oldCodePaths = null; 14229 } 14230 if (ps.childPackageNames != null) { 14231 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 14232 final String childPkgName = ps.childPackageNames.get(i); 14233 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 14234 childPs.oldCodePaths = ps.oldCodePaths; 14235 } 14236 } 14237 prepareAppDataAfterInstallLIF(newPackage); 14238 addedPkg = true; 14239 } catch (PackageManagerException e) { 14240 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14241 } 14242 } 14243 14244 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14245 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 14246 14247 // Revert all internal state mutations and added folders for the failed install 14248 if (addedPkg) { 14249 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14250 res.removedInfo, true, null); 14251 } 14252 14253 // Restore the old package 14254 if (deletedPkg) { 14255 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 14256 File restoreFile = new File(deletedPackage.codePath); 14257 // Parse old package 14258 boolean oldExternal = isExternal(deletedPackage); 14259 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 14260 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 14261 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 14262 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 14263 try { 14264 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 14265 null); 14266 } catch (PackageManagerException e) { 14267 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 14268 + e.getMessage()); 14269 return; 14270 } 14271 14272 synchronized (mPackages) { 14273 // Ensure the installer package name up to date 14274 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14275 14276 // Update permissions for restored package 14277 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14278 14279 mSettings.writeLPr(); 14280 } 14281 14282 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 14283 } 14284 } else { 14285 synchronized (mPackages) { 14286 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 14287 if (ps != null) { 14288 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 14289 if (res.removedInfo.removedChildPackages != null) { 14290 final int childCount = res.removedInfo.removedChildPackages.size(); 14291 // Iterate in reverse as we may modify the collection 14292 for (int i = childCount - 1; i >= 0; i--) { 14293 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 14294 if (res.addedChildPackages.containsKey(childPackageName)) { 14295 res.removedInfo.removedChildPackages.removeAt(i); 14296 } else { 14297 PackageRemovedInfo childInfo = res.removedInfo 14298 .removedChildPackages.valueAt(i); 14299 childInfo.removedForAllUsers = mPackages.get( 14300 childInfo.removedPackage) == null; 14301 } 14302 } 14303 } 14304 } 14305 } 14306 } 14307 } 14308 14309 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 14310 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14311 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14312 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 14313 + ", old=" + deletedPackage); 14314 14315 final boolean disabledSystem; 14316 14317 // Remove existing system package 14318 removePackageLI(deletedPackage, true); 14319 14320 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 14321 if (!disabledSystem) { 14322 // We didn't need to disable the .apk as a current system package, 14323 // which means we are replacing another update that is already 14324 // installed. We need to make sure to delete the older one's .apk. 14325 res.removedInfo.args = createInstallArgsForExisting(0, 14326 deletedPackage.applicationInfo.getCodePath(), 14327 deletedPackage.applicationInfo.getResourcePath(), 14328 getAppDexInstructionSets(deletedPackage.applicationInfo)); 14329 } else { 14330 res.removedInfo.args = null; 14331 } 14332 14333 // Successfully disabled the old package. Now proceed with re-installation 14334 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14335 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14336 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14337 14338 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14339 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 14340 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 14341 14342 PackageParser.Package newPackage = null; 14343 try { 14344 // Add the package to the internal data structures 14345 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 14346 14347 // Set the update and install times 14348 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 14349 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 14350 System.currentTimeMillis()); 14351 14352 // Update the package dynamic state if succeeded 14353 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14354 // Now that the install succeeded make sure we remove data 14355 // directories for any child package the update removed. 14356 final int deletedChildCount = (deletedPackage.childPackages != null) 14357 ? deletedPackage.childPackages.size() : 0; 14358 final int newChildCount = (newPackage.childPackages != null) 14359 ? newPackage.childPackages.size() : 0; 14360 for (int i = 0; i < deletedChildCount; i++) { 14361 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 14362 boolean childPackageDeleted = true; 14363 for (int j = 0; j < newChildCount; j++) { 14364 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 14365 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 14366 childPackageDeleted = false; 14367 break; 14368 } 14369 } 14370 if (childPackageDeleted) { 14371 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 14372 deletedChildPkg.packageName); 14373 if (ps != null && res.removedInfo.removedChildPackages != null) { 14374 PackageRemovedInfo removedChildRes = res.removedInfo 14375 .removedChildPackages.get(deletedChildPkg.packageName); 14376 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 14377 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 14378 } 14379 } 14380 } 14381 14382 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14383 prepareAppDataAfterInstallLIF(newPackage); 14384 } 14385 } catch (PackageManagerException e) { 14386 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 14387 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14388 } 14389 14390 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14391 // Re installation failed. Restore old information 14392 // Remove new pkg information 14393 if (newPackage != null) { 14394 removeInstalledPackageLI(newPackage, true); 14395 } 14396 // Add back the old system package 14397 try { 14398 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 14399 } catch (PackageManagerException e) { 14400 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 14401 } 14402 14403 synchronized (mPackages) { 14404 if (disabledSystem) { 14405 enableSystemPackageLPw(deletedPackage); 14406 } 14407 14408 // Ensure the installer package name up to date 14409 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14410 14411 // Update permissions for restored package 14412 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14413 14414 mSettings.writeLPr(); 14415 } 14416 14417 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 14418 + " after failed upgrade"); 14419 } 14420 } 14421 14422 /** 14423 * Checks whether the parent or any of the child packages have a change shared 14424 * user. For a package to be a valid update the shred users of the parent and 14425 * the children should match. We may later support changing child shared users. 14426 * @param oldPkg The updated package. 14427 * @param newPkg The update package. 14428 * @return The shared user that change between the versions. 14429 */ 14430 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 14431 PackageParser.Package newPkg) { 14432 // Check parent shared user 14433 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 14434 return newPkg.packageName; 14435 } 14436 // Check child shared users 14437 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14438 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 14439 for (int i = 0; i < newChildCount; i++) { 14440 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 14441 // If this child was present, did it have the same shared user? 14442 for (int j = 0; j < oldChildCount; j++) { 14443 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 14444 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 14445 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 14446 return newChildPkg.packageName; 14447 } 14448 } 14449 } 14450 return null; 14451 } 14452 14453 private void removeNativeBinariesLI(PackageSetting ps) { 14454 // Remove the lib path for the parent package 14455 if (ps != null) { 14456 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 14457 // Remove the lib path for the child packages 14458 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 14459 for (int i = 0; i < childCount; i++) { 14460 PackageSetting childPs = null; 14461 synchronized (mPackages) { 14462 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 14463 } 14464 if (childPs != null) { 14465 NativeLibraryHelper.removeNativeBinariesLI(childPs 14466 .legacyNativeLibraryPathString); 14467 } 14468 } 14469 } 14470 } 14471 14472 private void enableSystemPackageLPw(PackageParser.Package pkg) { 14473 // Enable the parent package 14474 mSettings.enableSystemPackageLPw(pkg.packageName); 14475 // Enable the child packages 14476 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14477 for (int i = 0; i < childCount; i++) { 14478 PackageParser.Package childPkg = pkg.childPackages.get(i); 14479 mSettings.enableSystemPackageLPw(childPkg.packageName); 14480 } 14481 } 14482 14483 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 14484 PackageParser.Package newPkg) { 14485 // Disable the parent package (parent always replaced) 14486 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 14487 // Disable the child packages 14488 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14489 for (int i = 0; i < childCount; i++) { 14490 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 14491 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 14492 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 14493 } 14494 return disabled; 14495 } 14496 14497 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 14498 String installerPackageName) { 14499 // Enable the parent package 14500 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 14501 // Enable the child packages 14502 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14503 for (int i = 0; i < childCount; i++) { 14504 PackageParser.Package childPkg = pkg.childPackages.get(i); 14505 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 14506 } 14507 } 14508 14509 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 14510 // Collect all used permissions in the UID 14511 ArraySet<String> usedPermissions = new ArraySet<>(); 14512 final int packageCount = su.packages.size(); 14513 for (int i = 0; i < packageCount; i++) { 14514 PackageSetting ps = su.packages.valueAt(i); 14515 if (ps.pkg == null) { 14516 continue; 14517 } 14518 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 14519 for (int j = 0; j < requestedPermCount; j++) { 14520 String permission = ps.pkg.requestedPermissions.get(j); 14521 BasePermission bp = mSettings.mPermissions.get(permission); 14522 if (bp != null) { 14523 usedPermissions.add(permission); 14524 } 14525 } 14526 } 14527 14528 PermissionsState permissionsState = su.getPermissionsState(); 14529 // Prune install permissions 14530 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 14531 final int installPermCount = installPermStates.size(); 14532 for (int i = installPermCount - 1; i >= 0; i--) { 14533 PermissionState permissionState = installPermStates.get(i); 14534 if (!usedPermissions.contains(permissionState.getName())) { 14535 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14536 if (bp != null) { 14537 permissionsState.revokeInstallPermission(bp); 14538 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 14539 PackageManager.MASK_PERMISSION_FLAGS, 0); 14540 } 14541 } 14542 } 14543 14544 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 14545 14546 // Prune runtime permissions 14547 for (int userId : allUserIds) { 14548 List<PermissionState> runtimePermStates = permissionsState 14549 .getRuntimePermissionStates(userId); 14550 final int runtimePermCount = runtimePermStates.size(); 14551 for (int i = runtimePermCount - 1; i >= 0; i--) { 14552 PermissionState permissionState = runtimePermStates.get(i); 14553 if (!usedPermissions.contains(permissionState.getName())) { 14554 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14555 if (bp != null) { 14556 permissionsState.revokeRuntimePermission(bp, userId); 14557 permissionsState.updatePermissionFlags(bp, userId, 14558 PackageManager.MASK_PERMISSION_FLAGS, 0); 14559 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 14560 runtimePermissionChangedUserIds, userId); 14561 } 14562 } 14563 } 14564 } 14565 14566 return runtimePermissionChangedUserIds; 14567 } 14568 14569 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 14570 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 14571 // Update the parent package setting 14572 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 14573 res, user); 14574 // Update the child packages setting 14575 final int childCount = (newPackage.childPackages != null) 14576 ? newPackage.childPackages.size() : 0; 14577 for (int i = 0; i < childCount; i++) { 14578 PackageParser.Package childPackage = newPackage.childPackages.get(i); 14579 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 14580 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 14581 childRes.origUsers, childRes, user); 14582 } 14583 } 14584 14585 private void updateSettingsInternalLI(PackageParser.Package newPackage, 14586 String installerPackageName, int[] allUsers, int[] installedForUsers, 14587 PackageInstalledInfo res, UserHandle user) { 14588 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 14589 14590 String pkgName = newPackage.packageName; 14591 synchronized (mPackages) { 14592 //write settings. the installStatus will be incomplete at this stage. 14593 //note that the new package setting would have already been 14594 //added to mPackages. It hasn't been persisted yet. 14595 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 14596 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14597 mSettings.writeLPr(); 14598 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14599 } 14600 14601 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 14602 synchronized (mPackages) { 14603 updatePermissionsLPw(newPackage.packageName, newPackage, 14604 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 14605 ? UPDATE_PERMISSIONS_ALL : 0)); 14606 // For system-bundled packages, we assume that installing an upgraded version 14607 // of the package implies that the user actually wants to run that new code, 14608 // so we enable the package. 14609 PackageSetting ps = mSettings.mPackages.get(pkgName); 14610 final int userId = user.getIdentifier(); 14611 if (ps != null) { 14612 if (isSystemApp(newPackage)) { 14613 if (DEBUG_INSTALL) { 14614 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 14615 } 14616 // Enable system package for requested users 14617 if (res.origUsers != null) { 14618 for (int origUserId : res.origUsers) { 14619 if (userId == UserHandle.USER_ALL || userId == origUserId) { 14620 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 14621 origUserId, installerPackageName); 14622 } 14623 } 14624 } 14625 // Also convey the prior install/uninstall state 14626 if (allUsers != null && installedForUsers != null) { 14627 for (int currentUserId : allUsers) { 14628 final boolean installed = ArrayUtils.contains( 14629 installedForUsers, currentUserId); 14630 if (DEBUG_INSTALL) { 14631 Slog.d(TAG, " user " + currentUserId + " => " + installed); 14632 } 14633 ps.setInstalled(installed, currentUserId); 14634 } 14635 // these install state changes will be persisted in the 14636 // upcoming call to mSettings.writeLPr(). 14637 } 14638 } 14639 // It's implied that when a user requests installation, they want the app to be 14640 // installed and enabled. 14641 if (userId != UserHandle.USER_ALL) { 14642 ps.setInstalled(true, userId); 14643 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 14644 } 14645 } 14646 res.name = pkgName; 14647 res.uid = newPackage.applicationInfo.uid; 14648 res.pkg = newPackage; 14649 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 14650 mSettings.setInstallerPackageName(pkgName, installerPackageName); 14651 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14652 //to update install status 14653 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14654 mSettings.writeLPr(); 14655 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14656 } 14657 14658 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14659 } 14660 14661 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 14662 try { 14663 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 14664 installPackageLI(args, res); 14665 } finally { 14666 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14667 } 14668 } 14669 14670 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 14671 final int installFlags = args.installFlags; 14672 final String installerPackageName = args.installerPackageName; 14673 final String volumeUuid = args.volumeUuid; 14674 final File tmpPackageFile = new File(args.getCodePath()); 14675 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 14676 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 14677 || (args.volumeUuid != null)); 14678 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 14679 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 14680 boolean replace = false; 14681 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 14682 if (args.move != null) { 14683 // moving a complete application; perform an initial scan on the new install location 14684 scanFlags |= SCAN_INITIAL; 14685 } 14686 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 14687 scanFlags |= SCAN_DONT_KILL_APP; 14688 } 14689 14690 // Result object to be returned 14691 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14692 14693 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 14694 14695 // Sanity check 14696 if (ephemeral && (forwardLocked || onExternal)) { 14697 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 14698 + " external=" + onExternal); 14699 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14700 return; 14701 } 14702 14703 // Retrieve PackageSettings and parse package 14704 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 14705 | PackageParser.PARSE_ENFORCE_CODE 14706 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 14707 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 14708 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0) 14709 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 14710 PackageParser pp = new PackageParser(); 14711 pp.setSeparateProcesses(mSeparateProcesses); 14712 pp.setDisplayMetrics(mMetrics); 14713 14714 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 14715 final PackageParser.Package pkg; 14716 try { 14717 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 14718 } catch (PackageParserException e) { 14719 res.setError("Failed parse during installPackageLI", e); 14720 return; 14721 } finally { 14722 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14723 } 14724 14725 // If we are installing a clustered package add results for the children 14726 if (pkg.childPackages != null) { 14727 synchronized (mPackages) { 14728 final int childCount = pkg.childPackages.size(); 14729 for (int i = 0; i < childCount; i++) { 14730 PackageParser.Package childPkg = pkg.childPackages.get(i); 14731 PackageInstalledInfo childRes = new PackageInstalledInfo(); 14732 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14733 childRes.pkg = childPkg; 14734 childRes.name = childPkg.packageName; 14735 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14736 if (childPs != null) { 14737 childRes.origUsers = childPs.queryInstalledUsers( 14738 sUserManager.getUserIds(), true); 14739 } 14740 if ((mPackages.containsKey(childPkg.packageName))) { 14741 childRes.removedInfo = new PackageRemovedInfo(); 14742 childRes.removedInfo.removedPackage = childPkg.packageName; 14743 } 14744 if (res.addedChildPackages == null) { 14745 res.addedChildPackages = new ArrayMap<>(); 14746 } 14747 res.addedChildPackages.put(childPkg.packageName, childRes); 14748 } 14749 } 14750 } 14751 14752 // If package doesn't declare API override, mark that we have an install 14753 // time CPU ABI override. 14754 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 14755 pkg.cpuAbiOverride = args.abiOverride; 14756 } 14757 14758 String pkgName = res.name = pkg.packageName; 14759 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 14760 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 14761 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 14762 return; 14763 } 14764 } 14765 14766 try { 14767 // either use what we've been given or parse directly from the APK 14768 if (args.certificates != null) { 14769 try { 14770 PackageParser.populateCertificates(pkg, args.certificates); 14771 } catch (PackageParserException e) { 14772 // there was something wrong with the certificates we were given; 14773 // try to pull them from the APK 14774 PackageParser.collectCertificates(pkg, parseFlags); 14775 } 14776 } else { 14777 PackageParser.collectCertificates(pkg, parseFlags); 14778 } 14779 } catch (PackageParserException e) { 14780 res.setError("Failed collect during installPackageLI", e); 14781 return; 14782 } 14783 14784 // Get rid of all references to package scan path via parser. 14785 pp = null; 14786 String oldCodePath = null; 14787 boolean systemApp = false; 14788 synchronized (mPackages) { 14789 // Check if installing already existing package 14790 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14791 String oldName = mSettings.mRenamedPackages.get(pkgName); 14792 if (pkg.mOriginalPackages != null 14793 && pkg.mOriginalPackages.contains(oldName) 14794 && mPackages.containsKey(oldName)) { 14795 // This package is derived from an original package, 14796 // and this device has been updating from that original 14797 // name. We must continue using the original name, so 14798 // rename the new package here. 14799 pkg.setPackageName(oldName); 14800 pkgName = pkg.packageName; 14801 replace = true; 14802 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 14803 + oldName + " pkgName=" + pkgName); 14804 } else if (mPackages.containsKey(pkgName)) { 14805 // This package, under its official name, already exists 14806 // on the device; we should replace it. 14807 replace = true; 14808 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 14809 } 14810 14811 // Child packages are installed through the parent package 14812 if (pkg.parentPackage != null) { 14813 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14814 "Package " + pkg.packageName + " is child of package " 14815 + pkg.parentPackage.parentPackage + ". Child packages " 14816 + "can be updated only through the parent package."); 14817 return; 14818 } 14819 14820 if (replace) { 14821 // Prevent apps opting out from runtime permissions 14822 PackageParser.Package oldPackage = mPackages.get(pkgName); 14823 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 14824 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 14825 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 14826 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 14827 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 14828 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 14829 + " doesn't support runtime permissions but the old" 14830 + " target SDK " + oldTargetSdk + " does."); 14831 return; 14832 } 14833 14834 // Prevent installing of child packages 14835 if (oldPackage.parentPackage != null) { 14836 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14837 "Package " + pkg.packageName + " is child of package " 14838 + oldPackage.parentPackage + ". Child packages " 14839 + "can be updated only through the parent package."); 14840 return; 14841 } 14842 } 14843 } 14844 14845 PackageSetting ps = mSettings.mPackages.get(pkgName); 14846 if (ps != null) { 14847 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 14848 14849 // Quick sanity check that we're signed correctly if updating; 14850 // we'll check this again later when scanning, but we want to 14851 // bail early here before tripping over redefined permissions. 14852 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14853 if (!checkUpgradeKeySetLP(ps, pkg)) { 14854 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 14855 + pkg.packageName + " upgrade keys do not match the " 14856 + "previously installed version"); 14857 return; 14858 } 14859 } else { 14860 try { 14861 verifySignaturesLP(ps, pkg); 14862 } catch (PackageManagerException e) { 14863 res.setError(e.error, e.getMessage()); 14864 return; 14865 } 14866 } 14867 14868 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 14869 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 14870 systemApp = (ps.pkg.applicationInfo.flags & 14871 ApplicationInfo.FLAG_SYSTEM) != 0; 14872 } 14873 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14874 } 14875 14876 // Check whether the newly-scanned package wants to define an already-defined perm 14877 int N = pkg.permissions.size(); 14878 for (int i = N-1; i >= 0; i--) { 14879 PackageParser.Permission perm = pkg.permissions.get(i); 14880 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 14881 if (bp != null) { 14882 // If the defining package is signed with our cert, it's okay. This 14883 // also includes the "updating the same package" case, of course. 14884 // "updating same package" could also involve key-rotation. 14885 final boolean sigsOk; 14886 if (bp.sourcePackage.equals(pkg.packageName) 14887 && (bp.packageSetting instanceof PackageSetting) 14888 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 14889 scanFlags))) { 14890 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 14891 } else { 14892 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 14893 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 14894 } 14895 if (!sigsOk) { 14896 // If the owning package is the system itself, we log but allow 14897 // install to proceed; we fail the install on all other permission 14898 // redefinitions. 14899 if (!bp.sourcePackage.equals("android")) { 14900 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 14901 + pkg.packageName + " attempting to redeclare permission " 14902 + perm.info.name + " already owned by " + bp.sourcePackage); 14903 res.origPermission = perm.info.name; 14904 res.origPackage = bp.sourcePackage; 14905 return; 14906 } else { 14907 Slog.w(TAG, "Package " + pkg.packageName 14908 + " attempting to redeclare system permission " 14909 + perm.info.name + "; ignoring new declaration"); 14910 pkg.permissions.remove(i); 14911 } 14912 } 14913 } 14914 } 14915 } 14916 14917 if (systemApp) { 14918 if (onExternal) { 14919 // Abort update; system app can't be replaced with app on sdcard 14920 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 14921 "Cannot install updates to system apps on sdcard"); 14922 return; 14923 } else if (ephemeral) { 14924 // Abort update; system app can't be replaced with an ephemeral app 14925 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 14926 "Cannot update a system app with an ephemeral app"); 14927 return; 14928 } 14929 } 14930 14931 if (args.move != null) { 14932 // We did an in-place move, so dex is ready to roll 14933 scanFlags |= SCAN_NO_DEX; 14934 scanFlags |= SCAN_MOVE; 14935 14936 synchronized (mPackages) { 14937 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14938 if (ps == null) { 14939 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 14940 "Missing settings for moved package " + pkgName); 14941 } 14942 14943 // We moved the entire application as-is, so bring over the 14944 // previously derived ABI information. 14945 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 14946 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 14947 } 14948 14949 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 14950 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 14951 scanFlags |= SCAN_NO_DEX; 14952 14953 try { 14954 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 14955 args.abiOverride : pkg.cpuAbiOverride); 14956 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 14957 true /* extract libs */); 14958 } catch (PackageManagerException pme) { 14959 Slog.e(TAG, "Error deriving application ABI", pme); 14960 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 14961 return; 14962 } 14963 14964 // Shared libraries for the package need to be updated. 14965 synchronized (mPackages) { 14966 try { 14967 updateSharedLibrariesLPw(pkg, null); 14968 } catch (PackageManagerException e) { 14969 Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage()); 14970 } 14971 } 14972 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 14973 // Do not run PackageDexOptimizer through the local performDexOpt 14974 // method because `pkg` is not in `mPackages` yet. 14975 int result = mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 14976 null /* instructionSets */, false /* checkProfiles */, 14977 getCompilerFilterForReason(REASON_INSTALL)); 14978 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14979 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 14980 String msg = "Extracting package failed for " + pkgName; 14981 res.setError(INSTALL_FAILED_DEXOPT, msg); 14982 return; 14983 } 14984 14985 // Notify BackgroundDexOptService that the package has been changed. 14986 // If this is an update of a package which used to fail to compile, 14987 // BDOS will remove it from its blacklist. 14988 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 14989 } 14990 14991 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 14992 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 14993 return; 14994 } 14995 14996 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 14997 14998 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 14999 "installPackageLI")) { 15000 if (replace) { 15001 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 15002 installerPackageName, res); 15003 } else { 15004 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 15005 args.user, installerPackageName, volumeUuid, res); 15006 } 15007 } 15008 synchronized (mPackages) { 15009 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15010 if (ps != null) { 15011 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 15012 } 15013 15014 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15015 for (int i = 0; i < childCount; i++) { 15016 PackageParser.Package childPkg = pkg.childPackages.get(i); 15017 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 15018 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 15019 if (childPs != null) { 15020 childRes.newUsers = childPs.queryInstalledUsers( 15021 sUserManager.getUserIds(), true); 15022 } 15023 } 15024 } 15025 } 15026 15027 private void startIntentFilterVerifications(int userId, boolean replacing, 15028 PackageParser.Package pkg) { 15029 if (mIntentFilterVerifierComponent == null) { 15030 Slog.w(TAG, "No IntentFilter verification will not be done as " 15031 + "there is no IntentFilterVerifier available!"); 15032 return; 15033 } 15034 15035 final int verifierUid = getPackageUid( 15036 mIntentFilterVerifierComponent.getPackageName(), 15037 MATCH_DEBUG_TRIAGED_MISSING, 15038 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 15039 15040 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15041 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 15042 mHandler.sendMessage(msg); 15043 15044 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15045 for (int i = 0; i < childCount; i++) { 15046 PackageParser.Package childPkg = pkg.childPackages.get(i); 15047 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15048 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 15049 mHandler.sendMessage(msg); 15050 } 15051 } 15052 15053 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 15054 PackageParser.Package pkg) { 15055 int size = pkg.activities.size(); 15056 if (size == 0) { 15057 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15058 "No activity, so no need to verify any IntentFilter!"); 15059 return; 15060 } 15061 15062 final boolean hasDomainURLs = hasDomainURLs(pkg); 15063 if (!hasDomainURLs) { 15064 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15065 "No domain URLs, so no need to verify any IntentFilter!"); 15066 return; 15067 } 15068 15069 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 15070 + " if any IntentFilter from the " + size 15071 + " Activities needs verification ..."); 15072 15073 int count = 0; 15074 final String packageName = pkg.packageName; 15075 15076 synchronized (mPackages) { 15077 // If this is a new install and we see that we've already run verification for this 15078 // package, we have nothing to do: it means the state was restored from backup. 15079 if (!replacing) { 15080 IntentFilterVerificationInfo ivi = 15081 mSettings.getIntentFilterVerificationLPr(packageName); 15082 if (ivi != null) { 15083 if (DEBUG_DOMAIN_VERIFICATION) { 15084 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 15085 + ivi.getStatusString()); 15086 } 15087 return; 15088 } 15089 } 15090 15091 // If any filters need to be verified, then all need to be. 15092 boolean needToVerify = false; 15093 for (PackageParser.Activity a : pkg.activities) { 15094 for (ActivityIntentInfo filter : a.intents) { 15095 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 15096 if (DEBUG_DOMAIN_VERIFICATION) { 15097 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 15098 } 15099 needToVerify = true; 15100 break; 15101 } 15102 } 15103 } 15104 15105 if (needToVerify) { 15106 final int verificationId = mIntentFilterVerificationToken++; 15107 for (PackageParser.Activity a : pkg.activities) { 15108 for (ActivityIntentInfo filter : a.intents) { 15109 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 15110 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15111 "Verification needed for IntentFilter:" + filter.toString()); 15112 mIntentFilterVerifier.addOneIntentFilterVerification( 15113 verifierUid, userId, verificationId, filter, packageName); 15114 count++; 15115 } 15116 } 15117 } 15118 } 15119 } 15120 15121 if (count > 0) { 15122 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 15123 + " IntentFilter verification" + (count > 1 ? "s" : "") 15124 + " for userId:" + userId); 15125 mIntentFilterVerifier.startVerifications(userId); 15126 } else { 15127 if (DEBUG_DOMAIN_VERIFICATION) { 15128 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 15129 } 15130 } 15131 } 15132 15133 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 15134 final ComponentName cn = filter.activity.getComponentName(); 15135 final String packageName = cn.getPackageName(); 15136 15137 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 15138 packageName); 15139 if (ivi == null) { 15140 return true; 15141 } 15142 int status = ivi.getStatus(); 15143 switch (status) { 15144 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 15145 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 15146 return true; 15147 15148 default: 15149 // Nothing to do 15150 return false; 15151 } 15152 } 15153 15154 private static boolean isMultiArch(ApplicationInfo info) { 15155 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 15156 } 15157 15158 private static boolean isExternal(PackageParser.Package pkg) { 15159 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15160 } 15161 15162 private static boolean isExternal(PackageSetting ps) { 15163 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15164 } 15165 15166 private static boolean isEphemeral(PackageParser.Package pkg) { 15167 return pkg.applicationInfo.isEphemeralApp(); 15168 } 15169 15170 private static boolean isEphemeral(PackageSetting ps) { 15171 return ps.pkg != null && isEphemeral(ps.pkg); 15172 } 15173 15174 private static boolean isSystemApp(PackageParser.Package pkg) { 15175 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 15176 } 15177 15178 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 15179 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 15180 } 15181 15182 private static boolean hasDomainURLs(PackageParser.Package pkg) { 15183 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 15184 } 15185 15186 private static boolean isSystemApp(PackageSetting ps) { 15187 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 15188 } 15189 15190 private static boolean isUpdatedSystemApp(PackageSetting ps) { 15191 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 15192 } 15193 15194 private int packageFlagsToInstallFlags(PackageSetting ps) { 15195 int installFlags = 0; 15196 if (isEphemeral(ps)) { 15197 installFlags |= PackageManager.INSTALL_EPHEMERAL; 15198 } 15199 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 15200 // This existing package was an external ASEC install when we have 15201 // the external flag without a UUID 15202 installFlags |= PackageManager.INSTALL_EXTERNAL; 15203 } 15204 if (ps.isForwardLocked()) { 15205 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 15206 } 15207 return installFlags; 15208 } 15209 15210 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 15211 if (isExternal(pkg)) { 15212 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15213 return StorageManager.UUID_PRIMARY_PHYSICAL; 15214 } else { 15215 return pkg.volumeUuid; 15216 } 15217 } else { 15218 return StorageManager.UUID_PRIVATE_INTERNAL; 15219 } 15220 } 15221 15222 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 15223 if (isExternal(pkg)) { 15224 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15225 return mSettings.getExternalVersion(); 15226 } else { 15227 return mSettings.findOrCreateVersion(pkg.volumeUuid); 15228 } 15229 } else { 15230 return mSettings.getInternalVersion(); 15231 } 15232 } 15233 15234 private void deleteTempPackageFiles() { 15235 final FilenameFilter filter = new FilenameFilter() { 15236 public boolean accept(File dir, String name) { 15237 return name.startsWith("vmdl") && name.endsWith(".tmp"); 15238 } 15239 }; 15240 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 15241 file.delete(); 15242 } 15243 } 15244 15245 @Override 15246 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 15247 int flags) { 15248 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 15249 flags); 15250 } 15251 15252 @Override 15253 public void deletePackage(final String packageName, 15254 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 15255 mContext.enforceCallingOrSelfPermission( 15256 android.Manifest.permission.DELETE_PACKAGES, null); 15257 Preconditions.checkNotNull(packageName); 15258 Preconditions.checkNotNull(observer); 15259 final int uid = Binder.getCallingUid(); 15260 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 15261 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 15262 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 15263 mContext.enforceCallingOrSelfPermission( 15264 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 15265 "deletePackage for user " + userId); 15266 } 15267 15268 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 15269 try { 15270 observer.onPackageDeleted(packageName, 15271 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 15272 } catch (RemoteException re) { 15273 } 15274 return; 15275 } 15276 15277 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 15278 try { 15279 observer.onPackageDeleted(packageName, 15280 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 15281 } catch (RemoteException re) { 15282 } 15283 return; 15284 } 15285 15286 if (DEBUG_REMOVE) { 15287 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 15288 + " deleteAllUsers: " + deleteAllUsers ); 15289 } 15290 // Queue up an async operation since the package deletion may take a little while. 15291 mHandler.post(new Runnable() { 15292 public void run() { 15293 mHandler.removeCallbacks(this); 15294 int returnCode; 15295 if (!deleteAllUsers) { 15296 returnCode = deletePackageX(packageName, userId, deleteFlags); 15297 } else { 15298 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 15299 // If nobody is blocking uninstall, proceed with delete for all users 15300 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 15301 returnCode = deletePackageX(packageName, userId, deleteFlags); 15302 } else { 15303 // Otherwise uninstall individually for users with blockUninstalls=false 15304 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 15305 for (int userId : users) { 15306 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 15307 returnCode = deletePackageX(packageName, userId, userFlags); 15308 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 15309 Slog.w(TAG, "Package delete failed for user " + userId 15310 + ", returnCode " + returnCode); 15311 } 15312 } 15313 } 15314 // The app has only been marked uninstalled for certain users. 15315 // We still need to report that delete was blocked 15316 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 15317 } 15318 } 15319 try { 15320 observer.onPackageDeleted(packageName, returnCode, null); 15321 } catch (RemoteException e) { 15322 Log.i(TAG, "Observer no longer exists."); 15323 } //end catch 15324 } //end run 15325 }); 15326 } 15327 15328 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 15329 int[] result = EMPTY_INT_ARRAY; 15330 for (int userId : userIds) { 15331 if (getBlockUninstallForUser(packageName, userId)) { 15332 result = ArrayUtils.appendInt(result, userId); 15333 } 15334 } 15335 return result; 15336 } 15337 15338 @Override 15339 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 15340 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 15341 } 15342 15343 private boolean isPackageDeviceAdmin(String packageName, int userId) { 15344 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 15345 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 15346 try { 15347 if (dpm != null) { 15348 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 15349 /* callingUserOnly =*/ false); 15350 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 15351 : deviceOwnerComponentName.getPackageName(); 15352 // Does the package contains the device owner? 15353 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 15354 // this check is probably not needed, since DO should be registered as a device 15355 // admin on some user too. (Original bug for this: b/17657954) 15356 if (packageName.equals(deviceOwnerPackageName)) { 15357 return true; 15358 } 15359 // Does it contain a device admin for any user? 15360 int[] users; 15361 if (userId == UserHandle.USER_ALL) { 15362 users = sUserManager.getUserIds(); 15363 } else { 15364 users = new int[]{userId}; 15365 } 15366 for (int i = 0; i < users.length; ++i) { 15367 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 15368 return true; 15369 } 15370 } 15371 } 15372 } catch (RemoteException e) { 15373 } 15374 return false; 15375 } 15376 15377 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 15378 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 15379 } 15380 15381 /** 15382 * This method is an internal method that could be get invoked either 15383 * to delete an installed package or to clean up a failed installation. 15384 * After deleting an installed package, a broadcast is sent to notify any 15385 * listeners that the package has been removed. For cleaning up a failed 15386 * installation, the broadcast is not necessary since the package's 15387 * installation wouldn't have sent the initial broadcast either 15388 * The key steps in deleting a package are 15389 * deleting the package information in internal structures like mPackages, 15390 * deleting the packages base directories through installd 15391 * updating mSettings to reflect current status 15392 * persisting settings for later use 15393 * sending a broadcast if necessary 15394 */ 15395 private int deletePackageX(String packageName, int userId, int deleteFlags) { 15396 final PackageRemovedInfo info = new PackageRemovedInfo(); 15397 final boolean res; 15398 15399 final UserHandle removeForUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 15400 ? UserHandle.ALL : new UserHandle(userId); 15401 15402 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 15403 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 15404 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 15405 } 15406 15407 PackageSetting uninstalledPs = null; 15408 15409 // for the uninstall-updates case and restricted profiles, remember the per- 15410 // user handle installed state 15411 int[] allUsers; 15412 synchronized (mPackages) { 15413 uninstalledPs = mSettings.mPackages.get(packageName); 15414 if (uninstalledPs == null) { 15415 Slog.w(TAG, "Not removing non-existent package " + packageName); 15416 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15417 } 15418 allUsers = sUserManager.getUserIds(); 15419 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 15420 } 15421 15422 synchronized (mInstallLock) { 15423 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 15424 try (PackageFreezer freezer = freezePackageForDelete(packageName, deleteFlags, 15425 "deletePackageX")) { 15426 res = deletePackageLIF(packageName, removeForUser, true, allUsers, 15427 deleteFlags | REMOVE_CHATTY, info, true, null); 15428 } 15429 synchronized (mPackages) { 15430 if (res) { 15431 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 15432 } 15433 } 15434 } 15435 15436 if (res) { 15437 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 15438 info.sendPackageRemovedBroadcasts(killApp); 15439 info.sendSystemPackageUpdatedBroadcasts(); 15440 info.sendSystemPackageAppearedBroadcasts(); 15441 } 15442 // Force a gc here. 15443 Runtime.getRuntime().gc(); 15444 // Delete the resources here after sending the broadcast to let 15445 // other processes clean up before deleting resources. 15446 if (info.args != null) { 15447 synchronized (mInstallLock) { 15448 info.args.doPostDeleteLI(true); 15449 } 15450 } 15451 15452 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15453 } 15454 15455 class PackageRemovedInfo { 15456 String removedPackage; 15457 int uid = -1; 15458 int removedAppId = -1; 15459 int[] origUsers; 15460 int[] removedUsers = null; 15461 boolean isRemovedPackageSystemUpdate = false; 15462 boolean isUpdate; 15463 boolean dataRemoved; 15464 boolean removedForAllUsers; 15465 // Clean up resources deleted packages. 15466 InstallArgs args = null; 15467 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 15468 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 15469 15470 void sendPackageRemovedBroadcasts(boolean killApp) { 15471 sendPackageRemovedBroadcastInternal(killApp); 15472 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 15473 for (int i = 0; i < childCount; i++) { 15474 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15475 childInfo.sendPackageRemovedBroadcastInternal(killApp); 15476 } 15477 } 15478 15479 void sendSystemPackageUpdatedBroadcasts() { 15480 if (isRemovedPackageSystemUpdate) { 15481 sendSystemPackageUpdatedBroadcastsInternal(); 15482 final int childCount = (removedChildPackages != null) 15483 ? removedChildPackages.size() : 0; 15484 for (int i = 0; i < childCount; i++) { 15485 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15486 if (childInfo.isRemovedPackageSystemUpdate) { 15487 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 15488 } 15489 } 15490 } 15491 } 15492 15493 void sendSystemPackageAppearedBroadcasts() { 15494 final int packageCount = (appearedChildPackages != null) 15495 ? appearedChildPackages.size() : 0; 15496 for (int i = 0; i < packageCount; i++) { 15497 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 15498 for (int userId : installedInfo.newUsers) { 15499 sendPackageAddedForUser(installedInfo.name, true, 15500 UserHandle.getAppId(installedInfo.uid), userId); 15501 } 15502 } 15503 } 15504 15505 private void sendSystemPackageUpdatedBroadcastsInternal() { 15506 Bundle extras = new Bundle(2); 15507 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15508 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15509 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 15510 extras, 0, null, null, null); 15511 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 15512 extras, 0, null, null, null); 15513 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 15514 null, 0, removedPackage, null, null); 15515 } 15516 15517 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 15518 Bundle extras = new Bundle(2); 15519 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15520 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 15521 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 15522 if (isUpdate || isRemovedPackageSystemUpdate) { 15523 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15524 } 15525 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 15526 if (removedPackage != null) { 15527 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 15528 extras, 0, null, null, removedUsers); 15529 if (dataRemoved && !isRemovedPackageSystemUpdate) { 15530 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 15531 removedPackage, extras, 0, null, null, removedUsers); 15532 } 15533 } 15534 if (removedAppId >= 0) { 15535 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 15536 removedUsers); 15537 } 15538 } 15539 } 15540 15541 /* 15542 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 15543 * flag is not set, the data directory is removed as well. 15544 * make sure this flag is set for partially installed apps. If not its meaningless to 15545 * delete a partially installed application. 15546 */ 15547 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 15548 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 15549 String packageName = ps.name; 15550 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 15551 // Retrieve object to delete permissions for shared user later on 15552 final PackageParser.Package deletedPkg; 15553 final PackageSetting deletedPs; 15554 // reader 15555 synchronized (mPackages) { 15556 deletedPkg = mPackages.get(packageName); 15557 deletedPs = mSettings.mPackages.get(packageName); 15558 if (outInfo != null) { 15559 outInfo.removedPackage = packageName; 15560 outInfo.removedUsers = deletedPs != null 15561 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 15562 : null; 15563 } 15564 } 15565 15566 removePackageLI(ps, (flags & REMOVE_CHATTY) != 0); 15567 15568 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 15569 final PackageParser.Package resolvedPkg; 15570 if (deletedPkg != null) { 15571 resolvedPkg = deletedPkg; 15572 } else { 15573 // We don't have a parsed package when it lives on an ejected 15574 // adopted storage device, so fake something together 15575 resolvedPkg = new PackageParser.Package(ps.name); 15576 resolvedPkg.setVolumeUuid(ps.volumeUuid); 15577 } 15578 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 15579 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15580 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 15581 if (outInfo != null) { 15582 outInfo.dataRemoved = true; 15583 } 15584 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 15585 } 15586 15587 // writer 15588 synchronized (mPackages) { 15589 if (deletedPs != null) { 15590 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 15591 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 15592 clearDefaultBrowserIfNeeded(packageName); 15593 if (outInfo != null) { 15594 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 15595 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 15596 } 15597 updatePermissionsLPw(deletedPs.name, null, 0); 15598 if (deletedPs.sharedUser != null) { 15599 // Remove permissions associated with package. Since runtime 15600 // permissions are per user we have to kill the removed package 15601 // or packages running under the shared user of the removed 15602 // package if revoking the permissions requested only by the removed 15603 // package is successful and this causes a change in gids. 15604 for (int userId : UserManagerService.getInstance().getUserIds()) { 15605 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 15606 userId); 15607 if (userIdToKill == UserHandle.USER_ALL 15608 || userIdToKill >= UserHandle.USER_SYSTEM) { 15609 // If gids changed for this user, kill all affected packages. 15610 mHandler.post(new Runnable() { 15611 @Override 15612 public void run() { 15613 // This has to happen with no lock held. 15614 killApplication(deletedPs.name, deletedPs.appId, 15615 KILL_APP_REASON_GIDS_CHANGED); 15616 } 15617 }); 15618 break; 15619 } 15620 } 15621 } 15622 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 15623 } 15624 // make sure to preserve per-user disabled state if this removal was just 15625 // a downgrade of a system app to the factory package 15626 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 15627 if (DEBUG_REMOVE) { 15628 Slog.d(TAG, "Propagating install state across downgrade"); 15629 } 15630 for (int userId : allUserHandles) { 15631 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15632 if (DEBUG_REMOVE) { 15633 Slog.d(TAG, " user " + userId + " => " + installed); 15634 } 15635 ps.setInstalled(installed, userId); 15636 } 15637 } 15638 } 15639 // can downgrade to reader 15640 if (writeSettings) { 15641 // Save settings now 15642 mSettings.writeLPr(); 15643 } 15644 } 15645 if (outInfo != null) { 15646 // A user ID was deleted here. Go through all users and remove it 15647 // from KeyStore. 15648 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 15649 } 15650 } 15651 15652 static boolean locationIsPrivileged(File path) { 15653 try { 15654 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 15655 .getCanonicalPath(); 15656 return path.getCanonicalPath().startsWith(privilegedAppDir); 15657 } catch (IOException e) { 15658 Slog.e(TAG, "Unable to access code path " + path); 15659 } 15660 return false; 15661 } 15662 15663 /* 15664 * Tries to delete system package. 15665 */ 15666 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 15667 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 15668 boolean writeSettings) { 15669 if (deletedPs.parentPackageName != null) { 15670 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 15671 return false; 15672 } 15673 15674 final boolean applyUserRestrictions 15675 = (allUserHandles != null) && (outInfo.origUsers != null); 15676 final PackageSetting disabledPs; 15677 // Confirm if the system package has been updated 15678 // An updated system app can be deleted. This will also have to restore 15679 // the system pkg from system partition 15680 // reader 15681 synchronized (mPackages) { 15682 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 15683 } 15684 15685 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 15686 + " disabledPs=" + disabledPs); 15687 15688 if (disabledPs == null) { 15689 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 15690 return false; 15691 } else if (DEBUG_REMOVE) { 15692 Slog.d(TAG, "Deleting system pkg from data partition"); 15693 } 15694 15695 if (DEBUG_REMOVE) { 15696 if (applyUserRestrictions) { 15697 Slog.d(TAG, "Remembering install states:"); 15698 for (int userId : allUserHandles) { 15699 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 15700 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 15701 } 15702 } 15703 } 15704 15705 // Delete the updated package 15706 outInfo.isRemovedPackageSystemUpdate = true; 15707 if (outInfo.removedChildPackages != null) { 15708 final int childCount = (deletedPs.childPackageNames != null) 15709 ? deletedPs.childPackageNames.size() : 0; 15710 for (int i = 0; i < childCount; i++) { 15711 String childPackageName = deletedPs.childPackageNames.get(i); 15712 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 15713 .contains(childPackageName)) { 15714 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15715 childPackageName); 15716 if (childInfo != null) { 15717 childInfo.isRemovedPackageSystemUpdate = true; 15718 } 15719 } 15720 } 15721 } 15722 15723 if (disabledPs.versionCode < deletedPs.versionCode) { 15724 // Delete data for downgrades 15725 flags &= ~PackageManager.DELETE_KEEP_DATA; 15726 } else { 15727 // Preserve data by setting flag 15728 flags |= PackageManager.DELETE_KEEP_DATA; 15729 } 15730 15731 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 15732 outInfo, writeSettings, disabledPs.pkg); 15733 if (!ret) { 15734 return false; 15735 } 15736 15737 // writer 15738 synchronized (mPackages) { 15739 // Reinstate the old system package 15740 enableSystemPackageLPw(disabledPs.pkg); 15741 // Remove any native libraries from the upgraded package. 15742 removeNativeBinariesLI(deletedPs); 15743 } 15744 15745 // Install the system package 15746 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 15747 int parseFlags = mDefParseFlags 15748 | PackageParser.PARSE_MUST_BE_APK 15749 | PackageParser.PARSE_IS_SYSTEM 15750 | PackageParser.PARSE_IS_SYSTEM_DIR; 15751 if (locationIsPrivileged(disabledPs.codePath)) { 15752 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 15753 } 15754 15755 final PackageParser.Package newPkg; 15756 try { 15757 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 15758 } catch (PackageManagerException e) { 15759 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 15760 + e.getMessage()); 15761 return false; 15762 } 15763 15764 prepareAppDataAfterInstallLIF(newPkg); 15765 15766 // writer 15767 synchronized (mPackages) { 15768 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 15769 15770 // Propagate the permissions state as we do not want to drop on the floor 15771 // runtime permissions. The update permissions method below will take 15772 // care of removing obsolete permissions and grant install permissions. 15773 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 15774 updatePermissionsLPw(newPkg.packageName, newPkg, 15775 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 15776 15777 if (applyUserRestrictions) { 15778 if (DEBUG_REMOVE) { 15779 Slog.d(TAG, "Propagating install state across reinstall"); 15780 } 15781 for (int userId : allUserHandles) { 15782 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15783 if (DEBUG_REMOVE) { 15784 Slog.d(TAG, " user " + userId + " => " + installed); 15785 } 15786 ps.setInstalled(installed, userId); 15787 15788 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 15789 } 15790 // Regardless of writeSettings we need to ensure that this restriction 15791 // state propagation is persisted 15792 mSettings.writeAllUsersPackageRestrictionsLPr(); 15793 } 15794 // can downgrade to reader here 15795 if (writeSettings) { 15796 mSettings.writeLPr(); 15797 } 15798 } 15799 return true; 15800 } 15801 15802 private boolean deleteInstalledPackageLIF(PackageSetting ps, 15803 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 15804 PackageRemovedInfo outInfo, boolean writeSettings, 15805 PackageParser.Package replacingPackage) { 15806 synchronized (mPackages) { 15807 if (outInfo != null) { 15808 outInfo.uid = ps.appId; 15809 } 15810 15811 if (outInfo != null && outInfo.removedChildPackages != null) { 15812 final int childCount = (ps.childPackageNames != null) 15813 ? ps.childPackageNames.size() : 0; 15814 for (int i = 0; i < childCount; i++) { 15815 String childPackageName = ps.childPackageNames.get(i); 15816 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 15817 if (childPs == null) { 15818 return false; 15819 } 15820 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15821 childPackageName); 15822 if (childInfo != null) { 15823 childInfo.uid = childPs.appId; 15824 } 15825 } 15826 } 15827 } 15828 15829 // Delete package data from internal structures and also remove data if flag is set 15830 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 15831 15832 // Delete the child packages data 15833 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 15834 for (int i = 0; i < childCount; i++) { 15835 PackageSetting childPs; 15836 synchronized (mPackages) { 15837 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 15838 } 15839 if (childPs != null) { 15840 PackageRemovedInfo childOutInfo = (outInfo != null 15841 && outInfo.removedChildPackages != null) 15842 ? outInfo.removedChildPackages.get(childPs.name) : null; 15843 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 15844 && (replacingPackage != null 15845 && !replacingPackage.hasChildPackage(childPs.name)) 15846 ? flags & ~DELETE_KEEP_DATA : flags; 15847 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 15848 deleteFlags, writeSettings); 15849 } 15850 } 15851 15852 // Delete application code and resources only for parent packages 15853 if (ps.parentPackageName == null) { 15854 if (deleteCodeAndResources && (outInfo != null)) { 15855 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 15856 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 15857 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 15858 } 15859 } 15860 15861 return true; 15862 } 15863 15864 @Override 15865 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 15866 int userId) { 15867 mContext.enforceCallingOrSelfPermission( 15868 android.Manifest.permission.DELETE_PACKAGES, null); 15869 synchronized (mPackages) { 15870 PackageSetting ps = mSettings.mPackages.get(packageName); 15871 if (ps == null) { 15872 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 15873 return false; 15874 } 15875 if (!ps.getInstalled(userId)) { 15876 // Can't block uninstall for an app that is not installed or enabled. 15877 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 15878 return false; 15879 } 15880 ps.setBlockUninstall(blockUninstall, userId); 15881 mSettings.writePackageRestrictionsLPr(userId); 15882 } 15883 return true; 15884 } 15885 15886 @Override 15887 public boolean getBlockUninstallForUser(String packageName, int userId) { 15888 synchronized (mPackages) { 15889 PackageSetting ps = mSettings.mPackages.get(packageName); 15890 if (ps == null) { 15891 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 15892 return false; 15893 } 15894 return ps.getBlockUninstall(userId); 15895 } 15896 } 15897 15898 @Override 15899 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 15900 int callingUid = Binder.getCallingUid(); 15901 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 15902 throw new SecurityException( 15903 "setRequiredForSystemUser can only be run by the system or root"); 15904 } 15905 synchronized (mPackages) { 15906 PackageSetting ps = mSettings.mPackages.get(packageName); 15907 if (ps == null) { 15908 Log.w(TAG, "Package doesn't exist: " + packageName); 15909 return false; 15910 } 15911 if (systemUserApp) { 15912 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15913 } else { 15914 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15915 } 15916 mSettings.writeLPr(); 15917 } 15918 return true; 15919 } 15920 15921 /* 15922 * This method handles package deletion in general 15923 */ 15924 private boolean deletePackageLIF(String packageName, UserHandle user, 15925 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 15926 PackageRemovedInfo outInfo, boolean writeSettings, 15927 PackageParser.Package replacingPackage) { 15928 if (packageName == null) { 15929 Slog.w(TAG, "Attempt to delete null packageName."); 15930 return false; 15931 } 15932 15933 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 15934 15935 PackageSetting ps; 15936 15937 synchronized (mPackages) { 15938 ps = mSettings.mPackages.get(packageName); 15939 if (ps == null) { 15940 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 15941 return false; 15942 } 15943 15944 if (ps.parentPackageName != null && (!isSystemApp(ps) 15945 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 15946 if (DEBUG_REMOVE) { 15947 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 15948 + ((user == null) ? UserHandle.USER_ALL : user)); 15949 } 15950 final int removedUserId = (user != null) ? user.getIdentifier() 15951 : UserHandle.USER_ALL; 15952 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 15953 return false; 15954 } 15955 markPackageUninstalledForUserLPw(ps, user); 15956 scheduleWritePackageRestrictionsLocked(user); 15957 return true; 15958 } 15959 } 15960 15961 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 15962 && user.getIdentifier() != UserHandle.USER_ALL)) { 15963 // The caller is asking that the package only be deleted for a single 15964 // user. To do this, we just mark its uninstalled state and delete 15965 // its data. If this is a system app, we only allow this to happen if 15966 // they have set the special DELETE_SYSTEM_APP which requests different 15967 // semantics than normal for uninstalling system apps. 15968 markPackageUninstalledForUserLPw(ps, user); 15969 15970 if (!isSystemApp(ps)) { 15971 // Do not uninstall the APK if an app should be cached 15972 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 15973 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 15974 // Other user still have this package installed, so all 15975 // we need to do is clear this user's data and save that 15976 // it is uninstalled. 15977 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 15978 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 15979 return false; 15980 } 15981 scheduleWritePackageRestrictionsLocked(user); 15982 return true; 15983 } else { 15984 // We need to set it back to 'installed' so the uninstall 15985 // broadcasts will be sent correctly. 15986 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 15987 ps.setInstalled(true, user.getIdentifier()); 15988 } 15989 } else { 15990 // This is a system app, so we assume that the 15991 // other users still have this package installed, so all 15992 // we need to do is clear this user's data and save that 15993 // it is uninstalled. 15994 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 15995 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 15996 return false; 15997 } 15998 scheduleWritePackageRestrictionsLocked(user); 15999 return true; 16000 } 16001 } 16002 16003 // If we are deleting a composite package for all users, keep track 16004 // of result for each child. 16005 if (ps.childPackageNames != null && outInfo != null) { 16006 synchronized (mPackages) { 16007 final int childCount = ps.childPackageNames.size(); 16008 outInfo.removedChildPackages = new ArrayMap<>(childCount); 16009 for (int i = 0; i < childCount; i++) { 16010 String childPackageName = ps.childPackageNames.get(i); 16011 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 16012 childInfo.removedPackage = childPackageName; 16013 outInfo.removedChildPackages.put(childPackageName, childInfo); 16014 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 16015 if (childPs != null) { 16016 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 16017 } 16018 } 16019 } 16020 } 16021 16022 boolean ret = false; 16023 if (isSystemApp(ps)) { 16024 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 16025 // When an updated system application is deleted we delete the existing resources 16026 // as well and fall back to existing code in system partition 16027 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 16028 } else { 16029 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 16030 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 16031 outInfo, writeSettings, replacingPackage); 16032 } 16033 16034 // Take a note whether we deleted the package for all users 16035 if (outInfo != null) { 16036 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 16037 if (outInfo.removedChildPackages != null) { 16038 synchronized (mPackages) { 16039 final int childCount = outInfo.removedChildPackages.size(); 16040 for (int i = 0; i < childCount; i++) { 16041 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 16042 if (childInfo != null) { 16043 childInfo.removedForAllUsers = mPackages.get( 16044 childInfo.removedPackage) == null; 16045 } 16046 } 16047 } 16048 } 16049 // If we uninstalled an update to a system app there may be some 16050 // child packages that appeared as they are declared in the system 16051 // app but were not declared in the update. 16052 if (isSystemApp(ps)) { 16053 synchronized (mPackages) { 16054 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 16055 final int childCount = (updatedPs.childPackageNames != null) 16056 ? updatedPs.childPackageNames.size() : 0; 16057 for (int i = 0; i < childCount; i++) { 16058 String childPackageName = updatedPs.childPackageNames.get(i); 16059 if (outInfo.removedChildPackages == null 16060 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 16061 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 16062 if (childPs == null) { 16063 continue; 16064 } 16065 PackageInstalledInfo installRes = new PackageInstalledInfo(); 16066 installRes.name = childPackageName; 16067 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 16068 installRes.pkg = mPackages.get(childPackageName); 16069 installRes.uid = childPs.pkg.applicationInfo.uid; 16070 if (outInfo.appearedChildPackages == null) { 16071 outInfo.appearedChildPackages = new ArrayMap<>(); 16072 } 16073 outInfo.appearedChildPackages.put(childPackageName, installRes); 16074 } 16075 } 16076 } 16077 } 16078 } 16079 16080 return ret; 16081 } 16082 16083 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 16084 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 16085 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 16086 for (int nextUserId : userIds) { 16087 if (DEBUG_REMOVE) { 16088 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 16089 } 16090 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 16091 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 16092 false /*hidden*/, false /*suspended*/, null, null, null, 16093 false /*blockUninstall*/, 16094 ps.readUserState(nextUserId).domainVerificationStatus, 0); 16095 } 16096 } 16097 16098 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 16099 PackageRemovedInfo outInfo) { 16100 final PackageParser.Package pkg; 16101 synchronized (mPackages) { 16102 pkg = mPackages.get(ps.name); 16103 } 16104 16105 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 16106 : new int[] {userId}; 16107 for (int nextUserId : userIds) { 16108 if (DEBUG_REMOVE) { 16109 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 16110 + nextUserId); 16111 } 16112 16113 destroyAppDataLIF(pkg, userId, 16114 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16115 destroyAppProfilesLIF(pkg, userId); 16116 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 16117 schedulePackageCleaning(ps.name, nextUserId, false); 16118 synchronized (mPackages) { 16119 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 16120 scheduleWritePackageRestrictionsLocked(nextUserId); 16121 } 16122 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 16123 } 16124 } 16125 16126 if (outInfo != null) { 16127 outInfo.removedPackage = ps.name; 16128 outInfo.removedAppId = ps.appId; 16129 outInfo.removedUsers = userIds; 16130 } 16131 16132 return true; 16133 } 16134 16135 private final class ClearStorageConnection implements ServiceConnection { 16136 IMediaContainerService mContainerService; 16137 16138 @Override 16139 public void onServiceConnected(ComponentName name, IBinder service) { 16140 synchronized (this) { 16141 mContainerService = IMediaContainerService.Stub.asInterface(service); 16142 notifyAll(); 16143 } 16144 } 16145 16146 @Override 16147 public void onServiceDisconnected(ComponentName name) { 16148 } 16149 } 16150 16151 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 16152 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 16153 16154 final boolean mounted; 16155 if (Environment.isExternalStorageEmulated()) { 16156 mounted = true; 16157 } else { 16158 final String status = Environment.getExternalStorageState(); 16159 16160 mounted = status.equals(Environment.MEDIA_MOUNTED) 16161 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 16162 } 16163 16164 if (!mounted) { 16165 return; 16166 } 16167 16168 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 16169 int[] users; 16170 if (userId == UserHandle.USER_ALL) { 16171 users = sUserManager.getUserIds(); 16172 } else { 16173 users = new int[] { userId }; 16174 } 16175 final ClearStorageConnection conn = new ClearStorageConnection(); 16176 if (mContext.bindServiceAsUser( 16177 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 16178 try { 16179 for (int curUser : users) { 16180 long timeout = SystemClock.uptimeMillis() + 5000; 16181 synchronized (conn) { 16182 long now = SystemClock.uptimeMillis(); 16183 while (conn.mContainerService == null && now < timeout) { 16184 try { 16185 conn.wait(timeout - now); 16186 } catch (InterruptedException e) { 16187 } 16188 } 16189 } 16190 if (conn.mContainerService == null) { 16191 return; 16192 } 16193 16194 final UserEnvironment userEnv = new UserEnvironment(curUser); 16195 clearDirectory(conn.mContainerService, 16196 userEnv.buildExternalStorageAppCacheDirs(packageName)); 16197 if (allData) { 16198 clearDirectory(conn.mContainerService, 16199 userEnv.buildExternalStorageAppDataDirs(packageName)); 16200 clearDirectory(conn.mContainerService, 16201 userEnv.buildExternalStorageAppMediaDirs(packageName)); 16202 } 16203 } 16204 } finally { 16205 mContext.unbindService(conn); 16206 } 16207 } 16208 } 16209 16210 @Override 16211 public void clearApplicationProfileData(String packageName) { 16212 enforceSystemOrRoot("Only the system can clear all profile data"); 16213 16214 final PackageParser.Package pkg; 16215 synchronized (mPackages) { 16216 pkg = mPackages.get(packageName); 16217 } 16218 16219 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 16220 synchronized (mInstallLock) { 16221 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 16222 } 16223 } 16224 } 16225 16226 @Override 16227 public void clearApplicationUserData(final String packageName, 16228 final IPackageDataObserver observer, final int userId) { 16229 mContext.enforceCallingOrSelfPermission( 16230 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 16231 16232 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16233 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 16234 16235 final DevicePolicyManagerInternal dpmi = LocalServices 16236 .getService(DevicePolicyManagerInternal.class); 16237 if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) { 16238 throw new SecurityException("Cannot clear data for a device owner or a profile owner"); 16239 } 16240 // Queue up an async operation since the package deletion may take a little while. 16241 mHandler.post(new Runnable() { 16242 public void run() { 16243 mHandler.removeCallbacks(this); 16244 final boolean succeeded; 16245 try (PackageFreezer freezer = freezePackage(packageName, 16246 "clearApplicationUserData")) { 16247 synchronized (mInstallLock) { 16248 succeeded = clearApplicationUserDataLIF(packageName, userId); 16249 } 16250 clearExternalStorageDataSync(packageName, userId, true); 16251 } 16252 if (succeeded) { 16253 // invoke DeviceStorageMonitor's update method to clear any notifications 16254 DeviceStorageMonitorInternal dsm = LocalServices 16255 .getService(DeviceStorageMonitorInternal.class); 16256 if (dsm != null) { 16257 dsm.checkMemory(); 16258 } 16259 } 16260 if(observer != null) { 16261 try { 16262 observer.onRemoveCompleted(packageName, succeeded); 16263 } catch (RemoteException e) { 16264 Log.i(TAG, "Observer no longer exists."); 16265 } 16266 } //end if observer 16267 } //end run 16268 }); 16269 } 16270 16271 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 16272 if (packageName == null) { 16273 Slog.w(TAG, "Attempt to delete null packageName."); 16274 return false; 16275 } 16276 16277 // Try finding details about the requested package 16278 PackageParser.Package pkg; 16279 synchronized (mPackages) { 16280 pkg = mPackages.get(packageName); 16281 if (pkg == null) { 16282 final PackageSetting ps = mSettings.mPackages.get(packageName); 16283 if (ps != null) { 16284 pkg = ps.pkg; 16285 } 16286 } 16287 16288 if (pkg == null) { 16289 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16290 return false; 16291 } 16292 16293 PackageSetting ps = (PackageSetting) pkg.mExtras; 16294 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16295 } 16296 16297 clearAppDataLIF(pkg, userId, 16298 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16299 16300 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16301 removeKeystoreDataIfNeeded(userId, appId); 16302 16303 final UserManager um = mContext.getSystemService(UserManager.class); 16304 final int flags; 16305 if (um.isUserUnlockingOrUnlocked(userId)) { 16306 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 16307 } else if (um.isUserRunning(userId)) { 16308 flags = StorageManager.FLAG_STORAGE_DE; 16309 } else { 16310 flags = 0; 16311 } 16312 prepareAppDataContentsLIF(pkg, userId, flags); 16313 16314 return true; 16315 } 16316 16317 /** 16318 * Reverts user permission state changes (permissions and flags) in 16319 * all packages for a given user. 16320 * 16321 * @param userId The device user for which to do a reset. 16322 */ 16323 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 16324 final int packageCount = mPackages.size(); 16325 for (int i = 0; i < packageCount; i++) { 16326 PackageParser.Package pkg = mPackages.valueAt(i); 16327 PackageSetting ps = (PackageSetting) pkg.mExtras; 16328 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16329 } 16330 } 16331 16332 private void resetNetworkPolicies(int userId) { 16333 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 16334 } 16335 16336 /** 16337 * Reverts user permission state changes (permissions and flags). 16338 * 16339 * @param ps The package for which to reset. 16340 * @param userId The device user for which to do a reset. 16341 */ 16342 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 16343 final PackageSetting ps, final int userId) { 16344 if (ps.pkg == null) { 16345 return; 16346 } 16347 16348 // These are flags that can change base on user actions. 16349 final int userSettableMask = FLAG_PERMISSION_USER_SET 16350 | FLAG_PERMISSION_USER_FIXED 16351 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 16352 | FLAG_PERMISSION_REVIEW_REQUIRED; 16353 16354 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 16355 | FLAG_PERMISSION_POLICY_FIXED; 16356 16357 boolean writeInstallPermissions = false; 16358 boolean writeRuntimePermissions = false; 16359 16360 final int permissionCount = ps.pkg.requestedPermissions.size(); 16361 for (int i = 0; i < permissionCount; i++) { 16362 String permission = ps.pkg.requestedPermissions.get(i); 16363 16364 BasePermission bp = mSettings.mPermissions.get(permission); 16365 if (bp == null) { 16366 continue; 16367 } 16368 16369 // If shared user we just reset the state to which only this app contributed. 16370 if (ps.sharedUser != null) { 16371 boolean used = false; 16372 final int packageCount = ps.sharedUser.packages.size(); 16373 for (int j = 0; j < packageCount; j++) { 16374 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 16375 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 16376 && pkg.pkg.requestedPermissions.contains(permission)) { 16377 used = true; 16378 break; 16379 } 16380 } 16381 if (used) { 16382 continue; 16383 } 16384 } 16385 16386 PermissionsState permissionsState = ps.getPermissionsState(); 16387 16388 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 16389 16390 // Always clear the user settable flags. 16391 final boolean hasInstallState = permissionsState.getInstallPermissionState( 16392 bp.name) != null; 16393 // If permission review is enabled and this is a legacy app, mark the 16394 // permission as requiring a review as this is the initial state. 16395 int flags = 0; 16396 if (Build.PERMISSIONS_REVIEW_REQUIRED 16397 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 16398 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 16399 } 16400 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 16401 if (hasInstallState) { 16402 writeInstallPermissions = true; 16403 } else { 16404 writeRuntimePermissions = true; 16405 } 16406 } 16407 16408 // Below is only runtime permission handling. 16409 if (!bp.isRuntime()) { 16410 continue; 16411 } 16412 16413 // Never clobber system or policy. 16414 if ((oldFlags & policyOrSystemFlags) != 0) { 16415 continue; 16416 } 16417 16418 // If this permission was granted by default, make sure it is. 16419 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 16420 if (permissionsState.grantRuntimePermission(bp, userId) 16421 != PERMISSION_OPERATION_FAILURE) { 16422 writeRuntimePermissions = true; 16423 } 16424 // If permission review is enabled the permissions for a legacy apps 16425 // are represented as constantly granted runtime ones, so don't revoke. 16426 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 16427 // Otherwise, reset the permission. 16428 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 16429 switch (revokeResult) { 16430 case PERMISSION_OPERATION_SUCCESS: 16431 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 16432 writeRuntimePermissions = true; 16433 final int appId = ps.appId; 16434 mHandler.post(new Runnable() { 16435 @Override 16436 public void run() { 16437 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 16438 } 16439 }); 16440 } break; 16441 } 16442 } 16443 } 16444 16445 // Synchronously write as we are taking permissions away. 16446 if (writeRuntimePermissions) { 16447 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 16448 } 16449 16450 // Synchronously write as we are taking permissions away. 16451 if (writeInstallPermissions) { 16452 mSettings.writeLPr(); 16453 } 16454 } 16455 16456 /** 16457 * Remove entries from the keystore daemon. Will only remove it if the 16458 * {@code appId} is valid. 16459 */ 16460 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 16461 if (appId < 0) { 16462 return; 16463 } 16464 16465 final KeyStore keyStore = KeyStore.getInstance(); 16466 if (keyStore != null) { 16467 if (userId == UserHandle.USER_ALL) { 16468 for (final int individual : sUserManager.getUserIds()) { 16469 keyStore.clearUid(UserHandle.getUid(individual, appId)); 16470 } 16471 } else { 16472 keyStore.clearUid(UserHandle.getUid(userId, appId)); 16473 } 16474 } else { 16475 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 16476 } 16477 } 16478 16479 @Override 16480 public void deleteApplicationCacheFiles(final String packageName, 16481 final IPackageDataObserver observer) { 16482 final int userId = UserHandle.getCallingUserId(); 16483 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 16484 } 16485 16486 @Override 16487 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 16488 final IPackageDataObserver observer) { 16489 mContext.enforceCallingOrSelfPermission( 16490 android.Manifest.permission.DELETE_CACHE_FILES, null); 16491 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16492 /* requireFullPermission= */ true, /* checkShell= */ false, 16493 "delete application cache files"); 16494 16495 final PackageParser.Package pkg; 16496 synchronized (mPackages) { 16497 pkg = mPackages.get(packageName); 16498 } 16499 16500 // Queue up an async operation since the package deletion may take a little while. 16501 mHandler.post(new Runnable() { 16502 public void run() { 16503 synchronized (mInstallLock) { 16504 final int flags = StorageManager.FLAG_STORAGE_DE 16505 | StorageManager.FLAG_STORAGE_CE; 16506 // We're only clearing cache files, so we don't care if the 16507 // app is unfrozen and still able to run 16508 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 16509 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16510 } 16511 clearExternalStorageDataSync(packageName, userId, false); 16512 if (observer != null) { 16513 try { 16514 observer.onRemoveCompleted(packageName, true); 16515 } catch (RemoteException e) { 16516 Log.i(TAG, "Observer no longer exists."); 16517 } 16518 } 16519 } 16520 }); 16521 } 16522 16523 @Override 16524 public void getPackageSizeInfo(final String packageName, int userHandle, 16525 final IPackageStatsObserver observer) { 16526 mContext.enforceCallingOrSelfPermission( 16527 android.Manifest.permission.GET_PACKAGE_SIZE, null); 16528 if (packageName == null) { 16529 throw new IllegalArgumentException("Attempt to get size of null packageName"); 16530 } 16531 16532 PackageStats stats = new PackageStats(packageName, userHandle); 16533 16534 /* 16535 * Queue up an async operation since the package measurement may take a 16536 * little while. 16537 */ 16538 Message msg = mHandler.obtainMessage(INIT_COPY); 16539 msg.obj = new MeasureParams(stats, observer); 16540 mHandler.sendMessage(msg); 16541 } 16542 16543 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 16544 final PackageSetting ps; 16545 synchronized (mPackages) { 16546 ps = mSettings.mPackages.get(packageName); 16547 if (ps == null) { 16548 Slog.w(TAG, "Failed to find settings for " + packageName); 16549 return false; 16550 } 16551 } 16552 try { 16553 mInstaller.getAppSize(ps.volumeUuid, packageName, userId, 16554 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 16555 ps.getCeDataInode(userId), ps.codePathString, stats); 16556 } catch (InstallerException e) { 16557 Slog.w(TAG, String.valueOf(e)); 16558 return false; 16559 } 16560 16561 // For now, ignore code size of packages on system partition 16562 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 16563 stats.codeSize = 0; 16564 } 16565 16566 return true; 16567 } 16568 16569 private int getUidTargetSdkVersionLockedLPr(int uid) { 16570 Object obj = mSettings.getUserIdLPr(uid); 16571 if (obj instanceof SharedUserSetting) { 16572 final SharedUserSetting sus = (SharedUserSetting) obj; 16573 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 16574 final Iterator<PackageSetting> it = sus.packages.iterator(); 16575 while (it.hasNext()) { 16576 final PackageSetting ps = it.next(); 16577 if (ps.pkg != null) { 16578 int v = ps.pkg.applicationInfo.targetSdkVersion; 16579 if (v < vers) vers = v; 16580 } 16581 } 16582 return vers; 16583 } else if (obj instanceof PackageSetting) { 16584 final PackageSetting ps = (PackageSetting) obj; 16585 if (ps.pkg != null) { 16586 return ps.pkg.applicationInfo.targetSdkVersion; 16587 } 16588 } 16589 return Build.VERSION_CODES.CUR_DEVELOPMENT; 16590 } 16591 16592 @Override 16593 public void addPreferredActivity(IntentFilter filter, int match, 16594 ComponentName[] set, ComponentName activity, int userId) { 16595 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16596 "Adding preferred"); 16597 } 16598 16599 private void addPreferredActivityInternal(IntentFilter filter, int match, 16600 ComponentName[] set, ComponentName activity, boolean always, int userId, 16601 String opname) { 16602 // writer 16603 int callingUid = Binder.getCallingUid(); 16604 enforceCrossUserPermission(callingUid, userId, 16605 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 16606 if (filter.countActions() == 0) { 16607 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16608 return; 16609 } 16610 synchronized (mPackages) { 16611 if (mContext.checkCallingOrSelfPermission( 16612 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16613 != PackageManager.PERMISSION_GRANTED) { 16614 if (getUidTargetSdkVersionLockedLPr(callingUid) 16615 < Build.VERSION_CODES.FROYO) { 16616 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 16617 + callingUid); 16618 return; 16619 } 16620 mContext.enforceCallingOrSelfPermission( 16621 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16622 } 16623 16624 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 16625 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 16626 + userId + ":"); 16627 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16628 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 16629 scheduleWritePackageRestrictionsLocked(userId); 16630 } 16631 } 16632 16633 @Override 16634 public void replacePreferredActivity(IntentFilter filter, int match, 16635 ComponentName[] set, ComponentName activity, int userId) { 16636 if (filter.countActions() != 1) { 16637 throw new IllegalArgumentException( 16638 "replacePreferredActivity expects filter to have only 1 action."); 16639 } 16640 if (filter.countDataAuthorities() != 0 16641 || filter.countDataPaths() != 0 16642 || filter.countDataSchemes() > 1 16643 || filter.countDataTypes() != 0) { 16644 throw new IllegalArgumentException( 16645 "replacePreferredActivity expects filter to have no data authorities, " + 16646 "paths, or types; and at most one scheme."); 16647 } 16648 16649 final int callingUid = Binder.getCallingUid(); 16650 enforceCrossUserPermission(callingUid, userId, 16651 true /* requireFullPermission */, false /* checkShell */, 16652 "replace preferred activity"); 16653 synchronized (mPackages) { 16654 if (mContext.checkCallingOrSelfPermission( 16655 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16656 != PackageManager.PERMISSION_GRANTED) { 16657 if (getUidTargetSdkVersionLockedLPr(callingUid) 16658 < Build.VERSION_CODES.FROYO) { 16659 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 16660 + Binder.getCallingUid()); 16661 return; 16662 } 16663 mContext.enforceCallingOrSelfPermission( 16664 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16665 } 16666 16667 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16668 if (pir != null) { 16669 // Get all of the existing entries that exactly match this filter. 16670 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 16671 if (existing != null && existing.size() == 1) { 16672 PreferredActivity cur = existing.get(0); 16673 if (DEBUG_PREFERRED) { 16674 Slog.i(TAG, "Checking replace of preferred:"); 16675 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16676 if (!cur.mPref.mAlways) { 16677 Slog.i(TAG, " -- CUR; not mAlways!"); 16678 } else { 16679 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 16680 Slog.i(TAG, " -- CUR: mSet=" 16681 + Arrays.toString(cur.mPref.mSetComponents)); 16682 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 16683 Slog.i(TAG, " -- NEW: mMatch=" 16684 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 16685 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 16686 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 16687 } 16688 } 16689 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 16690 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 16691 && cur.mPref.sameSet(set)) { 16692 // Setting the preferred activity to what it happens to be already 16693 if (DEBUG_PREFERRED) { 16694 Slog.i(TAG, "Replacing with same preferred activity " 16695 + cur.mPref.mShortComponent + " for user " 16696 + userId + ":"); 16697 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16698 } 16699 return; 16700 } 16701 } 16702 16703 if (existing != null) { 16704 if (DEBUG_PREFERRED) { 16705 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 16706 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16707 } 16708 for (int i = 0; i < existing.size(); i++) { 16709 PreferredActivity pa = existing.get(i); 16710 if (DEBUG_PREFERRED) { 16711 Slog.i(TAG, "Removing existing preferred activity " 16712 + pa.mPref.mComponent + ":"); 16713 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 16714 } 16715 pir.removeFilter(pa); 16716 } 16717 } 16718 } 16719 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16720 "Replacing preferred"); 16721 } 16722 } 16723 16724 @Override 16725 public void clearPackagePreferredActivities(String packageName) { 16726 final int uid = Binder.getCallingUid(); 16727 // writer 16728 synchronized (mPackages) { 16729 PackageParser.Package pkg = mPackages.get(packageName); 16730 if (pkg == null || pkg.applicationInfo.uid != uid) { 16731 if (mContext.checkCallingOrSelfPermission( 16732 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16733 != PackageManager.PERMISSION_GRANTED) { 16734 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 16735 < Build.VERSION_CODES.FROYO) { 16736 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 16737 + Binder.getCallingUid()); 16738 return; 16739 } 16740 mContext.enforceCallingOrSelfPermission( 16741 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16742 } 16743 } 16744 16745 int user = UserHandle.getCallingUserId(); 16746 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 16747 scheduleWritePackageRestrictionsLocked(user); 16748 } 16749 } 16750 } 16751 16752 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16753 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 16754 ArrayList<PreferredActivity> removed = null; 16755 boolean changed = false; 16756 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16757 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 16758 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16759 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 16760 continue; 16761 } 16762 Iterator<PreferredActivity> it = pir.filterIterator(); 16763 while (it.hasNext()) { 16764 PreferredActivity pa = it.next(); 16765 // Mark entry for removal only if it matches the package name 16766 // and the entry is of type "always". 16767 if (packageName == null || 16768 (pa.mPref.mComponent.getPackageName().equals(packageName) 16769 && pa.mPref.mAlways)) { 16770 if (removed == null) { 16771 removed = new ArrayList<PreferredActivity>(); 16772 } 16773 removed.add(pa); 16774 } 16775 } 16776 if (removed != null) { 16777 for (int j=0; j<removed.size(); j++) { 16778 PreferredActivity pa = removed.get(j); 16779 pir.removeFilter(pa); 16780 } 16781 changed = true; 16782 } 16783 } 16784 return changed; 16785 } 16786 16787 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16788 private void clearIntentFilterVerificationsLPw(int userId) { 16789 final int packageCount = mPackages.size(); 16790 for (int i = 0; i < packageCount; i++) { 16791 PackageParser.Package pkg = mPackages.valueAt(i); 16792 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 16793 } 16794 } 16795 16796 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16797 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 16798 if (userId == UserHandle.USER_ALL) { 16799 if (mSettings.removeIntentFilterVerificationLPw(packageName, 16800 sUserManager.getUserIds())) { 16801 for (int oneUserId : sUserManager.getUserIds()) { 16802 scheduleWritePackageRestrictionsLocked(oneUserId); 16803 } 16804 } 16805 } else { 16806 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 16807 scheduleWritePackageRestrictionsLocked(userId); 16808 } 16809 } 16810 } 16811 16812 void clearDefaultBrowserIfNeeded(String packageName) { 16813 for (int oneUserId : sUserManager.getUserIds()) { 16814 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 16815 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 16816 if (packageName.equals(defaultBrowserPackageName)) { 16817 setDefaultBrowserPackageName(null, oneUserId); 16818 } 16819 } 16820 } 16821 16822 @Override 16823 public void resetApplicationPreferences(int userId) { 16824 mContext.enforceCallingOrSelfPermission( 16825 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16826 final long identity = Binder.clearCallingIdentity(); 16827 // writer 16828 try { 16829 synchronized (mPackages) { 16830 clearPackagePreferredActivitiesLPw(null, userId); 16831 mSettings.applyDefaultPreferredAppsLPw(this, userId); 16832 // TODO: We have to reset the default SMS and Phone. This requires 16833 // significant refactoring to keep all default apps in the package 16834 // manager (cleaner but more work) or have the services provide 16835 // callbacks to the package manager to request a default app reset. 16836 applyFactoryDefaultBrowserLPw(userId); 16837 clearIntentFilterVerificationsLPw(userId); 16838 primeDomainVerificationsLPw(userId); 16839 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 16840 scheduleWritePackageRestrictionsLocked(userId); 16841 } 16842 resetNetworkPolicies(userId); 16843 } finally { 16844 Binder.restoreCallingIdentity(identity); 16845 } 16846 } 16847 16848 @Override 16849 public int getPreferredActivities(List<IntentFilter> outFilters, 16850 List<ComponentName> outActivities, String packageName) { 16851 16852 int num = 0; 16853 final int userId = UserHandle.getCallingUserId(); 16854 // reader 16855 synchronized (mPackages) { 16856 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16857 if (pir != null) { 16858 final Iterator<PreferredActivity> it = pir.filterIterator(); 16859 while (it.hasNext()) { 16860 final PreferredActivity pa = it.next(); 16861 if (packageName == null 16862 || (pa.mPref.mComponent.getPackageName().equals(packageName) 16863 && pa.mPref.mAlways)) { 16864 if (outFilters != null) { 16865 outFilters.add(new IntentFilter(pa)); 16866 } 16867 if (outActivities != null) { 16868 outActivities.add(pa.mPref.mComponent); 16869 } 16870 } 16871 } 16872 } 16873 } 16874 16875 return num; 16876 } 16877 16878 @Override 16879 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 16880 int userId) { 16881 int callingUid = Binder.getCallingUid(); 16882 if (callingUid != Process.SYSTEM_UID) { 16883 throw new SecurityException( 16884 "addPersistentPreferredActivity can only be run by the system"); 16885 } 16886 if (filter.countActions() == 0) { 16887 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16888 return; 16889 } 16890 synchronized (mPackages) { 16891 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 16892 ":"); 16893 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16894 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 16895 new PersistentPreferredActivity(filter, activity)); 16896 scheduleWritePackageRestrictionsLocked(userId); 16897 } 16898 } 16899 16900 @Override 16901 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 16902 int callingUid = Binder.getCallingUid(); 16903 if (callingUid != Process.SYSTEM_UID) { 16904 throw new SecurityException( 16905 "clearPackagePersistentPreferredActivities can only be run by the system"); 16906 } 16907 ArrayList<PersistentPreferredActivity> removed = null; 16908 boolean changed = false; 16909 synchronized (mPackages) { 16910 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 16911 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 16912 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 16913 .valueAt(i); 16914 if (userId != thisUserId) { 16915 continue; 16916 } 16917 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 16918 while (it.hasNext()) { 16919 PersistentPreferredActivity ppa = it.next(); 16920 // Mark entry for removal only if it matches the package name. 16921 if (ppa.mComponent.getPackageName().equals(packageName)) { 16922 if (removed == null) { 16923 removed = new ArrayList<PersistentPreferredActivity>(); 16924 } 16925 removed.add(ppa); 16926 } 16927 } 16928 if (removed != null) { 16929 for (int j=0; j<removed.size(); j++) { 16930 PersistentPreferredActivity ppa = removed.get(j); 16931 ppir.removeFilter(ppa); 16932 } 16933 changed = true; 16934 } 16935 } 16936 16937 if (changed) { 16938 scheduleWritePackageRestrictionsLocked(userId); 16939 } 16940 } 16941 } 16942 16943 /** 16944 * Common machinery for picking apart a restored XML blob and passing 16945 * it to a caller-supplied functor to be applied to the running system. 16946 */ 16947 private void restoreFromXml(XmlPullParser parser, int userId, 16948 String expectedStartTag, BlobXmlRestorer functor) 16949 throws IOException, XmlPullParserException { 16950 int type; 16951 while ((type = parser.next()) != XmlPullParser.START_TAG 16952 && type != XmlPullParser.END_DOCUMENT) { 16953 } 16954 if (type != XmlPullParser.START_TAG) { 16955 // oops didn't find a start tag?! 16956 if (DEBUG_BACKUP) { 16957 Slog.e(TAG, "Didn't find start tag during restore"); 16958 } 16959 return; 16960 } 16961Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 16962 // this is supposed to be TAG_PREFERRED_BACKUP 16963 if (!expectedStartTag.equals(parser.getName())) { 16964 if (DEBUG_BACKUP) { 16965 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 16966 } 16967 return; 16968 } 16969 16970 // skip interfering stuff, then we're aligned with the backing implementation 16971 while ((type = parser.next()) == XmlPullParser.TEXT) { } 16972Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 16973 functor.apply(parser, userId); 16974 } 16975 16976 private interface BlobXmlRestorer { 16977 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 16978 } 16979 16980 /** 16981 * Non-Binder method, support for the backup/restore mechanism: write the 16982 * full set of preferred activities in its canonical XML format. Returns the 16983 * XML output as a byte array, or null if there is none. 16984 */ 16985 @Override 16986 public byte[] getPreferredActivityBackup(int userId) { 16987 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16988 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 16989 } 16990 16991 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16992 try { 16993 final XmlSerializer serializer = new FastXmlSerializer(); 16994 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16995 serializer.startDocument(null, true); 16996 serializer.startTag(null, TAG_PREFERRED_BACKUP); 16997 16998 synchronized (mPackages) { 16999 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 17000 } 17001 17002 serializer.endTag(null, TAG_PREFERRED_BACKUP); 17003 serializer.endDocument(); 17004 serializer.flush(); 17005 } catch (Exception e) { 17006 if (DEBUG_BACKUP) { 17007 Slog.e(TAG, "Unable to write preferred activities for backup", e); 17008 } 17009 return null; 17010 } 17011 17012 return dataStream.toByteArray(); 17013 } 17014 17015 @Override 17016 public void restorePreferredActivities(byte[] backup, int userId) { 17017 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17018 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17019 } 17020 17021 try { 17022 final XmlPullParser parser = Xml.newPullParser(); 17023 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17024 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 17025 new BlobXmlRestorer() { 17026 @Override 17027 public void apply(XmlPullParser parser, int userId) 17028 throws XmlPullParserException, IOException { 17029 synchronized (mPackages) { 17030 mSettings.readPreferredActivitiesLPw(parser, userId); 17031 } 17032 } 17033 } ); 17034 } catch (Exception e) { 17035 if (DEBUG_BACKUP) { 17036 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17037 } 17038 } 17039 } 17040 17041 /** 17042 * Non-Binder method, support for the backup/restore mechanism: write the 17043 * default browser (etc) settings in its canonical XML format. Returns the default 17044 * browser XML representation as a byte array, or null if there is none. 17045 */ 17046 @Override 17047 public byte[] getDefaultAppsBackup(int userId) { 17048 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17049 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 17050 } 17051 17052 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17053 try { 17054 final XmlSerializer serializer = new FastXmlSerializer(); 17055 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17056 serializer.startDocument(null, true); 17057 serializer.startTag(null, TAG_DEFAULT_APPS); 17058 17059 synchronized (mPackages) { 17060 mSettings.writeDefaultAppsLPr(serializer, userId); 17061 } 17062 17063 serializer.endTag(null, TAG_DEFAULT_APPS); 17064 serializer.endDocument(); 17065 serializer.flush(); 17066 } catch (Exception e) { 17067 if (DEBUG_BACKUP) { 17068 Slog.e(TAG, "Unable to write default apps for backup", e); 17069 } 17070 return null; 17071 } 17072 17073 return dataStream.toByteArray(); 17074 } 17075 17076 @Override 17077 public void restoreDefaultApps(byte[] backup, int userId) { 17078 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17079 throw new SecurityException("Only the system may call restoreDefaultApps()"); 17080 } 17081 17082 try { 17083 final XmlPullParser parser = Xml.newPullParser(); 17084 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17085 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 17086 new BlobXmlRestorer() { 17087 @Override 17088 public void apply(XmlPullParser parser, int userId) 17089 throws XmlPullParserException, IOException { 17090 synchronized (mPackages) { 17091 mSettings.readDefaultAppsLPw(parser, userId); 17092 } 17093 } 17094 } ); 17095 } catch (Exception e) { 17096 if (DEBUG_BACKUP) { 17097 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 17098 } 17099 } 17100 } 17101 17102 @Override 17103 public byte[] getIntentFilterVerificationBackup(int userId) { 17104 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17105 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 17106 } 17107 17108 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17109 try { 17110 final XmlSerializer serializer = new FastXmlSerializer(); 17111 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17112 serializer.startDocument(null, true); 17113 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 17114 17115 synchronized (mPackages) { 17116 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 17117 } 17118 17119 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 17120 serializer.endDocument(); 17121 serializer.flush(); 17122 } catch (Exception e) { 17123 if (DEBUG_BACKUP) { 17124 Slog.e(TAG, "Unable to write default apps for backup", e); 17125 } 17126 return null; 17127 } 17128 17129 return dataStream.toByteArray(); 17130 } 17131 17132 @Override 17133 public void restoreIntentFilterVerification(byte[] backup, int userId) { 17134 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17135 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17136 } 17137 17138 try { 17139 final XmlPullParser parser = Xml.newPullParser(); 17140 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17141 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 17142 new BlobXmlRestorer() { 17143 @Override 17144 public void apply(XmlPullParser parser, int userId) 17145 throws XmlPullParserException, IOException { 17146 synchronized (mPackages) { 17147 mSettings.readAllDomainVerificationsLPr(parser, userId); 17148 mSettings.writeLPr(); 17149 } 17150 } 17151 } ); 17152 } catch (Exception e) { 17153 if (DEBUG_BACKUP) { 17154 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17155 } 17156 } 17157 } 17158 17159 @Override 17160 public byte[] getPermissionGrantBackup(int userId) { 17161 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17162 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 17163 } 17164 17165 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17166 try { 17167 final XmlSerializer serializer = new FastXmlSerializer(); 17168 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17169 serializer.startDocument(null, true); 17170 serializer.startTag(null, TAG_PERMISSION_BACKUP); 17171 17172 synchronized (mPackages) { 17173 serializeRuntimePermissionGrantsLPr(serializer, userId); 17174 } 17175 17176 serializer.endTag(null, TAG_PERMISSION_BACKUP); 17177 serializer.endDocument(); 17178 serializer.flush(); 17179 } catch (Exception e) { 17180 if (DEBUG_BACKUP) { 17181 Slog.e(TAG, "Unable to write default apps for backup", e); 17182 } 17183 return null; 17184 } 17185 17186 return dataStream.toByteArray(); 17187 } 17188 17189 @Override 17190 public void restorePermissionGrants(byte[] backup, int userId) { 17191 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17192 throw new SecurityException("Only the system may call restorePermissionGrants()"); 17193 } 17194 17195 try { 17196 final XmlPullParser parser = Xml.newPullParser(); 17197 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17198 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 17199 new BlobXmlRestorer() { 17200 @Override 17201 public void apply(XmlPullParser parser, int userId) 17202 throws XmlPullParserException, IOException { 17203 synchronized (mPackages) { 17204 processRestoredPermissionGrantsLPr(parser, userId); 17205 } 17206 } 17207 } ); 17208 } catch (Exception e) { 17209 if (DEBUG_BACKUP) { 17210 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17211 } 17212 } 17213 } 17214 17215 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 17216 throws IOException { 17217 serializer.startTag(null, TAG_ALL_GRANTS); 17218 17219 final int N = mSettings.mPackages.size(); 17220 for (int i = 0; i < N; i++) { 17221 final PackageSetting ps = mSettings.mPackages.valueAt(i); 17222 boolean pkgGrantsKnown = false; 17223 17224 PermissionsState packagePerms = ps.getPermissionsState(); 17225 17226 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 17227 final int grantFlags = state.getFlags(); 17228 // only look at grants that are not system/policy fixed 17229 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 17230 final boolean isGranted = state.isGranted(); 17231 // And only back up the user-twiddled state bits 17232 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 17233 final String packageName = mSettings.mPackages.keyAt(i); 17234 if (!pkgGrantsKnown) { 17235 serializer.startTag(null, TAG_GRANT); 17236 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 17237 pkgGrantsKnown = true; 17238 } 17239 17240 final boolean userSet = 17241 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 17242 final boolean userFixed = 17243 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 17244 final boolean revoke = 17245 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 17246 17247 serializer.startTag(null, TAG_PERMISSION); 17248 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 17249 if (isGranted) { 17250 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 17251 } 17252 if (userSet) { 17253 serializer.attribute(null, ATTR_USER_SET, "true"); 17254 } 17255 if (userFixed) { 17256 serializer.attribute(null, ATTR_USER_FIXED, "true"); 17257 } 17258 if (revoke) { 17259 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 17260 } 17261 serializer.endTag(null, TAG_PERMISSION); 17262 } 17263 } 17264 } 17265 17266 if (pkgGrantsKnown) { 17267 serializer.endTag(null, TAG_GRANT); 17268 } 17269 } 17270 17271 serializer.endTag(null, TAG_ALL_GRANTS); 17272 } 17273 17274 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 17275 throws XmlPullParserException, IOException { 17276 String pkgName = null; 17277 int outerDepth = parser.getDepth(); 17278 int type; 17279 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 17280 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 17281 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 17282 continue; 17283 } 17284 17285 final String tagName = parser.getName(); 17286 if (tagName.equals(TAG_GRANT)) { 17287 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 17288 if (DEBUG_BACKUP) { 17289 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 17290 } 17291 } else if (tagName.equals(TAG_PERMISSION)) { 17292 17293 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 17294 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 17295 17296 int newFlagSet = 0; 17297 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 17298 newFlagSet |= FLAG_PERMISSION_USER_SET; 17299 } 17300 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 17301 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 17302 } 17303 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 17304 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 17305 } 17306 if (DEBUG_BACKUP) { 17307 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 17308 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 17309 } 17310 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17311 if (ps != null) { 17312 // Already installed so we apply the grant immediately 17313 if (DEBUG_BACKUP) { 17314 Slog.v(TAG, " + already installed; applying"); 17315 } 17316 PermissionsState perms = ps.getPermissionsState(); 17317 BasePermission bp = mSettings.mPermissions.get(permName); 17318 if (bp != null) { 17319 if (isGranted) { 17320 perms.grantRuntimePermission(bp, userId); 17321 } 17322 if (newFlagSet != 0) { 17323 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 17324 } 17325 } 17326 } else { 17327 // Need to wait for post-restore install to apply the grant 17328 if (DEBUG_BACKUP) { 17329 Slog.v(TAG, " - not yet installed; saving for later"); 17330 } 17331 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 17332 isGranted, newFlagSet, userId); 17333 } 17334 } else { 17335 PackageManagerService.reportSettingsProblem(Log.WARN, 17336 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 17337 XmlUtils.skipCurrentTag(parser); 17338 } 17339 } 17340 17341 scheduleWriteSettingsLocked(); 17342 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 17343 } 17344 17345 @Override 17346 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 17347 int sourceUserId, int targetUserId, int flags) { 17348 mContext.enforceCallingOrSelfPermission( 17349 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17350 int callingUid = Binder.getCallingUid(); 17351 enforceOwnerRights(ownerPackage, callingUid); 17352 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17353 if (intentFilter.countActions() == 0) { 17354 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 17355 return; 17356 } 17357 synchronized (mPackages) { 17358 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 17359 ownerPackage, targetUserId, flags); 17360 CrossProfileIntentResolver resolver = 17361 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17362 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 17363 // We have all those whose filter is equal. Now checking if the rest is equal as well. 17364 if (existing != null) { 17365 int size = existing.size(); 17366 for (int i = 0; i < size; i++) { 17367 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 17368 return; 17369 } 17370 } 17371 } 17372 resolver.addFilter(newFilter); 17373 scheduleWritePackageRestrictionsLocked(sourceUserId); 17374 } 17375 } 17376 17377 @Override 17378 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 17379 mContext.enforceCallingOrSelfPermission( 17380 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17381 int callingUid = Binder.getCallingUid(); 17382 enforceOwnerRights(ownerPackage, callingUid); 17383 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17384 synchronized (mPackages) { 17385 CrossProfileIntentResolver resolver = 17386 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17387 ArraySet<CrossProfileIntentFilter> set = 17388 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 17389 for (CrossProfileIntentFilter filter : set) { 17390 if (filter.getOwnerPackage().equals(ownerPackage)) { 17391 resolver.removeFilter(filter); 17392 } 17393 } 17394 scheduleWritePackageRestrictionsLocked(sourceUserId); 17395 } 17396 } 17397 17398 // Enforcing that callingUid is owning pkg on userId 17399 private void enforceOwnerRights(String pkg, int callingUid) { 17400 // The system owns everything. 17401 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 17402 return; 17403 } 17404 int callingUserId = UserHandle.getUserId(callingUid); 17405 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 17406 if (pi == null) { 17407 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 17408 + callingUserId); 17409 } 17410 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 17411 throw new SecurityException("Calling uid " + callingUid 17412 + " does not own package " + pkg); 17413 } 17414 } 17415 17416 @Override 17417 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 17418 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 17419 } 17420 17421 private Intent getHomeIntent() { 17422 Intent intent = new Intent(Intent.ACTION_MAIN); 17423 intent.addCategory(Intent.CATEGORY_HOME); 17424 return intent; 17425 } 17426 17427 private IntentFilter getHomeFilter() { 17428 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 17429 filter.addCategory(Intent.CATEGORY_HOME); 17430 filter.addCategory(Intent.CATEGORY_DEFAULT); 17431 return filter; 17432 } 17433 17434 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 17435 int userId) { 17436 Intent intent = getHomeIntent(); 17437 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 17438 PackageManager.GET_META_DATA, userId); 17439 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 17440 true, false, false, userId); 17441 17442 allHomeCandidates.clear(); 17443 if (list != null) { 17444 for (ResolveInfo ri : list) { 17445 allHomeCandidates.add(ri); 17446 } 17447 } 17448 return (preferred == null || preferred.activityInfo == null) 17449 ? null 17450 : new ComponentName(preferred.activityInfo.packageName, 17451 preferred.activityInfo.name); 17452 } 17453 17454 @Override 17455 public void setHomeActivity(ComponentName comp, int userId) { 17456 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 17457 getHomeActivitiesAsUser(homeActivities, userId); 17458 17459 boolean found = false; 17460 17461 final int size = homeActivities.size(); 17462 final ComponentName[] set = new ComponentName[size]; 17463 for (int i = 0; i < size; i++) { 17464 final ResolveInfo candidate = homeActivities.get(i); 17465 final ActivityInfo info = candidate.activityInfo; 17466 final ComponentName activityName = new ComponentName(info.packageName, info.name); 17467 set[i] = activityName; 17468 if (!found && activityName.equals(comp)) { 17469 found = true; 17470 } 17471 } 17472 if (!found) { 17473 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 17474 + userId); 17475 } 17476 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 17477 set, comp, userId); 17478 } 17479 17480 private @Nullable String getSetupWizardPackageName() { 17481 final Intent intent = new Intent(Intent.ACTION_MAIN); 17482 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 17483 17484 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 17485 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 17486 | MATCH_DISABLED_COMPONENTS, 17487 UserHandle.myUserId()); 17488 if (matches.size() == 1) { 17489 return matches.get(0).getComponentInfo().packageName; 17490 } else { 17491 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 17492 + ": matches=" + matches); 17493 return null; 17494 } 17495 } 17496 17497 @Override 17498 public void setApplicationEnabledSetting(String appPackageName, 17499 int newState, int flags, int userId, String callingPackage) { 17500 if (!sUserManager.exists(userId)) return; 17501 if (callingPackage == null) { 17502 callingPackage = Integer.toString(Binder.getCallingUid()); 17503 } 17504 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 17505 } 17506 17507 @Override 17508 public void setComponentEnabledSetting(ComponentName componentName, 17509 int newState, int flags, int userId) { 17510 if (!sUserManager.exists(userId)) return; 17511 setEnabledSetting(componentName.getPackageName(), 17512 componentName.getClassName(), newState, flags, userId, null); 17513 } 17514 17515 private void setEnabledSetting(final String packageName, String className, int newState, 17516 final int flags, int userId, String callingPackage) { 17517 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 17518 || newState == COMPONENT_ENABLED_STATE_ENABLED 17519 || newState == COMPONENT_ENABLED_STATE_DISABLED 17520 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17521 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 17522 throw new IllegalArgumentException("Invalid new component state: " 17523 + newState); 17524 } 17525 PackageSetting pkgSetting; 17526 final int uid = Binder.getCallingUid(); 17527 final int permission; 17528 if (uid == Process.SYSTEM_UID) { 17529 permission = PackageManager.PERMISSION_GRANTED; 17530 } else { 17531 permission = mContext.checkCallingOrSelfPermission( 17532 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17533 } 17534 enforceCrossUserPermission(uid, userId, 17535 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 17536 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17537 boolean sendNow = false; 17538 boolean isApp = (className == null); 17539 String componentName = isApp ? packageName : className; 17540 int packageUid = -1; 17541 ArrayList<String> components; 17542 17543 // writer 17544 synchronized (mPackages) { 17545 pkgSetting = mSettings.mPackages.get(packageName); 17546 if (pkgSetting == null) { 17547 if (className == null) { 17548 throw new IllegalArgumentException("Unknown package: " + packageName); 17549 } 17550 throw new IllegalArgumentException( 17551 "Unknown component: " + packageName + "/" + className); 17552 } 17553 // Don't allow other apps to disable an active profile owner 17554 if (!UserHandle.isSameApp(uid, pkgSetting.appId)) { 17555 final DevicePolicyManagerInternal dpmi = LocalServices 17556 .getService(DevicePolicyManagerInternal.class); 17557 if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) { 17558 throw new SecurityException("Cannot disable a device owner or a profile owner"); 17559 } 17560 } 17561 // Allow root and verify that userId is not being specified by a different user 17562 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 17563 throw new SecurityException( 17564 "Permission Denial: attempt to change component state from pid=" 17565 + Binder.getCallingPid() 17566 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 17567 } 17568 if (uid == Process.SHELL_UID) { 17569 // Shell can only change whole packages between ENABLED and DISABLED_USER states 17570 int oldState = pkgSetting.getEnabled(userId); 17571 if (className == null 17572 && 17573 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 17574 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 17575 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 17576 && 17577 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17578 || newState == COMPONENT_ENABLED_STATE_DEFAULT 17579 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 17580 // ok 17581 } else { 17582 throw new SecurityException( 17583 "Shell cannot change component state for " + packageName + "/" 17584 + className + " to " + newState); 17585 } 17586 } 17587 if (className == null) { 17588 // We're dealing with an application/package level state change 17589 if (pkgSetting.getEnabled(userId) == newState) { 17590 // Nothing to do 17591 return; 17592 } 17593 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 17594 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 17595 // Don't care about who enables an app. 17596 callingPackage = null; 17597 } 17598 pkgSetting.setEnabled(newState, userId, callingPackage); 17599 // pkgSetting.pkg.mSetEnabled = newState; 17600 } else { 17601 // We're dealing with a component level state change 17602 // First, verify that this is a valid class name. 17603 PackageParser.Package pkg = pkgSetting.pkg; 17604 if (pkg == null || !pkg.hasComponentClassName(className)) { 17605 if (pkg != null && 17606 pkg.applicationInfo.targetSdkVersion >= 17607 Build.VERSION_CODES.JELLY_BEAN) { 17608 throw new IllegalArgumentException("Component class " + className 17609 + " does not exist in " + packageName); 17610 } else { 17611 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 17612 + className + " does not exist in " + packageName); 17613 } 17614 } 17615 switch (newState) { 17616 case COMPONENT_ENABLED_STATE_ENABLED: 17617 if (!pkgSetting.enableComponentLPw(className, userId)) { 17618 return; 17619 } 17620 break; 17621 case COMPONENT_ENABLED_STATE_DISABLED: 17622 if (!pkgSetting.disableComponentLPw(className, userId)) { 17623 return; 17624 } 17625 break; 17626 case COMPONENT_ENABLED_STATE_DEFAULT: 17627 if (!pkgSetting.restoreComponentLPw(className, userId)) { 17628 return; 17629 } 17630 break; 17631 default: 17632 Slog.e(TAG, "Invalid new component state: " + newState); 17633 return; 17634 } 17635 } 17636 scheduleWritePackageRestrictionsLocked(userId); 17637 components = mPendingBroadcasts.get(userId, packageName); 17638 final boolean newPackage = components == null; 17639 if (newPackage) { 17640 components = new ArrayList<String>(); 17641 } 17642 if (!components.contains(componentName)) { 17643 components.add(componentName); 17644 } 17645 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 17646 sendNow = true; 17647 // Purge entry from pending broadcast list if another one exists already 17648 // since we are sending one right away. 17649 mPendingBroadcasts.remove(userId, packageName); 17650 } else { 17651 if (newPackage) { 17652 mPendingBroadcasts.put(userId, packageName, components); 17653 } 17654 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 17655 // Schedule a message 17656 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 17657 } 17658 } 17659 } 17660 17661 long callingId = Binder.clearCallingIdentity(); 17662 try { 17663 if (sendNow) { 17664 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 17665 sendPackageChangedBroadcast(packageName, 17666 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 17667 } 17668 } finally { 17669 Binder.restoreCallingIdentity(callingId); 17670 } 17671 } 17672 17673 @Override 17674 public void flushPackageRestrictionsAsUser(int userId) { 17675 if (!sUserManager.exists(userId)) { 17676 return; 17677 } 17678 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 17679 false /* checkShell */, "flushPackageRestrictions"); 17680 synchronized (mPackages) { 17681 mSettings.writePackageRestrictionsLPr(userId); 17682 mDirtyUsers.remove(userId); 17683 if (mDirtyUsers.isEmpty()) { 17684 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 17685 } 17686 } 17687 } 17688 17689 private void sendPackageChangedBroadcast(String packageName, 17690 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 17691 if (DEBUG_INSTALL) 17692 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 17693 + componentNames); 17694 Bundle extras = new Bundle(4); 17695 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 17696 String nameList[] = new String[componentNames.size()]; 17697 componentNames.toArray(nameList); 17698 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 17699 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 17700 extras.putInt(Intent.EXTRA_UID, packageUid); 17701 // If this is not reporting a change of the overall package, then only send it 17702 // to registered receivers. We don't want to launch a swath of apps for every 17703 // little component state change. 17704 final int flags = !componentNames.contains(packageName) 17705 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 17706 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 17707 new int[] {UserHandle.getUserId(packageUid)}); 17708 } 17709 17710 @Override 17711 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 17712 if (!sUserManager.exists(userId)) return; 17713 final int uid = Binder.getCallingUid(); 17714 final int permission = mContext.checkCallingOrSelfPermission( 17715 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17716 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17717 enforceCrossUserPermission(uid, userId, 17718 true /* requireFullPermission */, true /* checkShell */, "stop package"); 17719 // writer 17720 synchronized (mPackages) { 17721 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 17722 allowedByPermission, uid, userId)) { 17723 scheduleWritePackageRestrictionsLocked(userId); 17724 } 17725 } 17726 } 17727 17728 @Override 17729 public String getInstallerPackageName(String packageName) { 17730 // reader 17731 synchronized (mPackages) { 17732 return mSettings.getInstallerPackageNameLPr(packageName); 17733 } 17734 } 17735 17736 public boolean isOrphaned(String packageName) { 17737 // reader 17738 synchronized (mPackages) { 17739 return mSettings.isOrphaned(packageName); 17740 } 17741 } 17742 17743 @Override 17744 public int getApplicationEnabledSetting(String packageName, int userId) { 17745 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17746 int uid = Binder.getCallingUid(); 17747 enforceCrossUserPermission(uid, userId, 17748 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 17749 // reader 17750 synchronized (mPackages) { 17751 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 17752 } 17753 } 17754 17755 @Override 17756 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 17757 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17758 int uid = Binder.getCallingUid(); 17759 enforceCrossUserPermission(uid, userId, 17760 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 17761 // reader 17762 synchronized (mPackages) { 17763 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 17764 } 17765 } 17766 17767 @Override 17768 public void enterSafeMode() { 17769 enforceSystemOrRoot("Only the system can request entering safe mode"); 17770 17771 if (!mSystemReady) { 17772 mSafeMode = true; 17773 } 17774 } 17775 17776 @Override 17777 public void systemReady() { 17778 mSystemReady = true; 17779 17780 // Read the compatibilty setting when the system is ready. 17781 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 17782 mContext.getContentResolver(), 17783 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 17784 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 17785 if (DEBUG_SETTINGS) { 17786 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 17787 } 17788 17789 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 17790 17791 synchronized (mPackages) { 17792 // Verify that all of the preferred activity components actually 17793 // exist. It is possible for applications to be updated and at 17794 // that point remove a previously declared activity component that 17795 // had been set as a preferred activity. We try to clean this up 17796 // the next time we encounter that preferred activity, but it is 17797 // possible for the user flow to never be able to return to that 17798 // situation so here we do a sanity check to make sure we haven't 17799 // left any junk around. 17800 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 17801 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17802 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17803 removed.clear(); 17804 for (PreferredActivity pa : pir.filterSet()) { 17805 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 17806 removed.add(pa); 17807 } 17808 } 17809 if (removed.size() > 0) { 17810 for (int r=0; r<removed.size(); r++) { 17811 PreferredActivity pa = removed.get(r); 17812 Slog.w(TAG, "Removing dangling preferred activity: " 17813 + pa.mPref.mComponent); 17814 pir.removeFilter(pa); 17815 } 17816 mSettings.writePackageRestrictionsLPr( 17817 mSettings.mPreferredActivities.keyAt(i)); 17818 } 17819 } 17820 17821 for (int userId : UserManagerService.getInstance().getUserIds()) { 17822 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 17823 grantPermissionsUserIds = ArrayUtils.appendInt( 17824 grantPermissionsUserIds, userId); 17825 } 17826 } 17827 } 17828 sUserManager.systemReady(); 17829 17830 // If we upgraded grant all default permissions before kicking off. 17831 for (int userId : grantPermissionsUserIds) { 17832 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 17833 } 17834 17835 // Kick off any messages waiting for system ready 17836 if (mPostSystemReadyMessages != null) { 17837 for (Message msg : mPostSystemReadyMessages) { 17838 msg.sendToTarget(); 17839 } 17840 mPostSystemReadyMessages = null; 17841 } 17842 17843 // Watch for external volumes that come and go over time 17844 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17845 storage.registerListener(mStorageListener); 17846 17847 mInstallerService.systemReady(); 17848 mPackageDexOptimizer.systemReady(); 17849 17850 MountServiceInternal mountServiceInternal = LocalServices.getService( 17851 MountServiceInternal.class); 17852 mountServiceInternal.addExternalStoragePolicy( 17853 new MountServiceInternal.ExternalStorageMountPolicy() { 17854 @Override 17855 public int getMountMode(int uid, String packageName) { 17856 if (Process.isIsolated(uid)) { 17857 return Zygote.MOUNT_EXTERNAL_NONE; 17858 } 17859 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 17860 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17861 } 17862 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17863 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17864 } 17865 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17866 return Zygote.MOUNT_EXTERNAL_READ; 17867 } 17868 return Zygote.MOUNT_EXTERNAL_WRITE; 17869 } 17870 17871 @Override 17872 public boolean hasExternalStorage(int uid, String packageName) { 17873 return true; 17874 } 17875 }); 17876 17877 // Now that we're mostly running, clean up stale users and apps 17878 reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 17879 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 17880 } 17881 17882 @Override 17883 public boolean isSafeMode() { 17884 return mSafeMode; 17885 } 17886 17887 @Override 17888 public boolean hasSystemUidErrors() { 17889 return mHasSystemUidErrors; 17890 } 17891 17892 static String arrayToString(int[] array) { 17893 StringBuffer buf = new StringBuffer(128); 17894 buf.append('['); 17895 if (array != null) { 17896 for (int i=0; i<array.length; i++) { 17897 if (i > 0) buf.append(", "); 17898 buf.append(array[i]); 17899 } 17900 } 17901 buf.append(']'); 17902 return buf.toString(); 17903 } 17904 17905 static class DumpState { 17906 public static final int DUMP_LIBS = 1 << 0; 17907 public static final int DUMP_FEATURES = 1 << 1; 17908 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 17909 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 17910 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 17911 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 17912 public static final int DUMP_PERMISSIONS = 1 << 6; 17913 public static final int DUMP_PACKAGES = 1 << 7; 17914 public static final int DUMP_SHARED_USERS = 1 << 8; 17915 public static final int DUMP_MESSAGES = 1 << 9; 17916 public static final int DUMP_PROVIDERS = 1 << 10; 17917 public static final int DUMP_VERIFIERS = 1 << 11; 17918 public static final int DUMP_PREFERRED = 1 << 12; 17919 public static final int DUMP_PREFERRED_XML = 1 << 13; 17920 public static final int DUMP_KEYSETS = 1 << 14; 17921 public static final int DUMP_VERSION = 1 << 15; 17922 public static final int DUMP_INSTALLS = 1 << 16; 17923 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 17924 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 17925 public static final int DUMP_FROZEN = 1 << 19; 17926 public static final int DUMP_DEXOPT = 1 << 20; 17927 17928 public static final int OPTION_SHOW_FILTERS = 1 << 0; 17929 17930 private int mTypes; 17931 17932 private int mOptions; 17933 17934 private boolean mTitlePrinted; 17935 17936 private SharedUserSetting mSharedUser; 17937 17938 public boolean isDumping(int type) { 17939 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 17940 return true; 17941 } 17942 17943 return (mTypes & type) != 0; 17944 } 17945 17946 public void setDump(int type) { 17947 mTypes |= type; 17948 } 17949 17950 public boolean isOptionEnabled(int option) { 17951 return (mOptions & option) != 0; 17952 } 17953 17954 public void setOptionEnabled(int option) { 17955 mOptions |= option; 17956 } 17957 17958 public boolean onTitlePrinted() { 17959 final boolean printed = mTitlePrinted; 17960 mTitlePrinted = true; 17961 return printed; 17962 } 17963 17964 public boolean getTitlePrinted() { 17965 return mTitlePrinted; 17966 } 17967 17968 public void setTitlePrinted(boolean enabled) { 17969 mTitlePrinted = enabled; 17970 } 17971 17972 public SharedUserSetting getSharedUser() { 17973 return mSharedUser; 17974 } 17975 17976 public void setSharedUser(SharedUserSetting user) { 17977 mSharedUser = user; 17978 } 17979 } 17980 17981 @Override 17982 public void onShellCommand(FileDescriptor in, FileDescriptor out, 17983 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 17984 (new PackageManagerShellCommand(this)).exec( 17985 this, in, out, err, args, resultReceiver); 17986 } 17987 17988 @Override 17989 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 17990 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 17991 != PackageManager.PERMISSION_GRANTED) { 17992 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 17993 + Binder.getCallingPid() 17994 + ", uid=" + Binder.getCallingUid() 17995 + " without permission " 17996 + android.Manifest.permission.DUMP); 17997 return; 17998 } 17999 18000 DumpState dumpState = new DumpState(); 18001 boolean fullPreferred = false; 18002 boolean checkin = false; 18003 18004 String packageName = null; 18005 ArraySet<String> permissionNames = null; 18006 18007 int opti = 0; 18008 while (opti < args.length) { 18009 String opt = args[opti]; 18010 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 18011 break; 18012 } 18013 opti++; 18014 18015 if ("-a".equals(opt)) { 18016 // Right now we only know how to print all. 18017 } else if ("-h".equals(opt)) { 18018 pw.println("Package manager dump options:"); 18019 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 18020 pw.println(" --checkin: dump for a checkin"); 18021 pw.println(" -f: print details of intent filters"); 18022 pw.println(" -h: print this help"); 18023 pw.println(" cmd may be one of:"); 18024 pw.println(" l[ibraries]: list known shared libraries"); 18025 pw.println(" f[eatures]: list device features"); 18026 pw.println(" k[eysets]: print known keysets"); 18027 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 18028 pw.println(" perm[issions]: dump permissions"); 18029 pw.println(" permission [name ...]: dump declaration and use of given permission"); 18030 pw.println(" pref[erred]: print preferred package settings"); 18031 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 18032 pw.println(" prov[iders]: dump content providers"); 18033 pw.println(" p[ackages]: dump installed packages"); 18034 pw.println(" s[hared-users]: dump shared user IDs"); 18035 pw.println(" m[essages]: print collected runtime messages"); 18036 pw.println(" v[erifiers]: print package verifier info"); 18037 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 18038 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 18039 pw.println(" version: print database version info"); 18040 pw.println(" write: write current settings now"); 18041 pw.println(" installs: details about install sessions"); 18042 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 18043 pw.println(" dexopt: dump dexopt state"); 18044 pw.println(" <package.name>: info about given package"); 18045 return; 18046 } else if ("--checkin".equals(opt)) { 18047 checkin = true; 18048 } else if ("-f".equals(opt)) { 18049 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18050 } else { 18051 pw.println("Unknown argument: " + opt + "; use -h for help"); 18052 } 18053 } 18054 18055 // Is the caller requesting to dump a particular piece of data? 18056 if (opti < args.length) { 18057 String cmd = args[opti]; 18058 opti++; 18059 // Is this a package name? 18060 if ("android".equals(cmd) || cmd.contains(".")) { 18061 packageName = cmd; 18062 // When dumping a single package, we always dump all of its 18063 // filter information since the amount of data will be reasonable. 18064 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18065 } else if ("check-permission".equals(cmd)) { 18066 if (opti >= args.length) { 18067 pw.println("Error: check-permission missing permission argument"); 18068 return; 18069 } 18070 String perm = args[opti]; 18071 opti++; 18072 if (opti >= args.length) { 18073 pw.println("Error: check-permission missing package argument"); 18074 return; 18075 } 18076 String pkg = args[opti]; 18077 opti++; 18078 int user = UserHandle.getUserId(Binder.getCallingUid()); 18079 if (opti < args.length) { 18080 try { 18081 user = Integer.parseInt(args[opti]); 18082 } catch (NumberFormatException e) { 18083 pw.println("Error: check-permission user argument is not a number: " 18084 + args[opti]); 18085 return; 18086 } 18087 } 18088 pw.println(checkPermission(perm, pkg, user)); 18089 return; 18090 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 18091 dumpState.setDump(DumpState.DUMP_LIBS); 18092 } else if ("f".equals(cmd) || "features".equals(cmd)) { 18093 dumpState.setDump(DumpState.DUMP_FEATURES); 18094 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 18095 if (opti >= args.length) { 18096 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 18097 | DumpState.DUMP_SERVICE_RESOLVERS 18098 | DumpState.DUMP_RECEIVER_RESOLVERS 18099 | DumpState.DUMP_CONTENT_RESOLVERS); 18100 } else { 18101 while (opti < args.length) { 18102 String name = args[opti]; 18103 if ("a".equals(name) || "activity".equals(name)) { 18104 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 18105 } else if ("s".equals(name) || "service".equals(name)) { 18106 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 18107 } else if ("r".equals(name) || "receiver".equals(name)) { 18108 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 18109 } else if ("c".equals(name) || "content".equals(name)) { 18110 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 18111 } else { 18112 pw.println("Error: unknown resolver table type: " + name); 18113 return; 18114 } 18115 opti++; 18116 } 18117 } 18118 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 18119 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 18120 } else if ("permission".equals(cmd)) { 18121 if (opti >= args.length) { 18122 pw.println("Error: permission requires permission name"); 18123 return; 18124 } 18125 permissionNames = new ArraySet<>(); 18126 while (opti < args.length) { 18127 permissionNames.add(args[opti]); 18128 opti++; 18129 } 18130 dumpState.setDump(DumpState.DUMP_PERMISSIONS 18131 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 18132 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 18133 dumpState.setDump(DumpState.DUMP_PREFERRED); 18134 } else if ("preferred-xml".equals(cmd)) { 18135 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 18136 if (opti < args.length && "--full".equals(args[opti])) { 18137 fullPreferred = true; 18138 opti++; 18139 } 18140 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 18141 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 18142 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 18143 dumpState.setDump(DumpState.DUMP_PACKAGES); 18144 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 18145 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 18146 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 18147 dumpState.setDump(DumpState.DUMP_PROVIDERS); 18148 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 18149 dumpState.setDump(DumpState.DUMP_MESSAGES); 18150 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 18151 dumpState.setDump(DumpState.DUMP_VERIFIERS); 18152 } else if ("i".equals(cmd) || "ifv".equals(cmd) 18153 || "intent-filter-verifiers".equals(cmd)) { 18154 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 18155 } else if ("version".equals(cmd)) { 18156 dumpState.setDump(DumpState.DUMP_VERSION); 18157 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 18158 dumpState.setDump(DumpState.DUMP_KEYSETS); 18159 } else if ("installs".equals(cmd)) { 18160 dumpState.setDump(DumpState.DUMP_INSTALLS); 18161 } else if ("frozen".equals(cmd)) { 18162 dumpState.setDump(DumpState.DUMP_FROZEN); 18163 } else if ("dexopt".equals(cmd)) { 18164 dumpState.setDump(DumpState.DUMP_DEXOPT); 18165 } else if ("write".equals(cmd)) { 18166 synchronized (mPackages) { 18167 mSettings.writeLPr(); 18168 pw.println("Settings written."); 18169 return; 18170 } 18171 } 18172 } 18173 18174 if (checkin) { 18175 pw.println("vers,1"); 18176 } 18177 18178 // reader 18179 synchronized (mPackages) { 18180 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 18181 if (!checkin) { 18182 if (dumpState.onTitlePrinted()) 18183 pw.println(); 18184 pw.println("Database versions:"); 18185 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 18186 } 18187 } 18188 18189 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 18190 if (!checkin) { 18191 if (dumpState.onTitlePrinted()) 18192 pw.println(); 18193 pw.println("Verifiers:"); 18194 pw.print(" Required: "); 18195 pw.print(mRequiredVerifierPackage); 18196 pw.print(" (uid="); 18197 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18198 UserHandle.USER_SYSTEM)); 18199 pw.println(")"); 18200 } else if (mRequiredVerifierPackage != null) { 18201 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 18202 pw.print(","); 18203 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18204 UserHandle.USER_SYSTEM)); 18205 } 18206 } 18207 18208 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 18209 packageName == null) { 18210 if (mIntentFilterVerifierComponent != null) { 18211 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 18212 if (!checkin) { 18213 if (dumpState.onTitlePrinted()) 18214 pw.println(); 18215 pw.println("Intent Filter Verifier:"); 18216 pw.print(" Using: "); 18217 pw.print(verifierPackageName); 18218 pw.print(" (uid="); 18219 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18220 UserHandle.USER_SYSTEM)); 18221 pw.println(")"); 18222 } else if (verifierPackageName != null) { 18223 pw.print("ifv,"); pw.print(verifierPackageName); 18224 pw.print(","); 18225 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18226 UserHandle.USER_SYSTEM)); 18227 } 18228 } else { 18229 pw.println(); 18230 pw.println("No Intent Filter Verifier available!"); 18231 } 18232 } 18233 18234 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 18235 boolean printedHeader = false; 18236 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 18237 while (it.hasNext()) { 18238 String name = it.next(); 18239 SharedLibraryEntry ent = mSharedLibraries.get(name); 18240 if (!checkin) { 18241 if (!printedHeader) { 18242 if (dumpState.onTitlePrinted()) 18243 pw.println(); 18244 pw.println("Libraries:"); 18245 printedHeader = true; 18246 } 18247 pw.print(" "); 18248 } else { 18249 pw.print("lib,"); 18250 } 18251 pw.print(name); 18252 if (!checkin) { 18253 pw.print(" -> "); 18254 } 18255 if (ent.path != null) { 18256 if (!checkin) { 18257 pw.print("(jar) "); 18258 pw.print(ent.path); 18259 } else { 18260 pw.print(",jar,"); 18261 pw.print(ent.path); 18262 } 18263 } else { 18264 if (!checkin) { 18265 pw.print("(apk) "); 18266 pw.print(ent.apk); 18267 } else { 18268 pw.print(",apk,"); 18269 pw.print(ent.apk); 18270 } 18271 } 18272 pw.println(); 18273 } 18274 } 18275 18276 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 18277 if (dumpState.onTitlePrinted()) 18278 pw.println(); 18279 if (!checkin) { 18280 pw.println("Features:"); 18281 } 18282 18283 for (FeatureInfo feat : mAvailableFeatures.values()) { 18284 if (checkin) { 18285 pw.print("feat,"); 18286 pw.print(feat.name); 18287 pw.print(","); 18288 pw.println(feat.version); 18289 } else { 18290 pw.print(" "); 18291 pw.print(feat.name); 18292 if (feat.version > 0) { 18293 pw.print(" version="); 18294 pw.print(feat.version); 18295 } 18296 pw.println(); 18297 } 18298 } 18299 } 18300 18301 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 18302 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 18303 : "Activity Resolver Table:", " ", packageName, 18304 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18305 dumpState.setTitlePrinted(true); 18306 } 18307 } 18308 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 18309 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 18310 : "Receiver Resolver Table:", " ", packageName, 18311 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18312 dumpState.setTitlePrinted(true); 18313 } 18314 } 18315 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 18316 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 18317 : "Service Resolver Table:", " ", packageName, 18318 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18319 dumpState.setTitlePrinted(true); 18320 } 18321 } 18322 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 18323 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 18324 : "Provider Resolver Table:", " ", packageName, 18325 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18326 dumpState.setTitlePrinted(true); 18327 } 18328 } 18329 18330 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 18331 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18332 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18333 int user = mSettings.mPreferredActivities.keyAt(i); 18334 if (pir.dump(pw, 18335 dumpState.getTitlePrinted() 18336 ? "\nPreferred Activities User " + user + ":" 18337 : "Preferred Activities User " + user + ":", " ", 18338 packageName, true, false)) { 18339 dumpState.setTitlePrinted(true); 18340 } 18341 } 18342 } 18343 18344 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 18345 pw.flush(); 18346 FileOutputStream fout = new FileOutputStream(fd); 18347 BufferedOutputStream str = new BufferedOutputStream(fout); 18348 XmlSerializer serializer = new FastXmlSerializer(); 18349 try { 18350 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 18351 serializer.startDocument(null, true); 18352 serializer.setFeature( 18353 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 18354 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 18355 serializer.endDocument(); 18356 serializer.flush(); 18357 } catch (IllegalArgumentException e) { 18358 pw.println("Failed writing: " + e); 18359 } catch (IllegalStateException e) { 18360 pw.println("Failed writing: " + e); 18361 } catch (IOException e) { 18362 pw.println("Failed writing: " + e); 18363 } 18364 } 18365 18366 if (!checkin 18367 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 18368 && packageName == null) { 18369 pw.println(); 18370 int count = mSettings.mPackages.size(); 18371 if (count == 0) { 18372 pw.println("No applications!"); 18373 pw.println(); 18374 } else { 18375 final String prefix = " "; 18376 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 18377 if (allPackageSettings.size() == 0) { 18378 pw.println("No domain preferred apps!"); 18379 pw.println(); 18380 } else { 18381 pw.println("App verification status:"); 18382 pw.println(); 18383 count = 0; 18384 for (PackageSetting ps : allPackageSettings) { 18385 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 18386 if (ivi == null || ivi.getPackageName() == null) continue; 18387 pw.println(prefix + "Package: " + ivi.getPackageName()); 18388 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 18389 pw.println(prefix + "Status: " + ivi.getStatusString()); 18390 pw.println(); 18391 count++; 18392 } 18393 if (count == 0) { 18394 pw.println(prefix + "No app verification established."); 18395 pw.println(); 18396 } 18397 for (int userId : sUserManager.getUserIds()) { 18398 pw.println("App linkages for user " + userId + ":"); 18399 pw.println(); 18400 count = 0; 18401 for (PackageSetting ps : allPackageSettings) { 18402 final long status = ps.getDomainVerificationStatusForUser(userId); 18403 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 18404 continue; 18405 } 18406 pw.println(prefix + "Package: " + ps.name); 18407 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 18408 String statusStr = IntentFilterVerificationInfo. 18409 getStatusStringFromValue(status); 18410 pw.println(prefix + "Status: " + statusStr); 18411 pw.println(); 18412 count++; 18413 } 18414 if (count == 0) { 18415 pw.println(prefix + "No configured app linkages."); 18416 pw.println(); 18417 } 18418 } 18419 } 18420 } 18421 } 18422 18423 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 18424 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 18425 if (packageName == null && permissionNames == null) { 18426 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 18427 if (iperm == 0) { 18428 if (dumpState.onTitlePrinted()) 18429 pw.println(); 18430 pw.println("AppOp Permissions:"); 18431 } 18432 pw.print(" AppOp Permission "); 18433 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 18434 pw.println(":"); 18435 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 18436 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 18437 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 18438 } 18439 } 18440 } 18441 } 18442 18443 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 18444 boolean printedSomething = false; 18445 for (PackageParser.Provider p : mProviders.mProviders.values()) { 18446 if (packageName != null && !packageName.equals(p.info.packageName)) { 18447 continue; 18448 } 18449 if (!printedSomething) { 18450 if (dumpState.onTitlePrinted()) 18451 pw.println(); 18452 pw.println("Registered ContentProviders:"); 18453 printedSomething = true; 18454 } 18455 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 18456 pw.print(" "); pw.println(p.toString()); 18457 } 18458 printedSomething = false; 18459 for (Map.Entry<String, PackageParser.Provider> entry : 18460 mProvidersByAuthority.entrySet()) { 18461 PackageParser.Provider p = entry.getValue(); 18462 if (packageName != null && !packageName.equals(p.info.packageName)) { 18463 continue; 18464 } 18465 if (!printedSomething) { 18466 if (dumpState.onTitlePrinted()) 18467 pw.println(); 18468 pw.println("ContentProvider Authorities:"); 18469 printedSomething = true; 18470 } 18471 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 18472 pw.print(" "); pw.println(p.toString()); 18473 if (p.info != null && p.info.applicationInfo != null) { 18474 final String appInfo = p.info.applicationInfo.toString(); 18475 pw.print(" applicationInfo="); pw.println(appInfo); 18476 } 18477 } 18478 } 18479 18480 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 18481 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 18482 } 18483 18484 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 18485 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 18486 } 18487 18488 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 18489 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 18490 } 18491 18492 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 18493 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 18494 } 18495 18496 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 18497 // XXX should handle packageName != null by dumping only install data that 18498 // the given package is involved with. 18499 if (dumpState.onTitlePrinted()) pw.println(); 18500 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 18501 } 18502 18503 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 18504 // XXX should handle packageName != null by dumping only install data that 18505 // the given package is involved with. 18506 if (dumpState.onTitlePrinted()) pw.println(); 18507 18508 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18509 ipw.println(); 18510 ipw.println("Frozen packages:"); 18511 ipw.increaseIndent(); 18512 if (mFrozenPackages.size() == 0) { 18513 ipw.println("(none)"); 18514 } else { 18515 for (int i = 0; i < mFrozenPackages.size(); i++) { 18516 ipw.println(mFrozenPackages.valueAt(i)); 18517 } 18518 } 18519 ipw.decreaseIndent(); 18520 } 18521 18522 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 18523 if (dumpState.onTitlePrinted()) pw.println(); 18524 dumpDexoptStateLPr(pw, packageName); 18525 } 18526 18527 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 18528 if (dumpState.onTitlePrinted()) pw.println(); 18529 mSettings.dumpReadMessagesLPr(pw, dumpState); 18530 18531 pw.println(); 18532 pw.println("Package warning messages:"); 18533 BufferedReader in = null; 18534 String line = null; 18535 try { 18536 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18537 while ((line = in.readLine()) != null) { 18538 if (line.contains("ignored: updated version")) continue; 18539 pw.println(line); 18540 } 18541 } catch (IOException ignored) { 18542 } finally { 18543 IoUtils.closeQuietly(in); 18544 } 18545 } 18546 18547 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 18548 BufferedReader in = null; 18549 String line = null; 18550 try { 18551 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18552 while ((line = in.readLine()) != null) { 18553 if (line.contains("ignored: updated version")) continue; 18554 pw.print("msg,"); 18555 pw.println(line); 18556 } 18557 } catch (IOException ignored) { 18558 } finally { 18559 IoUtils.closeQuietly(in); 18560 } 18561 } 18562 } 18563 } 18564 18565 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 18566 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18567 ipw.println(); 18568 ipw.println("Dexopt state:"); 18569 ipw.increaseIndent(); 18570 Collection<PackageParser.Package> packages = null; 18571 if (packageName != null) { 18572 PackageParser.Package targetPackage = mPackages.get(packageName); 18573 if (targetPackage != null) { 18574 packages = Collections.singletonList(targetPackage); 18575 } else { 18576 ipw.println("Unable to find package: " + packageName); 18577 return; 18578 } 18579 } else { 18580 packages = mPackages.values(); 18581 } 18582 18583 for (PackageParser.Package pkg : packages) { 18584 ipw.println("[" + pkg.packageName + "]"); 18585 ipw.increaseIndent(); 18586 mPackageDexOptimizer.dumpDexoptState(ipw, pkg); 18587 ipw.decreaseIndent(); 18588 } 18589 } 18590 18591 private String dumpDomainString(String packageName) { 18592 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 18593 .getList(); 18594 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 18595 18596 ArraySet<String> result = new ArraySet<>(); 18597 if (iviList.size() > 0) { 18598 for (IntentFilterVerificationInfo ivi : iviList) { 18599 for (String host : ivi.getDomains()) { 18600 result.add(host); 18601 } 18602 } 18603 } 18604 if (filters != null && filters.size() > 0) { 18605 for (IntentFilter filter : filters) { 18606 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 18607 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 18608 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 18609 result.addAll(filter.getHostsList()); 18610 } 18611 } 18612 } 18613 18614 StringBuilder sb = new StringBuilder(result.size() * 16); 18615 for (String domain : result) { 18616 if (sb.length() > 0) sb.append(" "); 18617 sb.append(domain); 18618 } 18619 return sb.toString(); 18620 } 18621 18622 // ------- apps on sdcard specific code ------- 18623 static final boolean DEBUG_SD_INSTALL = false; 18624 18625 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 18626 18627 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 18628 18629 private boolean mMediaMounted = false; 18630 18631 static String getEncryptKey() { 18632 try { 18633 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 18634 SD_ENCRYPTION_KEYSTORE_NAME); 18635 if (sdEncKey == null) { 18636 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 18637 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 18638 if (sdEncKey == null) { 18639 Slog.e(TAG, "Failed to create encryption keys"); 18640 return null; 18641 } 18642 } 18643 return sdEncKey; 18644 } catch (NoSuchAlgorithmException nsae) { 18645 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 18646 return null; 18647 } catch (IOException ioe) { 18648 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 18649 return null; 18650 } 18651 } 18652 18653 /* 18654 * Update media status on PackageManager. 18655 */ 18656 @Override 18657 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 18658 int callingUid = Binder.getCallingUid(); 18659 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 18660 throw new SecurityException("Media status can only be updated by the system"); 18661 } 18662 // reader; this apparently protects mMediaMounted, but should probably 18663 // be a different lock in that case. 18664 synchronized (mPackages) { 18665 Log.i(TAG, "Updating external media status from " 18666 + (mMediaMounted ? "mounted" : "unmounted") + " to " 18667 + (mediaStatus ? "mounted" : "unmounted")); 18668 if (DEBUG_SD_INSTALL) 18669 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 18670 + ", mMediaMounted=" + mMediaMounted); 18671 if (mediaStatus == mMediaMounted) { 18672 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 18673 : 0, -1); 18674 mHandler.sendMessage(msg); 18675 return; 18676 } 18677 mMediaMounted = mediaStatus; 18678 } 18679 // Queue up an async operation since the package installation may take a 18680 // little while. 18681 mHandler.post(new Runnable() { 18682 public void run() { 18683 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 18684 } 18685 }); 18686 } 18687 18688 /** 18689 * Called by MountService when the initial ASECs to scan are available. 18690 * Should block until all the ASEC containers are finished being scanned. 18691 */ 18692 public void scanAvailableAsecs() { 18693 updateExternalMediaStatusInner(true, false, false); 18694 } 18695 18696 /* 18697 * Collect information of applications on external media, map them against 18698 * existing containers and update information based on current mount status. 18699 * Please note that we always have to report status if reportStatus has been 18700 * set to true especially when unloading packages. 18701 */ 18702 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 18703 boolean externalStorage) { 18704 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 18705 int[] uidArr = EmptyArray.INT; 18706 18707 final String[] list = PackageHelper.getSecureContainerList(); 18708 if (ArrayUtils.isEmpty(list)) { 18709 Log.i(TAG, "No secure containers found"); 18710 } else { 18711 // Process list of secure containers and categorize them 18712 // as active or stale based on their package internal state. 18713 18714 // reader 18715 synchronized (mPackages) { 18716 for (String cid : list) { 18717 // Leave stages untouched for now; installer service owns them 18718 if (PackageInstallerService.isStageName(cid)) continue; 18719 18720 if (DEBUG_SD_INSTALL) 18721 Log.i(TAG, "Processing container " + cid); 18722 String pkgName = getAsecPackageName(cid); 18723 if (pkgName == null) { 18724 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 18725 continue; 18726 } 18727 if (DEBUG_SD_INSTALL) 18728 Log.i(TAG, "Looking for pkg : " + pkgName); 18729 18730 final PackageSetting ps = mSettings.mPackages.get(pkgName); 18731 if (ps == null) { 18732 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 18733 continue; 18734 } 18735 18736 /* 18737 * Skip packages that are not external if we're unmounting 18738 * external storage. 18739 */ 18740 if (externalStorage && !isMounted && !isExternal(ps)) { 18741 continue; 18742 } 18743 18744 final AsecInstallArgs args = new AsecInstallArgs(cid, 18745 getAppDexInstructionSets(ps), ps.isForwardLocked()); 18746 // The package status is changed only if the code path 18747 // matches between settings and the container id. 18748 if (ps.codePathString != null 18749 && ps.codePathString.startsWith(args.getCodePath())) { 18750 if (DEBUG_SD_INSTALL) { 18751 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 18752 + " at code path: " + ps.codePathString); 18753 } 18754 18755 // We do have a valid package installed on sdcard 18756 processCids.put(args, ps.codePathString); 18757 final int uid = ps.appId; 18758 if (uid != -1) { 18759 uidArr = ArrayUtils.appendInt(uidArr, uid); 18760 } 18761 } else { 18762 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 18763 + ps.codePathString); 18764 } 18765 } 18766 } 18767 18768 Arrays.sort(uidArr); 18769 } 18770 18771 // Process packages with valid entries. 18772 if (isMounted) { 18773 if (DEBUG_SD_INSTALL) 18774 Log.i(TAG, "Loading packages"); 18775 loadMediaPackages(processCids, uidArr, externalStorage); 18776 startCleaningPackages(); 18777 mInstallerService.onSecureContainersAvailable(); 18778 } else { 18779 if (DEBUG_SD_INSTALL) 18780 Log.i(TAG, "Unloading packages"); 18781 unloadMediaPackages(processCids, uidArr, reportStatus); 18782 } 18783 } 18784 18785 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18786 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 18787 final int size = infos.size(); 18788 final String[] packageNames = new String[size]; 18789 final int[] packageUids = new int[size]; 18790 for (int i = 0; i < size; i++) { 18791 final ApplicationInfo info = infos.get(i); 18792 packageNames[i] = info.packageName; 18793 packageUids[i] = info.uid; 18794 } 18795 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 18796 finishedReceiver); 18797 } 18798 18799 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18800 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18801 sendResourcesChangedBroadcast(mediaStatus, replacing, 18802 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 18803 } 18804 18805 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18806 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18807 int size = pkgList.length; 18808 if (size > 0) { 18809 // Send broadcasts here 18810 Bundle extras = new Bundle(); 18811 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 18812 if (uidArr != null) { 18813 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 18814 } 18815 if (replacing) { 18816 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 18817 } 18818 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 18819 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 18820 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 18821 } 18822 } 18823 18824 /* 18825 * Look at potentially valid container ids from processCids If package 18826 * information doesn't match the one on record or package scanning fails, 18827 * the cid is added to list of removeCids. We currently don't delete stale 18828 * containers. 18829 */ 18830 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 18831 boolean externalStorage) { 18832 ArrayList<String> pkgList = new ArrayList<String>(); 18833 Set<AsecInstallArgs> keys = processCids.keySet(); 18834 18835 for (AsecInstallArgs args : keys) { 18836 String codePath = processCids.get(args); 18837 if (DEBUG_SD_INSTALL) 18838 Log.i(TAG, "Loading container : " + args.cid); 18839 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 18840 try { 18841 // Make sure there are no container errors first. 18842 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 18843 Slog.e(TAG, "Failed to mount cid : " + args.cid 18844 + " when installing from sdcard"); 18845 continue; 18846 } 18847 // Check code path here. 18848 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 18849 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 18850 + " does not match one in settings " + codePath); 18851 continue; 18852 } 18853 // Parse package 18854 int parseFlags = mDefParseFlags; 18855 if (args.isExternalAsec()) { 18856 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 18857 } 18858 if (args.isFwdLocked()) { 18859 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 18860 } 18861 18862 synchronized (mInstallLock) { 18863 PackageParser.Package pkg = null; 18864 try { 18865 // Sadly we don't know the package name yet to freeze it 18866 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 18867 SCAN_IGNORE_FROZEN, 0, null); 18868 } catch (PackageManagerException e) { 18869 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 18870 } 18871 // Scan the package 18872 if (pkg != null) { 18873 /* 18874 * TODO why is the lock being held? doPostInstall is 18875 * called in other places without the lock. This needs 18876 * to be straightened out. 18877 */ 18878 // writer 18879 synchronized (mPackages) { 18880 retCode = PackageManager.INSTALL_SUCCEEDED; 18881 pkgList.add(pkg.packageName); 18882 // Post process args 18883 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 18884 pkg.applicationInfo.uid); 18885 } 18886 } else { 18887 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 18888 } 18889 } 18890 18891 } finally { 18892 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 18893 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 18894 } 18895 } 18896 } 18897 // writer 18898 synchronized (mPackages) { 18899 // If the platform SDK has changed since the last time we booted, 18900 // we need to re-grant app permission to catch any new ones that 18901 // appear. This is really a hack, and means that apps can in some 18902 // cases get permissions that the user didn't initially explicitly 18903 // allow... it would be nice to have some better way to handle 18904 // this situation. 18905 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 18906 : mSettings.getInternalVersion(); 18907 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 18908 : StorageManager.UUID_PRIVATE_INTERNAL; 18909 18910 int updateFlags = UPDATE_PERMISSIONS_ALL; 18911 if (ver.sdkVersion != mSdkVersion) { 18912 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 18913 + mSdkVersion + "; regranting permissions for external"); 18914 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 18915 } 18916 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 18917 18918 // Yay, everything is now upgraded 18919 ver.forceCurrent(); 18920 18921 // can downgrade to reader 18922 // Persist settings 18923 mSettings.writeLPr(); 18924 } 18925 // Send a broadcast to let everyone know we are done processing 18926 if (pkgList.size() > 0) { 18927 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 18928 } 18929 } 18930 18931 /* 18932 * Utility method to unload a list of specified containers 18933 */ 18934 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 18935 // Just unmount all valid containers. 18936 for (AsecInstallArgs arg : cidArgs) { 18937 synchronized (mInstallLock) { 18938 arg.doPostDeleteLI(false); 18939 } 18940 } 18941 } 18942 18943 /* 18944 * Unload packages mounted on external media. This involves deleting package 18945 * data from internal structures, sending broadcasts about disabled packages, 18946 * gc'ing to free up references, unmounting all secure containers 18947 * corresponding to packages on external media, and posting a 18948 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 18949 * that we always have to post this message if status has been requested no 18950 * matter what. 18951 */ 18952 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 18953 final boolean reportStatus) { 18954 if (DEBUG_SD_INSTALL) 18955 Log.i(TAG, "unloading media packages"); 18956 ArrayList<String> pkgList = new ArrayList<String>(); 18957 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 18958 final Set<AsecInstallArgs> keys = processCids.keySet(); 18959 for (AsecInstallArgs args : keys) { 18960 String pkgName = args.getPackageName(); 18961 if (DEBUG_SD_INSTALL) 18962 Log.i(TAG, "Trying to unload pkg : " + pkgName); 18963 // Delete package internally 18964 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 18965 synchronized (mInstallLock) { 18966 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 18967 final boolean res; 18968 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 18969 "unloadMediaPackages")) { 18970 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 18971 null); 18972 } 18973 if (res) { 18974 pkgList.add(pkgName); 18975 } else { 18976 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 18977 failedList.add(args); 18978 } 18979 } 18980 } 18981 18982 // reader 18983 synchronized (mPackages) { 18984 // We didn't update the settings after removing each package; 18985 // write them now for all packages. 18986 mSettings.writeLPr(); 18987 } 18988 18989 // We have to absolutely send UPDATED_MEDIA_STATUS only 18990 // after confirming that all the receivers processed the ordered 18991 // broadcast when packages get disabled, force a gc to clean things up. 18992 // and unload all the containers. 18993 if (pkgList.size() > 0) { 18994 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 18995 new IIntentReceiver.Stub() { 18996 public void performReceive(Intent intent, int resultCode, String data, 18997 Bundle extras, boolean ordered, boolean sticky, 18998 int sendingUser) throws RemoteException { 18999 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 19000 reportStatus ? 1 : 0, 1, keys); 19001 mHandler.sendMessage(msg); 19002 } 19003 }); 19004 } else { 19005 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 19006 keys); 19007 mHandler.sendMessage(msg); 19008 } 19009 } 19010 19011 private void loadPrivatePackages(final VolumeInfo vol) { 19012 mHandler.post(new Runnable() { 19013 @Override 19014 public void run() { 19015 loadPrivatePackagesInner(vol); 19016 } 19017 }); 19018 } 19019 19020 private void loadPrivatePackagesInner(VolumeInfo vol) { 19021 final String volumeUuid = vol.fsUuid; 19022 if (TextUtils.isEmpty(volumeUuid)) { 19023 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 19024 return; 19025 } 19026 19027 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 19028 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 19029 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 19030 19031 final VersionInfo ver; 19032 final List<PackageSetting> packages; 19033 synchronized (mPackages) { 19034 ver = mSettings.findOrCreateVersion(volumeUuid); 19035 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19036 } 19037 19038 for (PackageSetting ps : packages) { 19039 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 19040 synchronized (mInstallLock) { 19041 final PackageParser.Package pkg; 19042 try { 19043 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 19044 loaded.add(pkg.applicationInfo); 19045 19046 } catch (PackageManagerException e) { 19047 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 19048 } 19049 19050 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 19051 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 19052 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 19053 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 19054 } 19055 } 19056 } 19057 19058 // Reconcile app data for all started/unlocked users 19059 final StorageManager sm = mContext.getSystemService(StorageManager.class); 19060 final UserManager um = mContext.getSystemService(UserManager.class); 19061 for (UserInfo user : um.getUsers()) { 19062 final int flags; 19063 if (um.isUserUnlockingOrUnlocked(user.id)) { 19064 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19065 } else if (um.isUserRunning(user.id)) { 19066 flags = StorageManager.FLAG_STORAGE_DE; 19067 } else { 19068 continue; 19069 } 19070 19071 try { 19072 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 19073 synchronized (mInstallLock) { 19074 reconcileAppsDataLI(volumeUuid, user.id, flags); 19075 } 19076 } catch (IllegalStateException e) { 19077 // Device was probably ejected, and we'll process that event momentarily 19078 Slog.w(TAG, "Failed to prepare storage: " + e); 19079 } 19080 } 19081 19082 synchronized (mPackages) { 19083 int updateFlags = UPDATE_PERMISSIONS_ALL; 19084 if (ver.sdkVersion != mSdkVersion) { 19085 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19086 + mSdkVersion + "; regranting permissions for " + volumeUuid); 19087 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19088 } 19089 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19090 19091 // Yay, everything is now upgraded 19092 ver.forceCurrent(); 19093 19094 mSettings.writeLPr(); 19095 } 19096 19097 for (PackageFreezer freezer : freezers) { 19098 freezer.close(); 19099 } 19100 19101 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 19102 sendResourcesChangedBroadcast(true, false, loaded, null); 19103 } 19104 19105 private void unloadPrivatePackages(final VolumeInfo vol) { 19106 mHandler.post(new Runnable() { 19107 @Override 19108 public void run() { 19109 unloadPrivatePackagesInner(vol); 19110 } 19111 }); 19112 } 19113 19114 private void unloadPrivatePackagesInner(VolumeInfo vol) { 19115 final String volumeUuid = vol.fsUuid; 19116 if (TextUtils.isEmpty(volumeUuid)) { 19117 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 19118 return; 19119 } 19120 19121 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 19122 synchronized (mInstallLock) { 19123 synchronized (mPackages) { 19124 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 19125 for (PackageSetting ps : packages) { 19126 if (ps.pkg == null) continue; 19127 19128 final ApplicationInfo info = ps.pkg.applicationInfo; 19129 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19130 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19131 19132 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 19133 "unloadPrivatePackagesInner")) { 19134 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 19135 false, null)) { 19136 unloaded.add(info); 19137 } else { 19138 Slog.w(TAG, "Failed to unload " + ps.codePath); 19139 } 19140 } 19141 } 19142 19143 mSettings.writeLPr(); 19144 } 19145 } 19146 19147 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 19148 sendResourcesChangedBroadcast(false, false, unloaded, null); 19149 } 19150 19151 /** 19152 * Prepare storage areas for given user on all mounted devices. 19153 */ 19154 void prepareUserData(int userId, int userSerial, int flags) { 19155 synchronized (mInstallLock) { 19156 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19157 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19158 final String volumeUuid = vol.getFsUuid(); 19159 prepareUserDataLI(volumeUuid, userId, userSerial, flags, true); 19160 } 19161 } 19162 } 19163 19164 private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags, 19165 boolean allowRecover) { 19166 // Prepare storage and verify that serial numbers are consistent; if 19167 // there's a mismatch we need to destroy to avoid leaking data 19168 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19169 try { 19170 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags); 19171 19172 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) { 19173 UserManagerService.enforceSerialNumber( 19174 Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial); 19175 } 19176 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) { 19177 UserManagerService.enforceSerialNumber( 19178 Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial); 19179 } 19180 19181 synchronized (mInstallLock) { 19182 mInstaller.createUserData(volumeUuid, userId, userSerial, flags); 19183 } 19184 } catch (Exception e) { 19185 logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid 19186 + " because we failed to prepare: " + e); 19187 destroyUserDataLI(volumeUuid, userId, 19188 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19189 19190 if (allowRecover) { 19191 // Try one last time; if we fail again we're really in trouble 19192 prepareUserDataLI(volumeUuid, userId, userSerial, flags, false); 19193 } 19194 } 19195 } 19196 19197 /** 19198 * Destroy storage areas for given user on all mounted devices. 19199 */ 19200 void destroyUserData(int userId, int flags) { 19201 synchronized (mInstallLock) { 19202 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19203 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19204 final String volumeUuid = vol.getFsUuid(); 19205 destroyUserDataLI(volumeUuid, userId, flags); 19206 } 19207 } 19208 } 19209 19210 private void destroyUserDataLI(String volumeUuid, int userId, int flags) { 19211 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19212 try { 19213 // Clean up app data, profile data, and media data 19214 mInstaller.destroyUserData(volumeUuid, userId, flags); 19215 19216 // Clean up system data 19217 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19218 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19219 FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId)); 19220 FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId)); 19221 } 19222 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19223 FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId)); 19224 } 19225 } 19226 19227 // Data with special labels is now gone, so finish the job 19228 storage.destroyUserStorage(volumeUuid, userId, flags); 19229 19230 } catch (Exception e) { 19231 logCriticalInfo(Log.WARN, 19232 "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e); 19233 } 19234 } 19235 19236 /** 19237 * Examine all users present on given mounted volume, and destroy data 19238 * belonging to users that are no longer valid, or whose user ID has been 19239 * recycled. 19240 */ 19241 private void reconcileUsers(String volumeUuid) { 19242 final List<File> files = new ArrayList<>(); 19243 Collections.addAll(files, FileUtils 19244 .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid))); 19245 Collections.addAll(files, FileUtils 19246 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid))); 19247 for (File file : files) { 19248 if (!file.isDirectory()) continue; 19249 19250 final int userId; 19251 final UserInfo info; 19252 try { 19253 userId = Integer.parseInt(file.getName()); 19254 info = sUserManager.getUserInfo(userId); 19255 } catch (NumberFormatException e) { 19256 Slog.w(TAG, "Invalid user directory " + file); 19257 continue; 19258 } 19259 19260 boolean destroyUser = false; 19261 if (info == null) { 19262 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19263 + " because no matching user was found"); 19264 destroyUser = true; 19265 } else if (!mOnlyCore) { 19266 try { 19267 UserManagerService.enforceSerialNumber(file, info.serialNumber); 19268 } catch (IOException e) { 19269 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19270 + " because we failed to enforce serial number: " + e); 19271 destroyUser = true; 19272 } 19273 } 19274 19275 if (destroyUser) { 19276 synchronized (mInstallLock) { 19277 destroyUserDataLI(volumeUuid, userId, 19278 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19279 } 19280 } 19281 } 19282 } 19283 19284 private void assertPackageKnown(String volumeUuid, String packageName) 19285 throws PackageManagerException { 19286 synchronized (mPackages) { 19287 final PackageSetting ps = mSettings.mPackages.get(packageName); 19288 if (ps == null) { 19289 throw new PackageManagerException("Package " + packageName + " is unknown"); 19290 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19291 throw new PackageManagerException( 19292 "Package " + packageName + " found on unknown volume " + volumeUuid 19293 + "; expected volume " + ps.volumeUuid); 19294 } 19295 } 19296 } 19297 19298 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 19299 throws PackageManagerException { 19300 synchronized (mPackages) { 19301 final PackageSetting ps = mSettings.mPackages.get(packageName); 19302 if (ps == null) { 19303 throw new PackageManagerException("Package " + packageName + " is unknown"); 19304 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19305 throw new PackageManagerException( 19306 "Package " + packageName + " found on unknown volume " + volumeUuid 19307 + "; expected volume " + ps.volumeUuid); 19308 } else if (!ps.getInstalled(userId)) { 19309 throw new PackageManagerException( 19310 "Package " + packageName + " not installed for user " + userId); 19311 } 19312 } 19313 } 19314 19315 /** 19316 * Examine all apps present on given mounted volume, and destroy apps that 19317 * aren't expected, either due to uninstallation or reinstallation on 19318 * another volume. 19319 */ 19320 private void reconcileApps(String volumeUuid) { 19321 final File[] files = FileUtils 19322 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 19323 for (File file : files) { 19324 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 19325 && !PackageInstallerService.isStageName(file.getName()); 19326 if (!isPackage) { 19327 // Ignore entries which are not packages 19328 continue; 19329 } 19330 19331 try { 19332 final PackageLite pkg = PackageParser.parsePackageLite(file, 19333 PackageParser.PARSE_MUST_BE_APK); 19334 assertPackageKnown(volumeUuid, pkg.packageName); 19335 19336 } catch (PackageParserException | PackageManagerException e) { 19337 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19338 synchronized (mInstallLock) { 19339 removeCodePathLI(file); 19340 } 19341 } 19342 } 19343 } 19344 19345 /** 19346 * Reconcile all app data for the given user. 19347 * <p> 19348 * Verifies that directories exist and that ownership and labeling is 19349 * correct for all installed apps on all mounted volumes. 19350 */ 19351 void reconcileAppsData(int userId, int flags) { 19352 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19353 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19354 final String volumeUuid = vol.getFsUuid(); 19355 synchronized (mInstallLock) { 19356 reconcileAppsDataLI(volumeUuid, userId, flags); 19357 } 19358 } 19359 } 19360 19361 /** 19362 * Reconcile all app data on given mounted volume. 19363 * <p> 19364 * Destroys app data that isn't expected, either due to uninstallation or 19365 * reinstallation on another volume. 19366 * <p> 19367 * Verifies that directories exist and that ownership and labeling is 19368 * correct for all installed apps. 19369 */ 19370 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) { 19371 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 19372 + Integer.toHexString(flags)); 19373 19374 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 19375 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 19376 19377 boolean restoreconNeeded = false; 19378 19379 // First look for stale data that doesn't belong, and check if things 19380 // have changed since we did our last restorecon 19381 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19382 if (StorageManager.isFileEncryptedNativeOrEmulated() 19383 && !StorageManager.isUserKeyUnlocked(userId)) { 19384 throw new RuntimeException( 19385 "Yikes, someone asked us to reconcile CE storage while " + userId 19386 + " was still locked; this would have caused massive data loss!"); 19387 } 19388 19389 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 19390 19391 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 19392 for (File file : files) { 19393 final String packageName = file.getName(); 19394 try { 19395 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19396 } catch (PackageManagerException e) { 19397 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19398 try { 19399 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19400 StorageManager.FLAG_STORAGE_CE, 0); 19401 } catch (InstallerException e2) { 19402 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19403 } 19404 } 19405 } 19406 } 19407 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19408 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 19409 19410 final File[] files = FileUtils.listFilesOrEmpty(deDir); 19411 for (File file : files) { 19412 final String packageName = file.getName(); 19413 try { 19414 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19415 } catch (PackageManagerException e) { 19416 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19417 try { 19418 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19419 StorageManager.FLAG_STORAGE_DE, 0); 19420 } catch (InstallerException e2) { 19421 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19422 } 19423 } 19424 } 19425 } 19426 19427 // Ensure that data directories are ready to roll for all packages 19428 // installed for this volume and user 19429 final List<PackageSetting> packages; 19430 synchronized (mPackages) { 19431 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19432 } 19433 int preparedCount = 0; 19434 for (PackageSetting ps : packages) { 19435 final String packageName = ps.name; 19436 if (ps.pkg == null) { 19437 Slog.w(TAG, "Odd, missing scanned package " + packageName); 19438 // TODO: might be due to legacy ASEC apps; we should circle back 19439 // and reconcile again once they're scanned 19440 continue; 19441 } 19442 19443 if (ps.getInstalled(userId)) { 19444 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19445 19446 if (maybeMigrateAppDataLIF(ps.pkg, userId)) { 19447 // We may have just shuffled around app data directories, so 19448 // prepare them one more time 19449 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19450 } 19451 19452 preparedCount++; 19453 } 19454 } 19455 19456 if (restoreconNeeded) { 19457 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19458 SELinuxMMAC.setRestoreconDone(ceDir); 19459 } 19460 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19461 SELinuxMMAC.setRestoreconDone(deDir); 19462 } 19463 } 19464 19465 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 19466 + " packages; restoreconNeeded was " + restoreconNeeded); 19467 } 19468 19469 /** 19470 * Prepare app data for the given app just after it was installed or 19471 * upgraded. This method carefully only touches users that it's installed 19472 * for, and it forces a restorecon to handle any seinfo changes. 19473 * <p> 19474 * Verifies that directories exist and that ownership and labeling is 19475 * correct for all installed apps. If there is an ownership mismatch, it 19476 * will try recovering system apps by wiping data; third-party app data is 19477 * left intact. 19478 * <p> 19479 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 19480 */ 19481 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 19482 final PackageSetting ps; 19483 synchronized (mPackages) { 19484 ps = mSettings.mPackages.get(pkg.packageName); 19485 mSettings.writeKernelMappingLPr(ps); 19486 } 19487 19488 final UserManager um = mContext.getSystemService(UserManager.class); 19489 for (UserInfo user : um.getUsers()) { 19490 final int flags; 19491 if (um.isUserUnlockingOrUnlocked(user.id)) { 19492 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19493 } else if (um.isUserRunning(user.id)) { 19494 flags = StorageManager.FLAG_STORAGE_DE; 19495 } else { 19496 continue; 19497 } 19498 19499 if (ps.getInstalled(user.id)) { 19500 // Whenever an app changes, force a restorecon of its data 19501 // TODO: when user data is locked, mark that we're still dirty 19502 prepareAppDataLIF(pkg, user.id, flags, true); 19503 } 19504 } 19505 } 19506 19507 /** 19508 * Prepare app data for the given app. 19509 * <p> 19510 * Verifies that directories exist and that ownership and labeling is 19511 * correct for all installed apps. If there is an ownership mismatch, this 19512 * will try recovering system apps by wiping data; third-party app data is 19513 * left intact. 19514 */ 19515 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags, 19516 boolean restoreconNeeded) { 19517 if (pkg == null) { 19518 Slog.wtf(TAG, "Package was null!", new Throwable()); 19519 return; 19520 } 19521 prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded); 19522 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19523 for (int i = 0; i < childCount; i++) { 19524 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded); 19525 } 19526 } 19527 19528 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags, 19529 boolean restoreconNeeded) { 19530 if (DEBUG_APP_DATA) { 19531 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 19532 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 19533 } 19534 19535 final String volumeUuid = pkg.volumeUuid; 19536 final String packageName = pkg.packageName; 19537 final ApplicationInfo app = pkg.applicationInfo; 19538 final int appId = UserHandle.getAppId(app.uid); 19539 19540 Preconditions.checkNotNull(app.seinfo); 19541 19542 try { 19543 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19544 appId, app.seinfo, app.targetSdkVersion); 19545 } catch (InstallerException e) { 19546 if (app.isSystemApp()) { 19547 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 19548 + ", but trying to recover: " + e); 19549 destroyAppDataLeafLIF(pkg, userId, flags); 19550 try { 19551 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19552 appId, app.seinfo, app.targetSdkVersion); 19553 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 19554 } catch (InstallerException e2) { 19555 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 19556 } 19557 } else { 19558 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 19559 } 19560 } 19561 19562 if (restoreconNeeded) { 19563 try { 19564 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, 19565 app.seinfo); 19566 } catch (InstallerException e) { 19567 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 19568 } 19569 } 19570 19571 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19572 try { 19573 // CE storage is unlocked right now, so read out the inode and 19574 // remember for use later when it's locked 19575 // TODO: mark this structure as dirty so we persist it! 19576 final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId, 19577 StorageManager.FLAG_STORAGE_CE); 19578 synchronized (mPackages) { 19579 final PackageSetting ps = mSettings.mPackages.get(packageName); 19580 if (ps != null) { 19581 ps.setCeDataInode(ceDataInode, userId); 19582 } 19583 } 19584 } catch (InstallerException e) { 19585 Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e); 19586 } 19587 } 19588 19589 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19590 } 19591 19592 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 19593 if (pkg == null) { 19594 Slog.wtf(TAG, "Package was null!", new Throwable()); 19595 return; 19596 } 19597 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19598 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19599 for (int i = 0; i < childCount; i++) { 19600 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 19601 } 19602 } 19603 19604 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 19605 final String volumeUuid = pkg.volumeUuid; 19606 final String packageName = pkg.packageName; 19607 final ApplicationInfo app = pkg.applicationInfo; 19608 19609 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19610 // Create a native library symlink only if we have native libraries 19611 // and if the native libraries are 32 bit libraries. We do not provide 19612 // this symlink for 64 bit libraries. 19613 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 19614 final String nativeLibPath = app.nativeLibraryDir; 19615 try { 19616 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 19617 nativeLibPath, userId); 19618 } catch (InstallerException e) { 19619 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 19620 } 19621 } 19622 } 19623 } 19624 19625 /** 19626 * For system apps on non-FBE devices, this method migrates any existing 19627 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 19628 * requested by the app. 19629 */ 19630 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 19631 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 19632 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 19633 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 19634 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 19635 try { 19636 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 19637 storageTarget); 19638 } catch (InstallerException e) { 19639 logCriticalInfo(Log.WARN, 19640 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 19641 } 19642 return true; 19643 } else { 19644 return false; 19645 } 19646 } 19647 19648 public PackageFreezer freezePackage(String packageName, String killReason) { 19649 return new PackageFreezer(packageName, killReason); 19650 } 19651 19652 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 19653 String killReason) { 19654 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 19655 return new PackageFreezer(); 19656 } else { 19657 return freezePackage(packageName, killReason); 19658 } 19659 } 19660 19661 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 19662 String killReason) { 19663 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 19664 return new PackageFreezer(); 19665 } else { 19666 return freezePackage(packageName, killReason); 19667 } 19668 } 19669 19670 /** 19671 * Class that freezes and kills the given package upon creation, and 19672 * unfreezes it upon closing. This is typically used when doing surgery on 19673 * app code/data to prevent the app from running while you're working. 19674 */ 19675 private class PackageFreezer implements AutoCloseable { 19676 private final String mPackageName; 19677 private final PackageFreezer[] mChildren; 19678 19679 private final boolean mWeFroze; 19680 19681 private final AtomicBoolean mClosed = new AtomicBoolean(); 19682 private final CloseGuard mCloseGuard = CloseGuard.get(); 19683 19684 /** 19685 * Create and return a stub freezer that doesn't actually do anything, 19686 * typically used when someone requested 19687 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 19688 * {@link PackageManager#DELETE_DONT_KILL_APP}. 19689 */ 19690 public PackageFreezer() { 19691 mPackageName = null; 19692 mChildren = null; 19693 mWeFroze = false; 19694 mCloseGuard.open("close"); 19695 } 19696 19697 public PackageFreezer(String packageName, String killReason) { 19698 synchronized (mPackages) { 19699 mPackageName = packageName; 19700 mWeFroze = mFrozenPackages.add(mPackageName); 19701 19702 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 19703 if (ps != null) { 19704 killApplication(ps.name, ps.appId, killReason); 19705 } 19706 19707 final PackageParser.Package p = mPackages.get(packageName); 19708 if (p != null && p.childPackages != null) { 19709 final int N = p.childPackages.size(); 19710 mChildren = new PackageFreezer[N]; 19711 for (int i = 0; i < N; i++) { 19712 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 19713 killReason); 19714 } 19715 } else { 19716 mChildren = null; 19717 } 19718 } 19719 mCloseGuard.open("close"); 19720 } 19721 19722 @Override 19723 protected void finalize() throws Throwable { 19724 try { 19725 mCloseGuard.warnIfOpen(); 19726 close(); 19727 } finally { 19728 super.finalize(); 19729 } 19730 } 19731 19732 @Override 19733 public void close() { 19734 mCloseGuard.close(); 19735 if (mClosed.compareAndSet(false, true)) { 19736 synchronized (mPackages) { 19737 if (mWeFroze) { 19738 mFrozenPackages.remove(mPackageName); 19739 } 19740 19741 if (mChildren != null) { 19742 for (PackageFreezer freezer : mChildren) { 19743 freezer.close(); 19744 } 19745 } 19746 } 19747 } 19748 } 19749 } 19750 19751 /** 19752 * Verify that given package is currently frozen. 19753 */ 19754 private void checkPackageFrozen(String packageName) { 19755 synchronized (mPackages) { 19756 if (!mFrozenPackages.contains(packageName)) { 19757 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 19758 } 19759 } 19760 } 19761 19762 @Override 19763 public int movePackage(final String packageName, final String volumeUuid) { 19764 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19765 19766 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 19767 final int moveId = mNextMoveId.getAndIncrement(); 19768 mHandler.post(new Runnable() { 19769 @Override 19770 public void run() { 19771 try { 19772 movePackageInternal(packageName, volumeUuid, moveId, user); 19773 } catch (PackageManagerException e) { 19774 Slog.w(TAG, "Failed to move " + packageName, e); 19775 mMoveCallbacks.notifyStatusChanged(moveId, 19776 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19777 } 19778 } 19779 }); 19780 return moveId; 19781 } 19782 19783 private void movePackageInternal(final String packageName, final String volumeUuid, 19784 final int moveId, UserHandle user) throws PackageManagerException { 19785 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19786 final PackageManager pm = mContext.getPackageManager(); 19787 19788 final boolean currentAsec; 19789 final String currentVolumeUuid; 19790 final File codeFile; 19791 final String installerPackageName; 19792 final String packageAbiOverride; 19793 final int appId; 19794 final String seinfo; 19795 final String label; 19796 final int targetSdkVersion; 19797 final PackageFreezer freezer; 19798 final int[] installedUserIds; 19799 19800 // reader 19801 synchronized (mPackages) { 19802 final PackageParser.Package pkg = mPackages.get(packageName); 19803 final PackageSetting ps = mSettings.mPackages.get(packageName); 19804 if (pkg == null || ps == null) { 19805 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 19806 } 19807 19808 if (pkg.applicationInfo.isSystemApp()) { 19809 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 19810 "Cannot move system application"); 19811 } 19812 19813 if (pkg.applicationInfo.isExternalAsec()) { 19814 currentAsec = true; 19815 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 19816 } else if (pkg.applicationInfo.isForwardLocked()) { 19817 currentAsec = true; 19818 currentVolumeUuid = "forward_locked"; 19819 } else { 19820 currentAsec = false; 19821 currentVolumeUuid = ps.volumeUuid; 19822 19823 final File probe = new File(pkg.codePath); 19824 final File probeOat = new File(probe, "oat"); 19825 if (!probe.isDirectory() || !probeOat.isDirectory()) { 19826 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19827 "Move only supported for modern cluster style installs"); 19828 } 19829 } 19830 19831 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 19832 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19833 "Package already moved to " + volumeUuid); 19834 } 19835 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 19836 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 19837 "Device admin cannot be moved"); 19838 } 19839 19840 if (mFrozenPackages.contains(packageName)) { 19841 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 19842 "Failed to move already frozen package"); 19843 } 19844 19845 codeFile = new File(pkg.codePath); 19846 installerPackageName = ps.installerPackageName; 19847 packageAbiOverride = ps.cpuAbiOverrideString; 19848 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 19849 seinfo = pkg.applicationInfo.seinfo; 19850 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 19851 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 19852 freezer = new PackageFreezer(packageName, "movePackageInternal"); 19853 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 19854 } 19855 19856 final Bundle extras = new Bundle(); 19857 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 19858 extras.putString(Intent.EXTRA_TITLE, label); 19859 mMoveCallbacks.notifyCreated(moveId, extras); 19860 19861 int installFlags; 19862 final boolean moveCompleteApp; 19863 final File measurePath; 19864 19865 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 19866 installFlags = INSTALL_INTERNAL; 19867 moveCompleteApp = !currentAsec; 19868 measurePath = Environment.getDataAppDirectory(volumeUuid); 19869 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 19870 installFlags = INSTALL_EXTERNAL; 19871 moveCompleteApp = false; 19872 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 19873 } else { 19874 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 19875 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 19876 || !volume.isMountedWritable()) { 19877 freezer.close(); 19878 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19879 "Move location not mounted private volume"); 19880 } 19881 19882 Preconditions.checkState(!currentAsec); 19883 19884 installFlags = INSTALL_INTERNAL; 19885 moveCompleteApp = true; 19886 measurePath = Environment.getDataAppDirectory(volumeUuid); 19887 } 19888 19889 final PackageStats stats = new PackageStats(null, -1); 19890 synchronized (mInstaller) { 19891 for (int userId : installedUserIds) { 19892 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 19893 freezer.close(); 19894 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19895 "Failed to measure package size"); 19896 } 19897 } 19898 } 19899 19900 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 19901 + stats.dataSize); 19902 19903 final long startFreeBytes = measurePath.getFreeSpace(); 19904 final long sizeBytes; 19905 if (moveCompleteApp) { 19906 sizeBytes = stats.codeSize + stats.dataSize; 19907 } else { 19908 sizeBytes = stats.codeSize; 19909 } 19910 19911 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 19912 freezer.close(); 19913 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19914 "Not enough free space to move"); 19915 } 19916 19917 mMoveCallbacks.notifyStatusChanged(moveId, 10); 19918 19919 final CountDownLatch installedLatch = new CountDownLatch(1); 19920 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 19921 @Override 19922 public void onUserActionRequired(Intent intent) throws RemoteException { 19923 throw new IllegalStateException(); 19924 } 19925 19926 @Override 19927 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 19928 Bundle extras) throws RemoteException { 19929 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 19930 + PackageManager.installStatusToString(returnCode, msg)); 19931 19932 installedLatch.countDown(); 19933 freezer.close(); 19934 19935 final int status = PackageManager.installStatusToPublicStatus(returnCode); 19936 switch (status) { 19937 case PackageInstaller.STATUS_SUCCESS: 19938 mMoveCallbacks.notifyStatusChanged(moveId, 19939 PackageManager.MOVE_SUCCEEDED); 19940 break; 19941 case PackageInstaller.STATUS_FAILURE_STORAGE: 19942 mMoveCallbacks.notifyStatusChanged(moveId, 19943 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 19944 break; 19945 default: 19946 mMoveCallbacks.notifyStatusChanged(moveId, 19947 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19948 break; 19949 } 19950 } 19951 }; 19952 19953 final MoveInfo move; 19954 if (moveCompleteApp) { 19955 // Kick off a thread to report progress estimates 19956 new Thread() { 19957 @Override 19958 public void run() { 19959 while (true) { 19960 try { 19961 if (installedLatch.await(1, TimeUnit.SECONDS)) { 19962 break; 19963 } 19964 } catch (InterruptedException ignored) { 19965 } 19966 19967 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 19968 final int progress = 10 + (int) MathUtils.constrain( 19969 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 19970 mMoveCallbacks.notifyStatusChanged(moveId, progress); 19971 } 19972 } 19973 }.start(); 19974 19975 final String dataAppName = codeFile.getName(); 19976 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 19977 dataAppName, appId, seinfo, targetSdkVersion); 19978 } else { 19979 move = null; 19980 } 19981 19982 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 19983 19984 final Message msg = mHandler.obtainMessage(INIT_COPY); 19985 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 19986 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 19987 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 19988 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/); 19989 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 19990 msg.obj = params; 19991 19992 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 19993 System.identityHashCode(msg.obj)); 19994 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 19995 System.identityHashCode(msg.obj)); 19996 19997 mHandler.sendMessage(msg); 19998 } 19999 20000 @Override 20001 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 20002 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 20003 20004 final int realMoveId = mNextMoveId.getAndIncrement(); 20005 final Bundle extras = new Bundle(); 20006 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 20007 mMoveCallbacks.notifyCreated(realMoveId, extras); 20008 20009 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 20010 @Override 20011 public void onCreated(int moveId, Bundle extras) { 20012 // Ignored 20013 } 20014 20015 @Override 20016 public void onStatusChanged(int moveId, int status, long estMillis) { 20017 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 20018 } 20019 }; 20020 20021 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20022 storage.setPrimaryStorageUuid(volumeUuid, callback); 20023 return realMoveId; 20024 } 20025 20026 @Override 20027 public int getMoveStatus(int moveId) { 20028 mContext.enforceCallingOrSelfPermission( 20029 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20030 return mMoveCallbacks.mLastStatus.get(moveId); 20031 } 20032 20033 @Override 20034 public void registerMoveCallback(IPackageMoveObserver callback) { 20035 mContext.enforceCallingOrSelfPermission( 20036 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20037 mMoveCallbacks.register(callback); 20038 } 20039 20040 @Override 20041 public void unregisterMoveCallback(IPackageMoveObserver callback) { 20042 mContext.enforceCallingOrSelfPermission( 20043 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20044 mMoveCallbacks.unregister(callback); 20045 } 20046 20047 @Override 20048 public boolean setInstallLocation(int loc) { 20049 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 20050 null); 20051 if (getInstallLocation() == loc) { 20052 return true; 20053 } 20054 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 20055 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 20056 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 20057 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 20058 return true; 20059 } 20060 return false; 20061 } 20062 20063 @Override 20064 public int getInstallLocation() { 20065 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 20066 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 20067 PackageHelper.APP_INSTALL_AUTO); 20068 } 20069 20070 /** Called by UserManagerService */ 20071 void cleanUpUser(UserManagerService userManager, int userHandle) { 20072 synchronized (mPackages) { 20073 mDirtyUsers.remove(userHandle); 20074 mUserNeedsBadging.delete(userHandle); 20075 mSettings.removeUserLPw(userHandle); 20076 mPendingBroadcasts.remove(userHandle); 20077 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 20078 removeUnusedPackagesLPw(userManager, userHandle); 20079 } 20080 } 20081 20082 /** 20083 * We're removing userHandle and would like to remove any downloaded packages 20084 * that are no longer in use by any other user. 20085 * @param userHandle the user being removed 20086 */ 20087 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 20088 final boolean DEBUG_CLEAN_APKS = false; 20089 int [] users = userManager.getUserIds(); 20090 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 20091 while (psit.hasNext()) { 20092 PackageSetting ps = psit.next(); 20093 if (ps.pkg == null) { 20094 continue; 20095 } 20096 final String packageName = ps.pkg.packageName; 20097 // Skip over if system app 20098 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 20099 continue; 20100 } 20101 if (DEBUG_CLEAN_APKS) { 20102 Slog.i(TAG, "Checking package " + packageName); 20103 } 20104 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 20105 if (keep) { 20106 if (DEBUG_CLEAN_APKS) { 20107 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 20108 } 20109 } else { 20110 for (int i = 0; i < users.length; i++) { 20111 if (users[i] != userHandle && ps.getInstalled(users[i])) { 20112 keep = true; 20113 if (DEBUG_CLEAN_APKS) { 20114 Slog.i(TAG, " Keeping package " + packageName + " for user " 20115 + users[i]); 20116 } 20117 break; 20118 } 20119 } 20120 } 20121 if (!keep) { 20122 if (DEBUG_CLEAN_APKS) { 20123 Slog.i(TAG, " Removing package " + packageName); 20124 } 20125 mHandler.post(new Runnable() { 20126 public void run() { 20127 deletePackageX(packageName, userHandle, 0); 20128 } //end run 20129 }); 20130 } 20131 } 20132 } 20133 20134 /** Called by UserManagerService */ 20135 void createNewUser(int userId) { 20136 synchronized (mInstallLock) { 20137 mSettings.createNewUserLI(this, mInstaller, userId); 20138 } 20139 synchronized (mPackages) { 20140 scheduleWritePackageRestrictionsLocked(userId); 20141 scheduleWritePackageListLocked(userId); 20142 applyFactoryDefaultBrowserLPw(userId); 20143 primeDomainVerificationsLPw(userId); 20144 } 20145 } 20146 20147 void onBeforeUserStartUninitialized(final int userId) { 20148 synchronized (mPackages) { 20149 if (mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 20150 return; 20151 } 20152 } 20153 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 20154 // If permission review for legacy apps is required, we represent 20155 // dagerous permissions for such apps as always granted runtime 20156 // permissions to keep per user flag state whether review is needed. 20157 // Hence, if a new user is added we have to propagate dangerous 20158 // permission grants for these legacy apps. 20159 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 20160 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 20161 | UPDATE_PERMISSIONS_REPLACE_ALL); 20162 } 20163 } 20164 20165 @Override 20166 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 20167 mContext.enforceCallingOrSelfPermission( 20168 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 20169 "Only package verification agents can read the verifier device identity"); 20170 20171 synchronized (mPackages) { 20172 return mSettings.getVerifierDeviceIdentityLPw(); 20173 } 20174 } 20175 20176 @Override 20177 public void setPermissionEnforced(String permission, boolean enforced) { 20178 // TODO: Now that we no longer change GID for storage, this should to away. 20179 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 20180 "setPermissionEnforced"); 20181 if (READ_EXTERNAL_STORAGE.equals(permission)) { 20182 synchronized (mPackages) { 20183 if (mSettings.mReadExternalStorageEnforced == null 20184 || mSettings.mReadExternalStorageEnforced != enforced) { 20185 mSettings.mReadExternalStorageEnforced = enforced; 20186 mSettings.writeLPr(); 20187 } 20188 } 20189 // kill any non-foreground processes so we restart them and 20190 // grant/revoke the GID. 20191 final IActivityManager am = ActivityManagerNative.getDefault(); 20192 if (am != null) { 20193 final long token = Binder.clearCallingIdentity(); 20194 try { 20195 am.killProcessesBelowForeground("setPermissionEnforcement"); 20196 } catch (RemoteException e) { 20197 } finally { 20198 Binder.restoreCallingIdentity(token); 20199 } 20200 } 20201 } else { 20202 throw new IllegalArgumentException("No selective enforcement for " + permission); 20203 } 20204 } 20205 20206 @Override 20207 @Deprecated 20208 public boolean isPermissionEnforced(String permission) { 20209 return true; 20210 } 20211 20212 @Override 20213 public boolean isStorageLow() { 20214 final long token = Binder.clearCallingIdentity(); 20215 try { 20216 final DeviceStorageMonitorInternal 20217 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 20218 if (dsm != null) { 20219 return dsm.isMemoryLow(); 20220 } else { 20221 return false; 20222 } 20223 } finally { 20224 Binder.restoreCallingIdentity(token); 20225 } 20226 } 20227 20228 @Override 20229 public IPackageInstaller getPackageInstaller() { 20230 return mInstallerService; 20231 } 20232 20233 private boolean userNeedsBadging(int userId) { 20234 int index = mUserNeedsBadging.indexOfKey(userId); 20235 if (index < 0) { 20236 final UserInfo userInfo; 20237 final long token = Binder.clearCallingIdentity(); 20238 try { 20239 userInfo = sUserManager.getUserInfo(userId); 20240 } finally { 20241 Binder.restoreCallingIdentity(token); 20242 } 20243 final boolean b; 20244 if (userInfo != null && userInfo.isManagedProfile()) { 20245 b = true; 20246 } else { 20247 b = false; 20248 } 20249 mUserNeedsBadging.put(userId, b); 20250 return b; 20251 } 20252 return mUserNeedsBadging.valueAt(index); 20253 } 20254 20255 @Override 20256 public KeySet getKeySetByAlias(String packageName, String alias) { 20257 if (packageName == null || alias == null) { 20258 return null; 20259 } 20260 synchronized(mPackages) { 20261 final PackageParser.Package pkg = mPackages.get(packageName); 20262 if (pkg == null) { 20263 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20264 throw new IllegalArgumentException("Unknown package: " + packageName); 20265 } 20266 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20267 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 20268 } 20269 } 20270 20271 @Override 20272 public KeySet getSigningKeySet(String packageName) { 20273 if (packageName == null) { 20274 return null; 20275 } 20276 synchronized(mPackages) { 20277 final PackageParser.Package pkg = mPackages.get(packageName); 20278 if (pkg == null) { 20279 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20280 throw new IllegalArgumentException("Unknown package: " + packageName); 20281 } 20282 if (pkg.applicationInfo.uid != Binder.getCallingUid() 20283 && Process.SYSTEM_UID != Binder.getCallingUid()) { 20284 throw new SecurityException("May not access signing KeySet of other apps."); 20285 } 20286 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20287 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 20288 } 20289 } 20290 20291 @Override 20292 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 20293 if (packageName == null || ks == null) { 20294 return false; 20295 } 20296 synchronized(mPackages) { 20297 final PackageParser.Package pkg = mPackages.get(packageName); 20298 if (pkg == null) { 20299 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20300 throw new IllegalArgumentException("Unknown package: " + packageName); 20301 } 20302 IBinder ksh = ks.getToken(); 20303 if (ksh instanceof KeySetHandle) { 20304 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20305 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 20306 } 20307 return false; 20308 } 20309 } 20310 20311 @Override 20312 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 20313 if (packageName == null || ks == null) { 20314 return false; 20315 } 20316 synchronized(mPackages) { 20317 final PackageParser.Package pkg = mPackages.get(packageName); 20318 if (pkg == null) { 20319 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20320 throw new IllegalArgumentException("Unknown package: " + packageName); 20321 } 20322 IBinder ksh = ks.getToken(); 20323 if (ksh instanceof KeySetHandle) { 20324 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20325 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 20326 } 20327 return false; 20328 } 20329 } 20330 20331 private void deletePackageIfUnusedLPr(final String packageName) { 20332 PackageSetting ps = mSettings.mPackages.get(packageName); 20333 if (ps == null) { 20334 return; 20335 } 20336 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 20337 // TODO Implement atomic delete if package is unused 20338 // It is currently possible that the package will be deleted even if it is installed 20339 // after this method returns. 20340 mHandler.post(new Runnable() { 20341 public void run() { 20342 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 20343 } 20344 }); 20345 } 20346 } 20347 20348 /** 20349 * Check and throw if the given before/after packages would be considered a 20350 * downgrade. 20351 */ 20352 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 20353 throws PackageManagerException { 20354 if (after.versionCode < before.mVersionCode) { 20355 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20356 "Update version code " + after.versionCode + " is older than current " 20357 + before.mVersionCode); 20358 } else if (after.versionCode == before.mVersionCode) { 20359 if (after.baseRevisionCode < before.baseRevisionCode) { 20360 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20361 "Update base revision code " + after.baseRevisionCode 20362 + " is older than current " + before.baseRevisionCode); 20363 } 20364 20365 if (!ArrayUtils.isEmpty(after.splitNames)) { 20366 for (int i = 0; i < after.splitNames.length; i++) { 20367 final String splitName = after.splitNames[i]; 20368 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 20369 if (j != -1) { 20370 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 20371 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20372 "Update split " + splitName + " revision code " 20373 + after.splitRevisionCodes[i] + " is older than current " 20374 + before.splitRevisionCodes[j]); 20375 } 20376 } 20377 } 20378 } 20379 } 20380 } 20381 20382 private static class MoveCallbacks extends Handler { 20383 private static final int MSG_CREATED = 1; 20384 private static final int MSG_STATUS_CHANGED = 2; 20385 20386 private final RemoteCallbackList<IPackageMoveObserver> 20387 mCallbacks = new RemoteCallbackList<>(); 20388 20389 private final SparseIntArray mLastStatus = new SparseIntArray(); 20390 20391 public MoveCallbacks(Looper looper) { 20392 super(looper); 20393 } 20394 20395 public void register(IPackageMoveObserver callback) { 20396 mCallbacks.register(callback); 20397 } 20398 20399 public void unregister(IPackageMoveObserver callback) { 20400 mCallbacks.unregister(callback); 20401 } 20402 20403 @Override 20404 public void handleMessage(Message msg) { 20405 final SomeArgs args = (SomeArgs) msg.obj; 20406 final int n = mCallbacks.beginBroadcast(); 20407 for (int i = 0; i < n; i++) { 20408 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 20409 try { 20410 invokeCallback(callback, msg.what, args); 20411 } catch (RemoteException ignored) { 20412 } 20413 } 20414 mCallbacks.finishBroadcast(); 20415 args.recycle(); 20416 } 20417 20418 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 20419 throws RemoteException { 20420 switch (what) { 20421 case MSG_CREATED: { 20422 callback.onCreated(args.argi1, (Bundle) args.arg2); 20423 break; 20424 } 20425 case MSG_STATUS_CHANGED: { 20426 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 20427 break; 20428 } 20429 } 20430 } 20431 20432 private void notifyCreated(int moveId, Bundle extras) { 20433 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 20434 20435 final SomeArgs args = SomeArgs.obtain(); 20436 args.argi1 = moveId; 20437 args.arg2 = extras; 20438 obtainMessage(MSG_CREATED, args).sendToTarget(); 20439 } 20440 20441 private void notifyStatusChanged(int moveId, int status) { 20442 notifyStatusChanged(moveId, status, -1); 20443 } 20444 20445 private void notifyStatusChanged(int moveId, int status, long estMillis) { 20446 Slog.v(TAG, "Move " + moveId + " status " + status); 20447 20448 final SomeArgs args = SomeArgs.obtain(); 20449 args.argi1 = moveId; 20450 args.argi2 = status; 20451 args.arg3 = estMillis; 20452 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 20453 20454 synchronized (mLastStatus) { 20455 mLastStatus.put(moveId, status); 20456 } 20457 } 20458 } 20459 20460 private final static class OnPermissionChangeListeners extends Handler { 20461 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 20462 20463 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 20464 new RemoteCallbackList<>(); 20465 20466 public OnPermissionChangeListeners(Looper looper) { 20467 super(looper); 20468 } 20469 20470 @Override 20471 public void handleMessage(Message msg) { 20472 switch (msg.what) { 20473 case MSG_ON_PERMISSIONS_CHANGED: { 20474 final int uid = msg.arg1; 20475 handleOnPermissionsChanged(uid); 20476 } break; 20477 } 20478 } 20479 20480 public void addListenerLocked(IOnPermissionsChangeListener listener) { 20481 mPermissionListeners.register(listener); 20482 20483 } 20484 20485 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 20486 mPermissionListeners.unregister(listener); 20487 } 20488 20489 public void onPermissionsChanged(int uid) { 20490 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 20491 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 20492 } 20493 } 20494 20495 private void handleOnPermissionsChanged(int uid) { 20496 final int count = mPermissionListeners.beginBroadcast(); 20497 try { 20498 for (int i = 0; i < count; i++) { 20499 IOnPermissionsChangeListener callback = mPermissionListeners 20500 .getBroadcastItem(i); 20501 try { 20502 callback.onPermissionsChanged(uid); 20503 } catch (RemoteException e) { 20504 Log.e(TAG, "Permission listener is dead", e); 20505 } 20506 } 20507 } finally { 20508 mPermissionListeners.finishBroadcast(); 20509 } 20510 } 20511 } 20512 20513 private class PackageManagerInternalImpl extends PackageManagerInternal { 20514 @Override 20515 public void setLocationPackagesProvider(PackagesProvider provider) { 20516 synchronized (mPackages) { 20517 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 20518 } 20519 } 20520 20521 @Override 20522 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 20523 synchronized (mPackages) { 20524 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 20525 } 20526 } 20527 20528 @Override 20529 public void setSmsAppPackagesProvider(PackagesProvider provider) { 20530 synchronized (mPackages) { 20531 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 20532 } 20533 } 20534 20535 @Override 20536 public void setDialerAppPackagesProvider(PackagesProvider provider) { 20537 synchronized (mPackages) { 20538 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 20539 } 20540 } 20541 20542 @Override 20543 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 20544 synchronized (mPackages) { 20545 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 20546 } 20547 } 20548 20549 @Override 20550 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 20551 synchronized (mPackages) { 20552 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 20553 } 20554 } 20555 20556 @Override 20557 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 20558 synchronized (mPackages) { 20559 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 20560 packageName, userId); 20561 } 20562 } 20563 20564 @Override 20565 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 20566 synchronized (mPackages) { 20567 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 20568 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 20569 packageName, userId); 20570 } 20571 } 20572 20573 @Override 20574 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 20575 synchronized (mPackages) { 20576 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 20577 packageName, userId); 20578 } 20579 } 20580 20581 @Override 20582 public void setKeepUninstalledPackages(final List<String> packageList) { 20583 Preconditions.checkNotNull(packageList); 20584 List<String> removedFromList = null; 20585 synchronized (mPackages) { 20586 if (mKeepUninstalledPackages != null) { 20587 final int packagesCount = mKeepUninstalledPackages.size(); 20588 for (int i = 0; i < packagesCount; i++) { 20589 String oldPackage = mKeepUninstalledPackages.get(i); 20590 if (packageList != null && packageList.contains(oldPackage)) { 20591 continue; 20592 } 20593 if (removedFromList == null) { 20594 removedFromList = new ArrayList<>(); 20595 } 20596 removedFromList.add(oldPackage); 20597 } 20598 } 20599 mKeepUninstalledPackages = new ArrayList<>(packageList); 20600 if (removedFromList != null) { 20601 final int removedCount = removedFromList.size(); 20602 for (int i = 0; i < removedCount; i++) { 20603 deletePackageIfUnusedLPr(removedFromList.get(i)); 20604 } 20605 } 20606 } 20607 } 20608 20609 @Override 20610 public boolean isPermissionsReviewRequired(String packageName, int userId) { 20611 synchronized (mPackages) { 20612 // If we do not support permission review, done. 20613 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 20614 return false; 20615 } 20616 20617 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 20618 if (packageSetting == null) { 20619 return false; 20620 } 20621 20622 // Permission review applies only to apps not supporting the new permission model. 20623 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 20624 return false; 20625 } 20626 20627 // Legacy apps have the permission and get user consent on launch. 20628 PermissionsState permissionsState = packageSetting.getPermissionsState(); 20629 return permissionsState.isPermissionReviewRequired(userId); 20630 } 20631 } 20632 20633 @Override 20634 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 20635 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 20636 } 20637 20638 @Override 20639 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 20640 int userId) { 20641 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 20642 } 20643 } 20644 20645 @Override 20646 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 20647 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 20648 synchronized (mPackages) { 20649 final long identity = Binder.clearCallingIdentity(); 20650 try { 20651 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 20652 packageNames, userId); 20653 } finally { 20654 Binder.restoreCallingIdentity(identity); 20655 } 20656 } 20657 } 20658 20659 private static void enforceSystemOrPhoneCaller(String tag) { 20660 int callingUid = Binder.getCallingUid(); 20661 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 20662 throw new SecurityException( 20663 "Cannot call " + tag + " from UID " + callingUid); 20664 } 20665 } 20666 20667 boolean isHistoricalPackageUsageAvailable() { 20668 return mPackageUsage.isHistoricalPackageUsageAvailable(); 20669 } 20670 20671 /** 20672 * Return a <b>copy</b> of the collection of packages known to the package manager. 20673 * @return A copy of the values of mPackages. 20674 */ 20675 Collection<PackageParser.Package> getPackages() { 20676 synchronized (mPackages) { 20677 return new ArrayList<>(mPackages.values()); 20678 } 20679 } 20680 20681 /** 20682 * Logs process start information (including base APK hash) to the security log. 20683 * @hide 20684 */ 20685 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 20686 String apkFile, int pid) { 20687 if (!SecurityLog.isLoggingEnabled()) { 20688 return; 20689 } 20690 Bundle data = new Bundle(); 20691 data.putLong("startTimestamp", System.currentTimeMillis()); 20692 data.putString("processName", processName); 20693 data.putInt("uid", uid); 20694 data.putString("seinfo", seinfo); 20695 data.putString("apkFile", apkFile); 20696 data.putInt("pid", pid); 20697 Message msg = mProcessLoggingHandler.obtainMessage( 20698 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 20699 msg.setData(data); 20700 mProcessLoggingHandler.sendMessage(msg); 20701 } 20702} 20703