PackageManagerService.java revision f86ce783c6726694ad9f6d5e9b5d3b58c3b7e09c
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.app.usage.UsageStatsManager; 113import android.content.BroadcastReceiver; 114import android.content.ComponentName; 115import android.content.Context; 116import android.content.IIntentReceiver; 117import android.content.Intent; 118import android.content.IntentFilter; 119import android.content.IntentSender; 120import android.content.IntentSender.SendIntentException; 121import android.content.ServiceConnection; 122import android.content.pm.ActivityInfo; 123import android.content.pm.ApplicationInfo; 124import android.content.pm.AppsQueryHelper; 125import android.content.pm.ComponentInfo; 126import android.content.pm.EphemeralApplicationInfo; 127import android.content.pm.EphemeralResolveInfo; 128import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo; 129import android.content.pm.FeatureInfo; 130import android.content.pm.IOnPermissionsChangeListener; 131import android.content.pm.IPackageDataObserver; 132import android.content.pm.IPackageDeleteObserver; 133import android.content.pm.IPackageDeleteObserver2; 134import android.content.pm.IPackageInstallObserver2; 135import android.content.pm.IPackageInstaller; 136import android.content.pm.IPackageManager; 137import android.content.pm.IPackageMoveObserver; 138import android.content.pm.IPackageStatsObserver; 139import android.content.pm.InstrumentationInfo; 140import android.content.pm.IntentFilterVerificationInfo; 141import android.content.pm.KeySet; 142import android.content.pm.PackageCleanItem; 143import android.content.pm.PackageInfo; 144import android.content.pm.PackageInfoLite; 145import android.content.pm.PackageInstaller; 146import android.content.pm.PackageManager; 147import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 148import android.content.pm.PackageManagerInternal; 149import android.content.pm.PackageParser; 150import android.content.pm.PackageParser.ActivityIntentInfo; 151import android.content.pm.PackageParser.PackageLite; 152import android.content.pm.PackageParser.PackageParserException; 153import android.content.pm.PackageStats; 154import android.content.pm.PackageUserState; 155import android.content.pm.ParceledListSlice; 156import android.content.pm.PermissionGroupInfo; 157import android.content.pm.PermissionInfo; 158import android.content.pm.ProviderInfo; 159import android.content.pm.ResolveInfo; 160import android.content.pm.ServiceInfo; 161import android.content.pm.Signature; 162import android.content.pm.UserInfo; 163import android.content.pm.VerifierDeviceIdentity; 164import android.content.pm.VerifierInfo; 165import android.content.res.Resources; 166import android.graphics.Bitmap; 167import android.hardware.display.DisplayManager; 168import android.net.Uri; 169import android.os.Binder; 170import android.os.Build; 171import android.os.Bundle; 172import android.os.Debug; 173import android.os.Environment; 174import android.os.Environment.UserEnvironment; 175import android.os.FileUtils; 176import android.os.Handler; 177import android.os.IBinder; 178import android.os.Looper; 179import android.os.Message; 180import android.os.Parcel; 181import android.os.ParcelFileDescriptor; 182import android.os.Process; 183import android.os.RemoteCallbackList; 184import android.os.RemoteException; 185import android.os.ResultReceiver; 186import android.os.SELinux; 187import android.os.ServiceManager; 188import android.os.SystemClock; 189import android.os.SystemProperties; 190import android.os.Trace; 191import android.os.UserHandle; 192import android.os.UserManager; 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.view.Display; 221 222import com.android.internal.R; 223import com.android.internal.annotations.GuardedBy; 224import com.android.internal.app.IMediaContainerService; 225import com.android.internal.app.ResolverActivity; 226import com.android.internal.content.NativeLibraryHelper; 227import com.android.internal.content.PackageHelper; 228import com.android.internal.os.IParcelFileDescriptorFactory; 229import com.android.internal.os.InstallerConnection.InstallerException; 230import com.android.internal.os.SomeArgs; 231import com.android.internal.os.Zygote; 232import com.android.internal.util.ArrayUtils; 233import com.android.internal.util.FastPrintWriter; 234import com.android.internal.util.FastXmlSerializer; 235import com.android.internal.util.IndentingPrintWriter; 236import com.android.internal.util.Preconditions; 237import com.android.internal.util.XmlUtils; 238import com.android.server.EventLogTags; 239import com.android.server.FgThread; 240import com.android.server.IntentResolver; 241import com.android.server.LocalServices; 242import com.android.server.ServiceThread; 243import com.android.server.SystemConfig; 244import com.android.server.Watchdog; 245import com.android.server.pm.PermissionsState.PermissionState; 246import com.android.server.pm.Settings.DatabaseVersion; 247import com.android.server.pm.Settings.VersionInfo; 248import com.android.server.storage.DeviceStorageMonitorInternal; 249 250import dalvik.system.CloseGuard; 251import dalvik.system.DexFile; 252import dalvik.system.VMRuntime; 253 254import libcore.io.IoUtils; 255import libcore.util.EmptyArray; 256 257import org.xmlpull.v1.XmlPullParser; 258import org.xmlpull.v1.XmlPullParserException; 259import org.xmlpull.v1.XmlSerializer; 260 261import java.io.BufferedInputStream; 262import java.io.BufferedOutputStream; 263import java.io.BufferedReader; 264import java.io.ByteArrayInputStream; 265import java.io.ByteArrayOutputStream; 266import java.io.File; 267import java.io.FileDescriptor; 268import java.io.FileNotFoundException; 269import java.io.FileOutputStream; 270import java.io.FileReader; 271import java.io.FilenameFilter; 272import java.io.IOException; 273import java.io.InputStream; 274import java.io.PrintWriter; 275import java.nio.charset.StandardCharsets; 276import java.security.MessageDigest; 277import java.security.NoSuchAlgorithmException; 278import java.security.PublicKey; 279import java.security.cert.Certificate; 280import java.security.cert.CertificateEncodingException; 281import java.security.cert.CertificateException; 282import java.text.SimpleDateFormat; 283import java.util.ArrayList; 284import java.util.Arrays; 285import java.util.Collection; 286import java.util.Collections; 287import java.util.Comparator; 288import java.util.Date; 289import java.util.HashSet; 290import java.util.Iterator; 291import java.util.List; 292import java.util.Map; 293import java.util.Objects; 294import java.util.Set; 295import java.util.concurrent.CountDownLatch; 296import java.util.concurrent.TimeUnit; 297import java.util.concurrent.atomic.AtomicBoolean; 298import java.util.concurrent.atomic.AtomicInteger; 299import java.util.concurrent.atomic.AtomicLong; 300 301/** 302 * Keep track of all those APKs everywhere. 303 * <p> 304 * Internally there are two important locks: 305 * <ul> 306 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 307 * and other related state. It is a fine-grained lock that should only be held 308 * momentarily, as it's one of the most contended locks in the system. 309 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 310 * operations typically involve heavy lifting of application data on disk. Since 311 * {@code installd} is single-threaded, and it's operations can often be slow, 312 * this lock should never be acquired while already holding {@link #mPackages}. 313 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 314 * holding {@link #mInstallLock}. 315 * </ul> 316 * Many internal methods rely on the caller to hold the appropriate locks, and 317 * this contract is expressed through method name suffixes: 318 * <ul> 319 * <li>fooLI(): the caller must hold {@link #mInstallLock} 320 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 321 * being modified must be frozen 322 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 323 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 324 * </ul> 325 * <p> 326 * Because this class is very central to the platform's security; please run all 327 * CTS and unit tests whenever making modifications: 328 * 329 * <pre> 330 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 331 * $ cts-tradefed run commandAndExit cts -m AppSecurityTests 332 * </pre> 333 */ 334public class PackageManagerService extends IPackageManager.Stub { 335 static final String TAG = "PackageManager"; 336 static final boolean DEBUG_SETTINGS = false; 337 static final boolean DEBUG_PREFERRED = false; 338 static final boolean DEBUG_UPGRADE = false; 339 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 340 private static final boolean DEBUG_BACKUP = false; 341 private static final boolean DEBUG_INSTALL = false; 342 private static final boolean DEBUG_REMOVE = false; 343 private static final boolean DEBUG_BROADCASTS = false; 344 private static final boolean DEBUG_SHOW_INFO = false; 345 private static final boolean DEBUG_PACKAGE_INFO = false; 346 private static final boolean DEBUG_INTENT_MATCHING = false; 347 private static final boolean DEBUG_PACKAGE_SCANNING = false; 348 private static final boolean DEBUG_VERIFY = false; 349 private static final boolean DEBUG_FILTERS = false; 350 351 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 352 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 353 // user, but by default initialize to this. 354 static final boolean DEBUG_DEXOPT = false; 355 356 private static final boolean DEBUG_ABI_SELECTION = false; 357 private static final boolean DEBUG_EPHEMERAL = false; 358 private static final boolean DEBUG_TRIAGED_MISSING = false; 359 private static final boolean DEBUG_APP_DATA = false; 360 361 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 362 363 private static final boolean DISABLE_EPHEMERAL_APPS = true; 364 365 private static final int RADIO_UID = Process.PHONE_UID; 366 private static final int LOG_UID = Process.LOG_UID; 367 private static final int NFC_UID = Process.NFC_UID; 368 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 369 private static final int SHELL_UID = Process.SHELL_UID; 370 371 // Cap the size of permission trees that 3rd party apps can define 372 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 373 374 // Suffix used during package installation when copying/moving 375 // package apks to install directory. 376 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 377 378 static final int SCAN_NO_DEX = 1<<1; 379 static final int SCAN_FORCE_DEX = 1<<2; 380 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 381 static final int SCAN_NEW_INSTALL = 1<<4; 382 static final int SCAN_NO_PATHS = 1<<5; 383 static final int SCAN_UPDATE_TIME = 1<<6; 384 static final int SCAN_DEFER_DEX = 1<<7; 385 static final int SCAN_BOOTING = 1<<8; 386 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 387 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 388 static final int SCAN_REPLACING = 1<<11; 389 static final int SCAN_REQUIRE_KNOWN = 1<<12; 390 static final int SCAN_MOVE = 1<<13; 391 static final int SCAN_INITIAL = 1<<14; 392 static final int SCAN_CHECK_ONLY = 1<<15; 393 static final int SCAN_DONT_KILL_APP = 1<<17; 394 static final int SCAN_IGNORE_FROZEN = 1<<18; 395 396 static final int REMOVE_CHATTY = 1<<16; 397 398 private static final int[] EMPTY_INT_ARRAY = new int[0]; 399 400 /** 401 * Timeout (in milliseconds) after which the watchdog should declare that 402 * our handler thread is wedged. The usual default for such things is one 403 * minute but we sometimes do very lengthy I/O operations on this thread, 404 * such as installing multi-gigabyte applications, so ours needs to be longer. 405 */ 406 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 407 408 /** 409 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 410 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 411 * settings entry if available, otherwise we use the hardcoded default. If it's been 412 * more than this long since the last fstrim, we force one during the boot sequence. 413 * 414 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 415 * one gets run at the next available charging+idle time. This final mandatory 416 * no-fstrim check kicks in only of the other scheduling criteria is never met. 417 */ 418 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 419 420 /** 421 * Whether verification is enabled by default. 422 */ 423 private static final boolean DEFAULT_VERIFY_ENABLE = true; 424 425 /** 426 * The default maximum time to wait for the verification agent to return in 427 * milliseconds. 428 */ 429 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 430 431 /** 432 * The default response for package verification timeout. 433 * 434 * This can be either PackageManager.VERIFICATION_ALLOW or 435 * PackageManager.VERIFICATION_REJECT. 436 */ 437 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 438 439 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 440 441 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 442 DEFAULT_CONTAINER_PACKAGE, 443 "com.android.defcontainer.DefaultContainerService"); 444 445 private static final String KILL_APP_REASON_GIDS_CHANGED = 446 "permission grant or revoke changed gids"; 447 448 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 449 "permissions revoked"; 450 451 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 452 453 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 454 455 /** Permission grant: not grant the permission. */ 456 private static final int GRANT_DENIED = 1; 457 458 /** Permission grant: grant the permission as an install permission. */ 459 private static final int GRANT_INSTALL = 2; 460 461 /** Permission grant: grant the permission as a runtime one. */ 462 private static final int GRANT_RUNTIME = 3; 463 464 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 465 private static final int GRANT_UPGRADE = 4; 466 467 /** Canonical intent used to identify what counts as a "web browser" app */ 468 private static final Intent sBrowserIntent; 469 static { 470 sBrowserIntent = new Intent(); 471 sBrowserIntent.setAction(Intent.ACTION_VIEW); 472 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 473 sBrowserIntent.setData(Uri.parse("http:")); 474 } 475 476 /** 477 * The set of all protected actions [i.e. those actions for which a high priority 478 * intent filter is disallowed]. 479 */ 480 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 481 static { 482 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 483 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 484 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 485 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 486 } 487 488 // Compilation reasons. 489 public static final int REASON_FIRST_BOOT = 0; 490 public static final int REASON_BOOT = 1; 491 public static final int REASON_INSTALL = 2; 492 public static final int REASON_BACKGROUND_DEXOPT = 3; 493 public static final int REASON_AB_OTA = 4; 494 public static final int REASON_NON_SYSTEM_LIBRARY = 5; 495 public static final int REASON_SHARED_APK = 6; 496 public static final int REASON_FORCED_DEXOPT = 7; 497 498 public static final int REASON_LAST = REASON_FORCED_DEXOPT; 499 500 final ServiceThread mHandlerThread; 501 502 final PackageHandler mHandler; 503 504 private final ProcessLoggingHandler mProcessLoggingHandler; 505 506 /** 507 * Messages for {@link #mHandler} that need to wait for system ready before 508 * being dispatched. 509 */ 510 private ArrayList<Message> mPostSystemReadyMessages; 511 512 final int mSdkVersion = Build.VERSION.SDK_INT; 513 514 final Context mContext; 515 final boolean mFactoryTest; 516 final boolean mOnlyCore; 517 final DisplayMetrics mMetrics; 518 final int mDefParseFlags; 519 final String[] mSeparateProcesses; 520 final boolean mIsUpgrade; 521 final boolean mIsPreNUpgrade; 522 523 /** The location for ASEC container files on internal storage. */ 524 final String mAsecInternalPath; 525 526 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 527 // LOCK HELD. Can be called with mInstallLock held. 528 @GuardedBy("mInstallLock") 529 final Installer mInstaller; 530 531 /** Directory where installed third-party apps stored */ 532 final File mAppInstallDir; 533 final File mEphemeralInstallDir; 534 535 /** 536 * Directory to which applications installed internally have their 537 * 32 bit native libraries copied. 538 */ 539 private File mAppLib32InstallDir; 540 541 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 542 // apps. 543 final File mDrmAppPrivateInstallDir; 544 545 // ---------------------------------------------------------------- 546 547 // Lock for state used when installing and doing other long running 548 // operations. Methods that must be called with this lock held have 549 // the suffix "LI". 550 final Object mInstallLock = new Object(); 551 552 // ---------------------------------------------------------------- 553 554 // Keys are String (package name), values are Package. This also serves 555 // as the lock for the global state. Methods that must be called with 556 // this lock held have the prefix "LP". 557 @GuardedBy("mPackages") 558 final ArrayMap<String, PackageParser.Package> mPackages = 559 new ArrayMap<String, PackageParser.Package>(); 560 561 final ArrayMap<String, Set<String>> mKnownCodebase = 562 new ArrayMap<String, Set<String>>(); 563 564 // Tracks available target package names -> overlay package paths. 565 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 566 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 567 568 /** 569 * Tracks new system packages [received in an OTA] that we expect to 570 * find updated user-installed versions. Keys are package name, values 571 * are package location. 572 */ 573 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 574 /** 575 * Tracks high priority intent filters for protected actions. During boot, certain 576 * filter actions are protected and should never be allowed to have a high priority 577 * intent filter for them. However, there is one, and only one exception -- the 578 * setup wizard. It must be able to define a high priority intent filter for these 579 * actions to ensure there are no escapes from the wizard. We need to delay processing 580 * of these during boot as we need to look at all of the system packages in order 581 * to know which component is the setup wizard. 582 */ 583 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 584 /** 585 * Whether or not processing protected filters should be deferred. 586 */ 587 private boolean mDeferProtectedFilters = true; 588 589 /** 590 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 591 */ 592 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 593 /** 594 * Whether or not system app permissions should be promoted from install to runtime. 595 */ 596 boolean mPromoteSystemApps; 597 598 @GuardedBy("mPackages") 599 final Settings mSettings; 600 601 /** 602 * Set of package names that are currently "frozen", which means active 603 * surgery is being done on the code/data for that package. The platform 604 * will refuse to launch frozen packages to avoid race conditions. 605 * 606 * @see PackageFreezer 607 */ 608 @GuardedBy("mPackages") 609 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 610 611 boolean mRestoredSettings; 612 613 // System configuration read by SystemConfig. 614 final int[] mGlobalGids; 615 final SparseArray<ArraySet<String>> mSystemPermissions; 616 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 617 618 // If mac_permissions.xml was found for seinfo labeling. 619 boolean mFoundPolicyFile; 620 621 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 622 623 public static final class SharedLibraryEntry { 624 public final String path; 625 public final String apk; 626 627 SharedLibraryEntry(String _path, String _apk) { 628 path = _path; 629 apk = _apk; 630 } 631 } 632 633 // Currently known shared libraries. 634 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 635 new ArrayMap<String, SharedLibraryEntry>(); 636 637 // All available activities, for your resolving pleasure. 638 final ActivityIntentResolver mActivities = 639 new ActivityIntentResolver(); 640 641 // All available receivers, for your resolving pleasure. 642 final ActivityIntentResolver mReceivers = 643 new ActivityIntentResolver(); 644 645 // All available services, for your resolving pleasure. 646 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 647 648 // All available providers, for your resolving pleasure. 649 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 650 651 // Mapping from provider base names (first directory in content URI codePath) 652 // to the provider information. 653 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 654 new ArrayMap<String, PackageParser.Provider>(); 655 656 // Mapping from instrumentation class names to info about them. 657 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 658 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 659 660 // Mapping from permission names to info about them. 661 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 662 new ArrayMap<String, PackageParser.PermissionGroup>(); 663 664 // Packages whose data we have transfered into another package, thus 665 // should no longer exist. 666 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 667 668 // Broadcast actions that are only available to the system. 669 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 670 671 /** List of packages waiting for verification. */ 672 final SparseArray<PackageVerificationState> mPendingVerification 673 = new SparseArray<PackageVerificationState>(); 674 675 /** Set of packages associated with each app op permission. */ 676 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 677 678 final PackageInstallerService mInstallerService; 679 680 private final PackageDexOptimizer mPackageDexOptimizer; 681 682 private AtomicInteger mNextMoveId = new AtomicInteger(); 683 private final MoveCallbacks mMoveCallbacks; 684 685 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 686 687 // Cache of users who need badging. 688 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 689 690 /** Token for keys in mPendingVerification. */ 691 private int mPendingVerificationToken = 0; 692 693 volatile boolean mSystemReady; 694 volatile boolean mSafeMode; 695 volatile boolean mHasSystemUidErrors; 696 697 ApplicationInfo mAndroidApplication; 698 final ActivityInfo mResolveActivity = new ActivityInfo(); 699 final ResolveInfo mResolveInfo = new ResolveInfo(); 700 ComponentName mResolveComponentName; 701 PackageParser.Package mPlatformPackage; 702 ComponentName mCustomResolverComponentName; 703 704 boolean mResolverReplaced = false; 705 706 private final @Nullable ComponentName mIntentFilterVerifierComponent; 707 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 708 709 private int mIntentFilterVerificationToken = 0; 710 711 /** Component that knows whether or not an ephemeral application exists */ 712 final ComponentName mEphemeralResolverComponent; 713 /** The service connection to the ephemeral resolver */ 714 final EphemeralResolverConnection mEphemeralResolverConnection; 715 716 /** Component used to install ephemeral applications */ 717 final ComponentName mEphemeralInstallerComponent; 718 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 719 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 720 721 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 722 = new SparseArray<IntentFilterVerificationState>(); 723 724 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 725 new DefaultPermissionGrantPolicy(this); 726 727 // List of packages names to keep cached, even if they are uninstalled for all users 728 private List<String> mKeepUninstalledPackages; 729 730 private static class IFVerificationParams { 731 PackageParser.Package pkg; 732 boolean replacing; 733 int userId; 734 int verifierUid; 735 736 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 737 int _userId, int _verifierUid) { 738 pkg = _pkg; 739 replacing = _replacing; 740 userId = _userId; 741 replacing = _replacing; 742 verifierUid = _verifierUid; 743 } 744 } 745 746 private interface IntentFilterVerifier<T extends IntentFilter> { 747 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 748 T filter, String packageName); 749 void startVerifications(int userId); 750 void receiveVerificationResponse(int verificationId); 751 } 752 753 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 754 private Context mContext; 755 private ComponentName mIntentFilterVerifierComponent; 756 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 757 758 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 759 mContext = context; 760 mIntentFilterVerifierComponent = verifierComponent; 761 } 762 763 private String getDefaultScheme() { 764 return IntentFilter.SCHEME_HTTPS; 765 } 766 767 @Override 768 public void startVerifications(int userId) { 769 // Launch verifications requests 770 int count = mCurrentIntentFilterVerifications.size(); 771 for (int n=0; n<count; n++) { 772 int verificationId = mCurrentIntentFilterVerifications.get(n); 773 final IntentFilterVerificationState ivs = 774 mIntentFilterVerificationStates.get(verificationId); 775 776 String packageName = ivs.getPackageName(); 777 778 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 779 final int filterCount = filters.size(); 780 ArraySet<String> domainsSet = new ArraySet<>(); 781 for (int m=0; m<filterCount; m++) { 782 PackageParser.ActivityIntentInfo filter = filters.get(m); 783 domainsSet.addAll(filter.getHostsList()); 784 } 785 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 786 synchronized (mPackages) { 787 if (mSettings.createIntentFilterVerificationIfNeededLPw( 788 packageName, domainsList) != null) { 789 scheduleWriteSettingsLocked(); 790 } 791 } 792 sendVerificationRequest(userId, verificationId, ivs); 793 } 794 mCurrentIntentFilterVerifications.clear(); 795 } 796 797 private void sendVerificationRequest(int userId, int verificationId, 798 IntentFilterVerificationState ivs) { 799 800 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 801 verificationIntent.putExtra( 802 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 803 verificationId); 804 verificationIntent.putExtra( 805 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 806 getDefaultScheme()); 807 verificationIntent.putExtra( 808 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 809 ivs.getHostsString()); 810 verificationIntent.putExtra( 811 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 812 ivs.getPackageName()); 813 verificationIntent.setComponent(mIntentFilterVerifierComponent); 814 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 815 816 UserHandle user = new UserHandle(userId); 817 mContext.sendBroadcastAsUser(verificationIntent, user); 818 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 819 "Sending IntentFilter verification broadcast"); 820 } 821 822 public void receiveVerificationResponse(int verificationId) { 823 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 824 825 final boolean verified = ivs.isVerified(); 826 827 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 828 final int count = filters.size(); 829 if (DEBUG_DOMAIN_VERIFICATION) { 830 Slog.i(TAG, "Received verification response " + verificationId 831 + " for " + count + " filters, verified=" + verified); 832 } 833 for (int n=0; n<count; n++) { 834 PackageParser.ActivityIntentInfo filter = filters.get(n); 835 filter.setVerified(verified); 836 837 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 838 + " verified with result:" + verified + " and hosts:" 839 + ivs.getHostsString()); 840 } 841 842 mIntentFilterVerificationStates.remove(verificationId); 843 844 final String packageName = ivs.getPackageName(); 845 IntentFilterVerificationInfo ivi = null; 846 847 synchronized (mPackages) { 848 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 849 } 850 if (ivi == null) { 851 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 852 + verificationId + " packageName:" + packageName); 853 return; 854 } 855 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 856 "Updating IntentFilterVerificationInfo for package " + packageName 857 +" verificationId:" + verificationId); 858 859 synchronized (mPackages) { 860 if (verified) { 861 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 862 } else { 863 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 864 } 865 scheduleWriteSettingsLocked(); 866 867 final int userId = ivs.getUserId(); 868 if (userId != UserHandle.USER_ALL) { 869 final int userStatus = 870 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 871 872 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 873 boolean needUpdate = false; 874 875 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 876 // already been set by the User thru the Disambiguation dialog 877 switch (userStatus) { 878 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 879 if (verified) { 880 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 881 } else { 882 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 883 } 884 needUpdate = true; 885 break; 886 887 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 888 if (verified) { 889 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 890 needUpdate = true; 891 } 892 break; 893 894 default: 895 // Nothing to do 896 } 897 898 if (needUpdate) { 899 mSettings.updateIntentFilterVerificationStatusLPw( 900 packageName, updatedStatus, userId); 901 scheduleWritePackageRestrictionsLocked(userId); 902 } 903 } 904 } 905 } 906 907 @Override 908 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 909 ActivityIntentInfo filter, String packageName) { 910 if (!hasValidDomains(filter)) { 911 return false; 912 } 913 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 914 if (ivs == null) { 915 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 916 packageName); 917 } 918 if (DEBUG_DOMAIN_VERIFICATION) { 919 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 920 } 921 ivs.addFilter(filter); 922 return true; 923 } 924 925 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 926 int userId, int verificationId, String packageName) { 927 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 928 verifierUid, userId, packageName); 929 ivs.setPendingState(); 930 synchronized (mPackages) { 931 mIntentFilterVerificationStates.append(verificationId, ivs); 932 mCurrentIntentFilterVerifications.add(verificationId); 933 } 934 return ivs; 935 } 936 } 937 938 private static boolean hasValidDomains(ActivityIntentInfo filter) { 939 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 940 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 941 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 942 } 943 944 // Set of pending broadcasts for aggregating enable/disable of components. 945 static class PendingPackageBroadcasts { 946 // for each user id, a map of <package name -> components within that package> 947 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 948 949 public PendingPackageBroadcasts() { 950 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 951 } 952 953 public ArrayList<String> get(int userId, String packageName) { 954 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 955 return packages.get(packageName); 956 } 957 958 public void put(int userId, String packageName, ArrayList<String> components) { 959 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 960 packages.put(packageName, components); 961 } 962 963 public void remove(int userId, String packageName) { 964 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 965 if (packages != null) { 966 packages.remove(packageName); 967 } 968 } 969 970 public void remove(int userId) { 971 mUidMap.remove(userId); 972 } 973 974 public int userIdCount() { 975 return mUidMap.size(); 976 } 977 978 public int userIdAt(int n) { 979 return mUidMap.keyAt(n); 980 } 981 982 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 983 return mUidMap.get(userId); 984 } 985 986 public int size() { 987 // total number of pending broadcast entries across all userIds 988 int num = 0; 989 for (int i = 0; i< mUidMap.size(); i++) { 990 num += mUidMap.valueAt(i).size(); 991 } 992 return num; 993 } 994 995 public void clear() { 996 mUidMap.clear(); 997 } 998 999 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1000 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1001 if (map == null) { 1002 map = new ArrayMap<String, ArrayList<String>>(); 1003 mUidMap.put(userId, map); 1004 } 1005 return map; 1006 } 1007 } 1008 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1009 1010 // Service Connection to remote media container service to copy 1011 // package uri's from external media onto secure containers 1012 // or internal storage. 1013 private IMediaContainerService mContainerService = null; 1014 1015 static final int SEND_PENDING_BROADCAST = 1; 1016 static final int MCS_BOUND = 3; 1017 static final int END_COPY = 4; 1018 static final int INIT_COPY = 5; 1019 static final int MCS_UNBIND = 6; 1020 static final int START_CLEANING_PACKAGE = 7; 1021 static final int FIND_INSTALL_LOC = 8; 1022 static final int POST_INSTALL = 9; 1023 static final int MCS_RECONNECT = 10; 1024 static final int MCS_GIVE_UP = 11; 1025 static final int UPDATED_MEDIA_STATUS = 12; 1026 static final int WRITE_SETTINGS = 13; 1027 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1028 static final int PACKAGE_VERIFIED = 15; 1029 static final int CHECK_PENDING_VERIFICATION = 16; 1030 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1031 static final int INTENT_FILTER_VERIFIED = 18; 1032 1033 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1034 1035 // Delay time in millisecs 1036 static final int BROADCAST_DELAY = 10 * 1000; 1037 1038 static UserManagerService sUserManager; 1039 1040 // Stores a list of users whose package restrictions file needs to be updated 1041 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1042 1043 final private DefaultContainerConnection mDefContainerConn = 1044 new DefaultContainerConnection(); 1045 class DefaultContainerConnection implements ServiceConnection { 1046 public void onServiceConnected(ComponentName name, IBinder service) { 1047 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1048 IMediaContainerService imcs = 1049 IMediaContainerService.Stub.asInterface(service); 1050 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1051 } 1052 1053 public void onServiceDisconnected(ComponentName name) { 1054 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1055 } 1056 } 1057 1058 // Recordkeeping of restore-after-install operations that are currently in flight 1059 // between the Package Manager and the Backup Manager 1060 static class PostInstallData { 1061 public InstallArgs args; 1062 public PackageInstalledInfo res; 1063 1064 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1065 args = _a; 1066 res = _r; 1067 } 1068 } 1069 1070 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1071 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1072 1073 // XML tags for backup/restore of various bits of state 1074 private static final String TAG_PREFERRED_BACKUP = "pa"; 1075 private static final String TAG_DEFAULT_APPS = "da"; 1076 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1077 1078 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1079 private static final String TAG_ALL_GRANTS = "rt-grants"; 1080 private static final String TAG_GRANT = "grant"; 1081 private static final String ATTR_PACKAGE_NAME = "pkg"; 1082 1083 private static final String TAG_PERMISSION = "perm"; 1084 private static final String ATTR_PERMISSION_NAME = "name"; 1085 private static final String ATTR_IS_GRANTED = "g"; 1086 private static final String ATTR_USER_SET = "set"; 1087 private static final String ATTR_USER_FIXED = "fixed"; 1088 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1089 1090 // System/policy permission grants are not backed up 1091 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1092 FLAG_PERMISSION_POLICY_FIXED 1093 | FLAG_PERMISSION_SYSTEM_FIXED 1094 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1095 1096 // And we back up these user-adjusted states 1097 private static final int USER_RUNTIME_GRANT_MASK = 1098 FLAG_PERMISSION_USER_SET 1099 | FLAG_PERMISSION_USER_FIXED 1100 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1101 1102 final @Nullable String mRequiredVerifierPackage; 1103 final @NonNull String mRequiredInstallerPackage; 1104 final @Nullable String mSetupWizardPackage; 1105 final @NonNull String mServicesSystemSharedLibraryPackageName; 1106 1107 private final PackageUsage mPackageUsage = new PackageUsage(); 1108 1109 private class PackageUsage { 1110 private static final int WRITE_INTERVAL 1111 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 1112 1113 private final Object mFileLock = new Object(); 1114 private final AtomicLong mLastWritten = new AtomicLong(0); 1115 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 1116 1117 private boolean mIsHistoricalPackageUsageAvailable = true; 1118 1119 boolean isHistoricalPackageUsageAvailable() { 1120 return mIsHistoricalPackageUsageAvailable; 1121 } 1122 1123 void write(boolean force) { 1124 if (force) { 1125 writeInternal(); 1126 return; 1127 } 1128 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 1129 && !DEBUG_DEXOPT) { 1130 return; 1131 } 1132 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 1133 new Thread("PackageUsage_DiskWriter") { 1134 @Override 1135 public void run() { 1136 try { 1137 writeInternal(); 1138 } finally { 1139 mBackgroundWriteRunning.set(false); 1140 } 1141 } 1142 }.start(); 1143 } 1144 } 1145 1146 private void writeInternal() { 1147 synchronized (mPackages) { 1148 synchronized (mFileLock) { 1149 AtomicFile file = getFile(); 1150 FileOutputStream f = null; 1151 try { 1152 f = file.startWrite(); 1153 BufferedOutputStream out = new BufferedOutputStream(f); 1154 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1155 StringBuilder sb = new StringBuilder(); 1156 for (PackageParser.Package pkg : mPackages.values()) { 1157 if (pkg.mLastPackageUsageTimeInMills == 0) { 1158 continue; 1159 } 1160 sb.setLength(0); 1161 sb.append(pkg.packageName); 1162 sb.append(' '); 1163 sb.append((long)pkg.mLastPackageUsageTimeInMills); 1164 sb.append('\n'); 1165 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1166 } 1167 out.flush(); 1168 file.finishWrite(f); 1169 } catch (IOException e) { 1170 if (f != null) { 1171 file.failWrite(f); 1172 } 1173 Log.e(TAG, "Failed to write package usage times", e); 1174 } 1175 } 1176 } 1177 mLastWritten.set(SystemClock.elapsedRealtime()); 1178 } 1179 1180 void readLP() { 1181 synchronized (mFileLock) { 1182 AtomicFile file = getFile(); 1183 BufferedInputStream in = null; 1184 try { 1185 in = new BufferedInputStream(file.openRead()); 1186 StringBuffer sb = new StringBuffer(); 1187 while (true) { 1188 String packageName = readToken(in, sb, ' '); 1189 if (packageName == null) { 1190 break; 1191 } 1192 String timeInMillisString = readToken(in, sb, '\n'); 1193 if (timeInMillisString == null) { 1194 throw new IOException("Failed to find last usage time for package " 1195 + packageName); 1196 } 1197 PackageParser.Package pkg = mPackages.get(packageName); 1198 if (pkg == null) { 1199 continue; 1200 } 1201 long timeInMillis; 1202 try { 1203 timeInMillis = Long.parseLong(timeInMillisString); 1204 } catch (NumberFormatException e) { 1205 throw new IOException("Failed to parse " + timeInMillisString 1206 + " as a long.", e); 1207 } 1208 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1209 } 1210 } catch (FileNotFoundException expected) { 1211 mIsHistoricalPackageUsageAvailable = false; 1212 } catch (IOException e) { 1213 Log.w(TAG, "Failed to read package usage times", e); 1214 } finally { 1215 IoUtils.closeQuietly(in); 1216 } 1217 } 1218 mLastWritten.set(SystemClock.elapsedRealtime()); 1219 } 1220 1221 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1222 throws IOException { 1223 sb.setLength(0); 1224 while (true) { 1225 int ch = in.read(); 1226 if (ch == -1) { 1227 if (sb.length() == 0) { 1228 return null; 1229 } 1230 throw new IOException("Unexpected EOF"); 1231 } 1232 if (ch == endOfToken) { 1233 return sb.toString(); 1234 } 1235 sb.append((char)ch); 1236 } 1237 } 1238 1239 private AtomicFile getFile() { 1240 File dataDir = Environment.getDataDirectory(); 1241 File systemDir = new File(dataDir, "system"); 1242 File fname = new File(systemDir, "package-usage.list"); 1243 return new AtomicFile(fname); 1244 } 1245 } 1246 1247 class PackageHandler extends Handler { 1248 private boolean mBound = false; 1249 final ArrayList<HandlerParams> mPendingInstalls = 1250 new ArrayList<HandlerParams>(); 1251 1252 private boolean connectToService() { 1253 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1254 " DefaultContainerService"); 1255 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1256 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1257 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1258 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1259 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1260 mBound = true; 1261 return true; 1262 } 1263 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1264 return false; 1265 } 1266 1267 private void disconnectService() { 1268 mContainerService = null; 1269 mBound = false; 1270 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1271 mContext.unbindService(mDefContainerConn); 1272 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1273 } 1274 1275 PackageHandler(Looper looper) { 1276 super(looper); 1277 } 1278 1279 public void handleMessage(Message msg) { 1280 try { 1281 doHandleMessage(msg); 1282 } finally { 1283 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1284 } 1285 } 1286 1287 void doHandleMessage(Message msg) { 1288 switch (msg.what) { 1289 case INIT_COPY: { 1290 HandlerParams params = (HandlerParams) msg.obj; 1291 int idx = mPendingInstalls.size(); 1292 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1293 // If a bind was already initiated we dont really 1294 // need to do anything. The pending install 1295 // will be processed later on. 1296 if (!mBound) { 1297 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1298 System.identityHashCode(mHandler)); 1299 // If this is the only one pending we might 1300 // have to bind to the service again. 1301 if (!connectToService()) { 1302 Slog.e(TAG, "Failed to bind to media container service"); 1303 params.serviceError(); 1304 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1305 System.identityHashCode(mHandler)); 1306 if (params.traceMethod != null) { 1307 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1308 params.traceCookie); 1309 } 1310 return; 1311 } else { 1312 // Once we bind to the service, the first 1313 // pending request will be processed. 1314 mPendingInstalls.add(idx, params); 1315 } 1316 } else { 1317 mPendingInstalls.add(idx, params); 1318 // Already bound to the service. Just make 1319 // sure we trigger off processing the first request. 1320 if (idx == 0) { 1321 mHandler.sendEmptyMessage(MCS_BOUND); 1322 } 1323 } 1324 break; 1325 } 1326 case MCS_BOUND: { 1327 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1328 if (msg.obj != null) { 1329 mContainerService = (IMediaContainerService) msg.obj; 1330 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1331 System.identityHashCode(mHandler)); 1332 } 1333 if (mContainerService == null) { 1334 if (!mBound) { 1335 // Something seriously wrong since we are not bound and we are not 1336 // waiting for connection. Bail out. 1337 Slog.e(TAG, "Cannot bind to media container service"); 1338 for (HandlerParams params : mPendingInstalls) { 1339 // Indicate service bind error 1340 params.serviceError(); 1341 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1342 System.identityHashCode(params)); 1343 if (params.traceMethod != null) { 1344 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1345 params.traceMethod, params.traceCookie); 1346 } 1347 return; 1348 } 1349 mPendingInstalls.clear(); 1350 } else { 1351 Slog.w(TAG, "Waiting to connect to media container service"); 1352 } 1353 } else if (mPendingInstalls.size() > 0) { 1354 HandlerParams params = mPendingInstalls.get(0); 1355 if (params != null) { 1356 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1357 System.identityHashCode(params)); 1358 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1359 if (params.startCopy()) { 1360 // We are done... look for more work or to 1361 // go idle. 1362 if (DEBUG_SD_INSTALL) Log.i(TAG, 1363 "Checking for more work or unbind..."); 1364 // Delete pending install 1365 if (mPendingInstalls.size() > 0) { 1366 mPendingInstalls.remove(0); 1367 } 1368 if (mPendingInstalls.size() == 0) { 1369 if (mBound) { 1370 if (DEBUG_SD_INSTALL) Log.i(TAG, 1371 "Posting delayed MCS_UNBIND"); 1372 removeMessages(MCS_UNBIND); 1373 Message ubmsg = obtainMessage(MCS_UNBIND); 1374 // Unbind after a little delay, to avoid 1375 // continual thrashing. 1376 sendMessageDelayed(ubmsg, 10000); 1377 } 1378 } else { 1379 // There are more pending requests in queue. 1380 // Just post MCS_BOUND message to trigger processing 1381 // of next pending install. 1382 if (DEBUG_SD_INSTALL) Log.i(TAG, 1383 "Posting MCS_BOUND for next work"); 1384 mHandler.sendEmptyMessage(MCS_BOUND); 1385 } 1386 } 1387 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1388 } 1389 } else { 1390 // Should never happen ideally. 1391 Slog.w(TAG, "Empty queue"); 1392 } 1393 break; 1394 } 1395 case MCS_RECONNECT: { 1396 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1397 if (mPendingInstalls.size() > 0) { 1398 if (mBound) { 1399 disconnectService(); 1400 } 1401 if (!connectToService()) { 1402 Slog.e(TAG, "Failed to bind to media container service"); 1403 for (HandlerParams params : mPendingInstalls) { 1404 // Indicate service bind error 1405 params.serviceError(); 1406 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1407 System.identityHashCode(params)); 1408 } 1409 mPendingInstalls.clear(); 1410 } 1411 } 1412 break; 1413 } 1414 case MCS_UNBIND: { 1415 // If there is no actual work left, then time to unbind. 1416 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1417 1418 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1419 if (mBound) { 1420 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1421 1422 disconnectService(); 1423 } 1424 } else if (mPendingInstalls.size() > 0) { 1425 // There are more pending requests in queue. 1426 // Just post MCS_BOUND message to trigger processing 1427 // of next pending install. 1428 mHandler.sendEmptyMessage(MCS_BOUND); 1429 } 1430 1431 break; 1432 } 1433 case MCS_GIVE_UP: { 1434 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1435 HandlerParams params = mPendingInstalls.remove(0); 1436 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1437 System.identityHashCode(params)); 1438 break; 1439 } 1440 case SEND_PENDING_BROADCAST: { 1441 String packages[]; 1442 ArrayList<String> components[]; 1443 int size = 0; 1444 int uids[]; 1445 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1446 synchronized (mPackages) { 1447 if (mPendingBroadcasts == null) { 1448 return; 1449 } 1450 size = mPendingBroadcasts.size(); 1451 if (size <= 0) { 1452 // Nothing to be done. Just return 1453 return; 1454 } 1455 packages = new String[size]; 1456 components = new ArrayList[size]; 1457 uids = new int[size]; 1458 int i = 0; // filling out the above arrays 1459 1460 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1461 int packageUserId = mPendingBroadcasts.userIdAt(n); 1462 Iterator<Map.Entry<String, ArrayList<String>>> it 1463 = mPendingBroadcasts.packagesForUserId(packageUserId) 1464 .entrySet().iterator(); 1465 while (it.hasNext() && i < size) { 1466 Map.Entry<String, ArrayList<String>> ent = it.next(); 1467 packages[i] = ent.getKey(); 1468 components[i] = ent.getValue(); 1469 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1470 uids[i] = (ps != null) 1471 ? UserHandle.getUid(packageUserId, ps.appId) 1472 : -1; 1473 i++; 1474 } 1475 } 1476 size = i; 1477 mPendingBroadcasts.clear(); 1478 } 1479 // Send broadcasts 1480 for (int i = 0; i < size; i++) { 1481 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1482 } 1483 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1484 break; 1485 } 1486 case START_CLEANING_PACKAGE: { 1487 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1488 final String packageName = (String)msg.obj; 1489 final int userId = msg.arg1; 1490 final boolean andCode = msg.arg2 != 0; 1491 synchronized (mPackages) { 1492 if (userId == UserHandle.USER_ALL) { 1493 int[] users = sUserManager.getUserIds(); 1494 for (int user : users) { 1495 mSettings.addPackageToCleanLPw( 1496 new PackageCleanItem(user, packageName, andCode)); 1497 } 1498 } else { 1499 mSettings.addPackageToCleanLPw( 1500 new PackageCleanItem(userId, packageName, andCode)); 1501 } 1502 } 1503 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1504 startCleaningPackages(); 1505 } break; 1506 case POST_INSTALL: { 1507 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1508 1509 PostInstallData data = mRunningInstalls.get(msg.arg1); 1510 mRunningInstalls.delete(msg.arg1); 1511 1512 if (data != null) { 1513 InstallArgs args = data.args; 1514 PackageInstalledInfo parentRes = data.res; 1515 1516 final boolean grantPermissions = (args.installFlags 1517 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1518 final boolean killApp = (args.installFlags 1519 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1520 final String[] grantedPermissions = args.installGrantPermissions; 1521 1522 // Handle the parent package 1523 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1524 grantedPermissions, args.observer); 1525 1526 // Handle the child packages 1527 final int childCount = (parentRes.addedChildPackages != null) 1528 ? parentRes.addedChildPackages.size() : 0; 1529 for (int i = 0; i < childCount; i++) { 1530 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1531 handlePackagePostInstall(childRes, grantPermissions, killApp, 1532 grantedPermissions, args.observer); 1533 } 1534 1535 // Log tracing if needed 1536 if (args.traceMethod != null) { 1537 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1538 args.traceCookie); 1539 } 1540 } else { 1541 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1542 } 1543 1544 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1545 } break; 1546 case UPDATED_MEDIA_STATUS: { 1547 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1548 boolean reportStatus = msg.arg1 == 1; 1549 boolean doGc = msg.arg2 == 1; 1550 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1551 if (doGc) { 1552 // Force a gc to clear up stale containers. 1553 Runtime.getRuntime().gc(); 1554 } 1555 if (msg.obj != null) { 1556 @SuppressWarnings("unchecked") 1557 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1558 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1559 // Unload containers 1560 unloadAllContainers(args); 1561 } 1562 if (reportStatus) { 1563 try { 1564 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1565 PackageHelper.getMountService().finishMediaUpdate(); 1566 } catch (RemoteException e) { 1567 Log.e(TAG, "MountService not running?"); 1568 } 1569 } 1570 } break; 1571 case WRITE_SETTINGS: { 1572 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1573 synchronized (mPackages) { 1574 removeMessages(WRITE_SETTINGS); 1575 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1576 mSettings.writeLPr(); 1577 mDirtyUsers.clear(); 1578 } 1579 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1580 } break; 1581 case WRITE_PACKAGE_RESTRICTIONS: { 1582 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1583 synchronized (mPackages) { 1584 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1585 for (int userId : mDirtyUsers) { 1586 mSettings.writePackageRestrictionsLPr(userId); 1587 } 1588 mDirtyUsers.clear(); 1589 } 1590 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1591 } break; 1592 case CHECK_PENDING_VERIFICATION: { 1593 final int verificationId = msg.arg1; 1594 final PackageVerificationState state = mPendingVerification.get(verificationId); 1595 1596 if ((state != null) && !state.timeoutExtended()) { 1597 final InstallArgs args = state.getInstallArgs(); 1598 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1599 1600 Slog.i(TAG, "Verification timed out for " + originUri); 1601 mPendingVerification.remove(verificationId); 1602 1603 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1604 1605 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1606 Slog.i(TAG, "Continuing with installation of " + originUri); 1607 state.setVerifierResponse(Binder.getCallingUid(), 1608 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1609 broadcastPackageVerified(verificationId, originUri, 1610 PackageManager.VERIFICATION_ALLOW, 1611 state.getInstallArgs().getUser()); 1612 try { 1613 ret = args.copyApk(mContainerService, true); 1614 } catch (RemoteException e) { 1615 Slog.e(TAG, "Could not contact the ContainerService"); 1616 } 1617 } else { 1618 broadcastPackageVerified(verificationId, originUri, 1619 PackageManager.VERIFICATION_REJECT, 1620 state.getInstallArgs().getUser()); 1621 } 1622 1623 Trace.asyncTraceEnd( 1624 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1625 1626 processPendingInstall(args, ret); 1627 mHandler.sendEmptyMessage(MCS_UNBIND); 1628 } 1629 break; 1630 } 1631 case PACKAGE_VERIFIED: { 1632 final int verificationId = msg.arg1; 1633 1634 final PackageVerificationState state = mPendingVerification.get(verificationId); 1635 if (state == null) { 1636 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1637 break; 1638 } 1639 1640 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1641 1642 state.setVerifierResponse(response.callerUid, response.code); 1643 1644 if (state.isVerificationComplete()) { 1645 mPendingVerification.remove(verificationId); 1646 1647 final InstallArgs args = state.getInstallArgs(); 1648 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1649 1650 int ret; 1651 if (state.isInstallAllowed()) { 1652 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1653 broadcastPackageVerified(verificationId, originUri, 1654 response.code, state.getInstallArgs().getUser()); 1655 try { 1656 ret = args.copyApk(mContainerService, true); 1657 } catch (RemoteException e) { 1658 Slog.e(TAG, "Could not contact the ContainerService"); 1659 } 1660 } else { 1661 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1662 } 1663 1664 Trace.asyncTraceEnd( 1665 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1666 1667 processPendingInstall(args, ret); 1668 mHandler.sendEmptyMessage(MCS_UNBIND); 1669 } 1670 1671 break; 1672 } 1673 case START_INTENT_FILTER_VERIFICATIONS: { 1674 IFVerificationParams params = (IFVerificationParams) msg.obj; 1675 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1676 params.replacing, params.pkg); 1677 break; 1678 } 1679 case INTENT_FILTER_VERIFIED: { 1680 final int verificationId = msg.arg1; 1681 1682 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1683 verificationId); 1684 if (state == null) { 1685 Slog.w(TAG, "Invalid IntentFilter verification token " 1686 + verificationId + " received"); 1687 break; 1688 } 1689 1690 final int userId = state.getUserId(); 1691 1692 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1693 "Processing IntentFilter verification with token:" 1694 + verificationId + " and userId:" + userId); 1695 1696 final IntentFilterVerificationResponse response = 1697 (IntentFilterVerificationResponse) msg.obj; 1698 1699 state.setVerifierResponse(response.callerUid, response.code); 1700 1701 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1702 "IntentFilter verification with token:" + verificationId 1703 + " and userId:" + userId 1704 + " is settings verifier response with response code:" 1705 + response.code); 1706 1707 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1708 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1709 + response.getFailedDomainsString()); 1710 } 1711 1712 if (state.isVerificationComplete()) { 1713 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1714 } else { 1715 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1716 "IntentFilter verification with token:" + verificationId 1717 + " was not said to be complete"); 1718 } 1719 1720 break; 1721 } 1722 } 1723 } 1724 } 1725 1726 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1727 boolean killApp, String[] grantedPermissions, 1728 IPackageInstallObserver2 installObserver) { 1729 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1730 // Send the removed broadcasts 1731 if (res.removedInfo != null) { 1732 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1733 } 1734 1735 // Now that we successfully installed the package, grant runtime 1736 // permissions if requested before broadcasting the install. 1737 if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion 1738 >= Build.VERSION_CODES.M) { 1739 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1740 } 1741 1742 final boolean update = res.removedInfo != null 1743 && res.removedInfo.removedPackage != null; 1744 1745 // If this is the first time we have child packages for a disabled privileged 1746 // app that had no children, we grant requested runtime permissions to the new 1747 // children if the parent on the system image had them already granted. 1748 if (res.pkg.parentPackage != null) { 1749 synchronized (mPackages) { 1750 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1751 } 1752 } 1753 1754 synchronized (mPackages) { 1755 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1756 } 1757 1758 final String packageName = res.pkg.applicationInfo.packageName; 1759 Bundle extras = new Bundle(1); 1760 extras.putInt(Intent.EXTRA_UID, res.uid); 1761 1762 // Determine the set of users who are adding this package for 1763 // the first time vs. those who are seeing an update. 1764 int[] firstUsers = EMPTY_INT_ARRAY; 1765 int[] updateUsers = EMPTY_INT_ARRAY; 1766 if (res.origUsers == null || res.origUsers.length == 0) { 1767 firstUsers = res.newUsers; 1768 } else { 1769 for (int newUser : res.newUsers) { 1770 boolean isNew = true; 1771 for (int origUser : res.origUsers) { 1772 if (origUser == newUser) { 1773 isNew = false; 1774 break; 1775 } 1776 } 1777 if (isNew) { 1778 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1779 } else { 1780 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1781 } 1782 } 1783 } 1784 1785 // Send installed broadcasts if the install/update is not ephemeral 1786 if (!isEphemeral(res.pkg)) { 1787 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1788 1789 // Send added for users that see the package for the first time 1790 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1791 extras, 0 /*flags*/, null /*targetPackage*/, 1792 null /*finishedReceiver*/, firstUsers); 1793 1794 // Send added for users that don't see the package for the first time 1795 if (update) { 1796 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1797 } 1798 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1799 extras, 0 /*flags*/, null /*targetPackage*/, 1800 null /*finishedReceiver*/, updateUsers); 1801 1802 // Send replaced for users that don't see the package for the first time 1803 if (update) { 1804 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1805 packageName, extras, 0 /*flags*/, 1806 null /*targetPackage*/, null /*finishedReceiver*/, 1807 updateUsers); 1808 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1809 null /*package*/, null /*extras*/, 0 /*flags*/, 1810 packageName /*targetPackage*/, 1811 null /*finishedReceiver*/, updateUsers); 1812 } 1813 1814 // Send broadcast package appeared if forward locked/external for all users 1815 // treat asec-hosted packages like removable media on upgrade 1816 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1817 if (DEBUG_INSTALL) { 1818 Slog.i(TAG, "upgrading pkg " + res.pkg 1819 + " is ASEC-hosted -> AVAILABLE"); 1820 } 1821 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1822 ArrayList<String> pkgList = new ArrayList<>(1); 1823 pkgList.add(packageName); 1824 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1825 } 1826 } 1827 1828 // Work that needs to happen on first install within each user 1829 if (firstUsers != null && firstUsers.length > 0) { 1830 synchronized (mPackages) { 1831 for (int userId : firstUsers) { 1832 // If this app is a browser and it's newly-installed for some 1833 // users, clear any default-browser state in those users. The 1834 // app's nature doesn't depend on the user, so we can just check 1835 // its browser nature in any user and generalize. 1836 if (packageIsBrowser(packageName, userId)) { 1837 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1838 } 1839 1840 // We may also need to apply pending (restored) runtime 1841 // permission grants within these users. 1842 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1843 } 1844 } 1845 } 1846 1847 // Log current value of "unknown sources" setting 1848 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1849 getUnknownSourcesSettings()); 1850 1851 // Force a gc to clear up things 1852 Runtime.getRuntime().gc(); 1853 1854 // Remove the replaced package's older resources safely now 1855 // We delete after a gc for applications on sdcard. 1856 if (res.removedInfo != null && res.removedInfo.args != null) { 1857 synchronized (mInstallLock) { 1858 res.removedInfo.args.doPostDeleteLI(true); 1859 } 1860 } 1861 } 1862 1863 // If someone is watching installs - notify them 1864 if (installObserver != null) { 1865 try { 1866 Bundle extras = extrasForInstallResult(res); 1867 installObserver.onPackageInstalled(res.name, res.returnCode, 1868 res.returnMsg, extras); 1869 } catch (RemoteException e) { 1870 Slog.i(TAG, "Observer no longer exists."); 1871 } 1872 } 1873 } 1874 1875 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1876 PackageParser.Package pkg) { 1877 if (pkg.parentPackage == null) { 1878 return; 1879 } 1880 if (pkg.requestedPermissions == null) { 1881 return; 1882 } 1883 final PackageSetting disabledSysParentPs = mSettings 1884 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1885 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1886 || !disabledSysParentPs.isPrivileged() 1887 || (disabledSysParentPs.childPackageNames != null 1888 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1889 return; 1890 } 1891 final int[] allUserIds = sUserManager.getUserIds(); 1892 final int permCount = pkg.requestedPermissions.size(); 1893 for (int i = 0; i < permCount; i++) { 1894 String permission = pkg.requestedPermissions.get(i); 1895 BasePermission bp = mSettings.mPermissions.get(permission); 1896 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1897 continue; 1898 } 1899 for (int userId : allUserIds) { 1900 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1901 permission, userId)) { 1902 grantRuntimePermission(pkg.packageName, permission, userId); 1903 } 1904 } 1905 } 1906 } 1907 1908 private StorageEventListener mStorageListener = new StorageEventListener() { 1909 @Override 1910 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1911 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1912 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1913 final String volumeUuid = vol.getFsUuid(); 1914 1915 // Clean up any users or apps that were removed or recreated 1916 // while this volume was missing 1917 reconcileUsers(volumeUuid); 1918 reconcileApps(volumeUuid); 1919 1920 // Clean up any install sessions that expired or were 1921 // cancelled while this volume was missing 1922 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1923 1924 loadPrivatePackages(vol); 1925 1926 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1927 unloadPrivatePackages(vol); 1928 } 1929 } 1930 1931 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1932 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1933 updateExternalMediaStatus(true, false); 1934 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1935 updateExternalMediaStatus(false, false); 1936 } 1937 } 1938 } 1939 1940 @Override 1941 public void onVolumeForgotten(String fsUuid) { 1942 if (TextUtils.isEmpty(fsUuid)) { 1943 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1944 return; 1945 } 1946 1947 // Remove any apps installed on the forgotten volume 1948 synchronized (mPackages) { 1949 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1950 for (PackageSetting ps : packages) { 1951 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1952 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1953 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 1954 } 1955 1956 mSettings.onVolumeForgotten(fsUuid); 1957 mSettings.writeLPr(); 1958 } 1959 } 1960 }; 1961 1962 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 1963 String[] grantedPermissions) { 1964 for (int userId : userIds) { 1965 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1966 } 1967 1968 // We could have touched GID membership, so flush out packages.list 1969 synchronized (mPackages) { 1970 mSettings.writePackageListLPr(); 1971 } 1972 } 1973 1974 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1975 String[] grantedPermissions) { 1976 SettingBase sb = (SettingBase) pkg.mExtras; 1977 if (sb == null) { 1978 return; 1979 } 1980 1981 PermissionsState permissionsState = sb.getPermissionsState(); 1982 1983 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 1984 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 1985 1986 synchronized (mPackages) { 1987 for (String permission : pkg.requestedPermissions) { 1988 BasePermission bp = mSettings.mPermissions.get(permission); 1989 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 1990 && (grantedPermissions == null 1991 || ArrayUtils.contains(grantedPermissions, permission))) { 1992 final int flags = permissionsState.getPermissionFlags(permission, userId); 1993 // Installer cannot change immutable permissions. 1994 if ((flags & immutableFlags) == 0) { 1995 grantRuntimePermission(pkg.packageName, permission, userId); 1996 } 1997 } 1998 } 1999 } 2000 } 2001 2002 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2003 Bundle extras = null; 2004 switch (res.returnCode) { 2005 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2006 extras = new Bundle(); 2007 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2008 res.origPermission); 2009 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2010 res.origPackage); 2011 break; 2012 } 2013 case PackageManager.INSTALL_SUCCEEDED: { 2014 extras = new Bundle(); 2015 extras.putBoolean(Intent.EXTRA_REPLACING, 2016 res.removedInfo != null && res.removedInfo.removedPackage != null); 2017 break; 2018 } 2019 } 2020 return extras; 2021 } 2022 2023 void scheduleWriteSettingsLocked() { 2024 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2025 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2026 } 2027 } 2028 2029 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2030 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2031 scheduleWritePackageRestrictionsLocked(userId); 2032 } 2033 2034 void scheduleWritePackageRestrictionsLocked(int userId) { 2035 final int[] userIds = (userId == UserHandle.USER_ALL) 2036 ? sUserManager.getUserIds() : new int[]{userId}; 2037 for (int nextUserId : userIds) { 2038 if (!sUserManager.exists(nextUserId)) return; 2039 mDirtyUsers.add(nextUserId); 2040 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2041 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2042 } 2043 } 2044 } 2045 2046 public static PackageManagerService main(Context context, Installer installer, 2047 boolean factoryTest, boolean onlyCore) { 2048 // Self-check for initial settings. 2049 PackageManagerServiceCompilerMapping.checkProperties(); 2050 2051 PackageManagerService m = new PackageManagerService(context, installer, 2052 factoryTest, onlyCore); 2053 m.enableSystemUserPackages(); 2054 ServiceManager.addService("package", m); 2055 return m; 2056 } 2057 2058 private void enableSystemUserPackages() { 2059 if (!UserManager.isSplitSystemUser()) { 2060 return; 2061 } 2062 // For system user, enable apps based on the following conditions: 2063 // - app is whitelisted or belong to one of these groups: 2064 // -- system app which has no launcher icons 2065 // -- system app which has INTERACT_ACROSS_USERS permission 2066 // -- system IME app 2067 // - app is not in the blacklist 2068 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2069 Set<String> enableApps = new ArraySet<>(); 2070 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2071 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2072 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2073 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2074 enableApps.addAll(wlApps); 2075 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2076 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2077 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2078 enableApps.removeAll(blApps); 2079 Log.i(TAG, "Applications installed for system user: " + enableApps); 2080 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2081 UserHandle.SYSTEM); 2082 final int allAppsSize = allAps.size(); 2083 synchronized (mPackages) { 2084 for (int i = 0; i < allAppsSize; i++) { 2085 String pName = allAps.get(i); 2086 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2087 // Should not happen, but we shouldn't be failing if it does 2088 if (pkgSetting == null) { 2089 continue; 2090 } 2091 boolean install = enableApps.contains(pName); 2092 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2093 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2094 + " for system user"); 2095 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2096 } 2097 } 2098 } 2099 } 2100 2101 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2102 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2103 Context.DISPLAY_SERVICE); 2104 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2105 } 2106 2107 public PackageManagerService(Context context, Installer installer, 2108 boolean factoryTest, boolean onlyCore) { 2109 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2110 SystemClock.uptimeMillis()); 2111 2112 if (mSdkVersion <= 0) { 2113 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2114 } 2115 2116 mContext = context; 2117 mFactoryTest = factoryTest; 2118 mOnlyCore = onlyCore; 2119 mMetrics = new DisplayMetrics(); 2120 mSettings = new Settings(mPackages); 2121 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2122 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2123 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2124 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2125 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2126 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2127 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2128 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2129 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2130 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2131 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2132 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2133 2134 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2135 if (separateProcesses != null && separateProcesses.length() > 0) { 2136 if ("*".equals(separateProcesses)) { 2137 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2138 mSeparateProcesses = null; 2139 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2140 } else { 2141 mDefParseFlags = 0; 2142 mSeparateProcesses = separateProcesses.split(","); 2143 Slog.w(TAG, "Running with debug.separate_processes: " 2144 + separateProcesses); 2145 } 2146 } else { 2147 mDefParseFlags = 0; 2148 mSeparateProcesses = null; 2149 } 2150 2151 mInstaller = installer; 2152 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2153 "*dexopt*"); 2154 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2155 2156 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2157 FgThread.get().getLooper()); 2158 2159 getDefaultDisplayMetrics(context, mMetrics); 2160 2161 SystemConfig systemConfig = SystemConfig.getInstance(); 2162 mGlobalGids = systemConfig.getGlobalGids(); 2163 mSystemPermissions = systemConfig.getSystemPermissions(); 2164 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2165 2166 synchronized (mInstallLock) { 2167 // writer 2168 synchronized (mPackages) { 2169 mHandlerThread = new ServiceThread(TAG, 2170 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2171 mHandlerThread.start(); 2172 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2173 mProcessLoggingHandler = new ProcessLoggingHandler(); 2174 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2175 2176 File dataDir = Environment.getDataDirectory(); 2177 mAppInstallDir = new File(dataDir, "app"); 2178 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2179 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2180 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2181 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2182 2183 sUserManager = new UserManagerService(context, this, mPackages); 2184 2185 // Propagate permission configuration in to package manager. 2186 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2187 = systemConfig.getPermissions(); 2188 for (int i=0; i<permConfig.size(); i++) { 2189 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2190 BasePermission bp = mSettings.mPermissions.get(perm.name); 2191 if (bp == null) { 2192 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2193 mSettings.mPermissions.put(perm.name, bp); 2194 } 2195 if (perm.gids != null) { 2196 bp.setGids(perm.gids, perm.perUser); 2197 } 2198 } 2199 2200 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2201 for (int i=0; i<libConfig.size(); i++) { 2202 mSharedLibraries.put(libConfig.keyAt(i), 2203 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2204 } 2205 2206 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2207 2208 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 2209 2210 String customResolverActivity = Resources.getSystem().getString( 2211 R.string.config_customResolverActivity); 2212 if (TextUtils.isEmpty(customResolverActivity)) { 2213 customResolverActivity = null; 2214 } else { 2215 mCustomResolverComponentName = ComponentName.unflattenFromString( 2216 customResolverActivity); 2217 } 2218 2219 long startTime = SystemClock.uptimeMillis(); 2220 2221 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2222 startTime); 2223 2224 // Set flag to monitor and not change apk file paths when 2225 // scanning install directories. 2226 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2227 2228 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2229 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2230 2231 if (bootClassPath == null) { 2232 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2233 } 2234 2235 if (systemServerClassPath == null) { 2236 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2237 } 2238 2239 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2240 final String[] dexCodeInstructionSets = 2241 getDexCodeInstructionSets( 2242 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2243 2244 /** 2245 * Ensure all external libraries have had dexopt run on them. 2246 */ 2247 if (mSharedLibraries.size() > 0) { 2248 // NOTE: For now, we're compiling these system "shared libraries" 2249 // (and framework jars) into all available architectures. It's possible 2250 // to compile them only when we come across an app that uses them (there's 2251 // already logic for that in scanPackageLI) but that adds some complexity. 2252 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2253 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2254 final String lib = libEntry.path; 2255 if (lib == null) { 2256 continue; 2257 } 2258 2259 try { 2260 // Shared libraries do not have profiles so we perform a full 2261 // AOT compilation (if needed). 2262 int dexoptNeeded = DexFile.getDexOptNeeded( 2263 lib, dexCodeInstructionSet, 2264 getCompilerFilterForReason(REASON_SHARED_APK), 2265 false /* newProfile */); 2266 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2267 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2268 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/, 2269 getCompilerFilterForReason(REASON_SHARED_APK), 2270 StorageManager.UUID_PRIVATE_INTERNAL); 2271 } 2272 } catch (FileNotFoundException e) { 2273 Slog.w(TAG, "Library not found: " + lib); 2274 } catch (IOException | InstallerException e) { 2275 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2276 + e.getMessage()); 2277 } 2278 } 2279 } 2280 } 2281 2282 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2283 2284 final VersionInfo ver = mSettings.getInternalVersion(); 2285 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2286 2287 // when upgrading from pre-M, promote system app permissions from install to runtime 2288 mPromoteSystemApps = 2289 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2290 2291 // save off the names of pre-existing system packages prior to scanning; we don't 2292 // want to automatically grant runtime permissions for new system apps 2293 if (mPromoteSystemApps) { 2294 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2295 while (pkgSettingIter.hasNext()) { 2296 PackageSetting ps = pkgSettingIter.next(); 2297 if (isSystemApp(ps)) { 2298 mExistingSystemPackages.add(ps.name); 2299 } 2300 } 2301 } 2302 2303 // When upgrading from pre-N, we need to handle package extraction like first boot, 2304 // as there is no profiling data available. 2305 mIsPreNUpgrade = !mSettings.isNWorkDone(); 2306 mSettings.setNWorkDone(); 2307 2308 // Collect vendor overlay packages. 2309 // (Do this before scanning any apps.) 2310 // For security and version matching reason, only consider 2311 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2312 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2313 scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 2314 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2315 2316 // Find base frameworks (resource packages without code). 2317 scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 2318 | PackageParser.PARSE_IS_SYSTEM_DIR 2319 | PackageParser.PARSE_IS_PRIVILEGED, 2320 scanFlags | SCAN_NO_DEX, 0); 2321 2322 // Collected privileged system packages. 2323 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2324 scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 2325 | PackageParser.PARSE_IS_SYSTEM_DIR 2326 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2327 2328 // Collect ordinary system packages. 2329 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2330 scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2331 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2332 2333 // Collect all vendor packages. 2334 File vendorAppDir = new File("/vendor/app"); 2335 try { 2336 vendorAppDir = vendorAppDir.getCanonicalFile(); 2337 } catch (IOException e) { 2338 // failed to look up canonical path, continue with original one 2339 } 2340 scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2341 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2342 2343 // Collect all OEM packages. 2344 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2345 scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2346 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2347 2348 // Prune any system packages that no longer exist. 2349 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2350 if (!mOnlyCore) { 2351 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2352 while (psit.hasNext()) { 2353 PackageSetting ps = psit.next(); 2354 2355 /* 2356 * If this is not a system app, it can't be a 2357 * disable system app. 2358 */ 2359 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2360 continue; 2361 } 2362 2363 /* 2364 * If the package is scanned, it's not erased. 2365 */ 2366 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2367 if (scannedPkg != null) { 2368 /* 2369 * If the system app is both scanned and in the 2370 * disabled packages list, then it must have been 2371 * added via OTA. Remove it from the currently 2372 * scanned package so the previously user-installed 2373 * application can be scanned. 2374 */ 2375 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2376 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2377 + ps.name + "; removing system app. Last known codePath=" 2378 + ps.codePathString + ", installStatus=" + ps.installStatus 2379 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2380 + scannedPkg.mVersionCode); 2381 removePackageLI(scannedPkg, true); 2382 mExpectingBetter.put(ps.name, ps.codePath); 2383 } 2384 2385 continue; 2386 } 2387 2388 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2389 psit.remove(); 2390 logCriticalInfo(Log.WARN, "System package " + ps.name 2391 + " no longer exists; it's data will be wiped"); 2392 // Actual deletion of code and data will be handled by later 2393 // reconciliation step 2394 } else { 2395 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2396 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2397 possiblyDeletedUpdatedSystemApps.add(ps.name); 2398 } 2399 } 2400 } 2401 } 2402 2403 //look for any incomplete package installations 2404 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2405 for (int i = 0; i < deletePkgsList.size(); i++) { 2406 // Actual deletion of code and data will be handled by later 2407 // reconciliation step 2408 final String packageName = deletePkgsList.get(i).name; 2409 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2410 synchronized (mPackages) { 2411 mSettings.removePackageLPw(packageName); 2412 } 2413 } 2414 2415 //delete tmp files 2416 deleteTempPackageFiles(); 2417 2418 // Remove any shared userIDs that have no associated packages 2419 mSettings.pruneSharedUsersLPw(); 2420 2421 if (!mOnlyCore) { 2422 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2423 SystemClock.uptimeMillis()); 2424 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2425 2426 scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2427 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2428 2429 scanDirLI(mEphemeralInstallDir, PackageParser.PARSE_IS_EPHEMERAL, 2430 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2431 2432 /** 2433 * Remove disable package settings for any updated system 2434 * apps that were removed via an OTA. If they're not a 2435 * previously-updated app, remove them completely. 2436 * Otherwise, just revoke their system-level permissions. 2437 */ 2438 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2439 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2440 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2441 2442 String msg; 2443 if (deletedPkg == null) { 2444 msg = "Updated system package " + deletedAppName 2445 + " no longer exists; it's data will be wiped"; 2446 // Actual deletion of code and data will be handled by later 2447 // reconciliation step 2448 } else { 2449 msg = "Updated system app + " + deletedAppName 2450 + " no longer present; removing system privileges for " 2451 + deletedAppName; 2452 2453 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2454 2455 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2456 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2457 } 2458 logCriticalInfo(Log.WARN, msg); 2459 } 2460 2461 /** 2462 * Make sure all system apps that we expected to appear on 2463 * the userdata partition actually showed up. If they never 2464 * appeared, crawl back and revive the system version. 2465 */ 2466 for (int i = 0; i < mExpectingBetter.size(); i++) { 2467 final String packageName = mExpectingBetter.keyAt(i); 2468 if (!mPackages.containsKey(packageName)) { 2469 final File scanFile = mExpectingBetter.valueAt(i); 2470 2471 logCriticalInfo(Log.WARN, "Expected better " + packageName 2472 + " but never showed up; reverting to system"); 2473 2474 final int reparseFlags; 2475 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2476 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2477 | PackageParser.PARSE_IS_SYSTEM_DIR 2478 | PackageParser.PARSE_IS_PRIVILEGED; 2479 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2480 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2481 | PackageParser.PARSE_IS_SYSTEM_DIR; 2482 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2483 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2484 | PackageParser.PARSE_IS_SYSTEM_DIR; 2485 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2486 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2487 | PackageParser.PARSE_IS_SYSTEM_DIR; 2488 } else { 2489 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2490 continue; 2491 } 2492 2493 mSettings.enableSystemPackageLPw(packageName); 2494 2495 try { 2496 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2497 } catch (PackageManagerException e) { 2498 Slog.e(TAG, "Failed to parse original system package: " 2499 + e.getMessage()); 2500 } 2501 } 2502 } 2503 } 2504 mExpectingBetter.clear(); 2505 2506 // Resolve protected action filters. Only the setup wizard is allowed to 2507 // have a high priority filter for these actions. 2508 mSetupWizardPackage = getSetupWizardPackageName(); 2509 if (mProtectedFilters.size() > 0) { 2510 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2511 Slog.i(TAG, "No setup wizard;" 2512 + " All protected intents capped to priority 0"); 2513 } 2514 for (ActivityIntentInfo filter : mProtectedFilters) { 2515 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2516 if (DEBUG_FILTERS) { 2517 Slog.i(TAG, "Found setup wizard;" 2518 + " allow priority " + filter.getPriority() + ";" 2519 + " package: " + filter.activity.info.packageName 2520 + " activity: " + filter.activity.className 2521 + " priority: " + filter.getPriority()); 2522 } 2523 // skip setup wizard; allow it to keep the high priority filter 2524 continue; 2525 } 2526 Slog.w(TAG, "Protected action; cap priority to 0;" 2527 + " package: " + filter.activity.info.packageName 2528 + " activity: " + filter.activity.className 2529 + " origPrio: " + filter.getPriority()); 2530 filter.setPriority(0); 2531 } 2532 } 2533 mDeferProtectedFilters = false; 2534 mProtectedFilters.clear(); 2535 2536 // Now that we know all of the shared libraries, update all clients to have 2537 // the correct library paths. 2538 updateAllSharedLibrariesLPw(); 2539 2540 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2541 // NOTE: We ignore potential failures here during a system scan (like 2542 // the rest of the commands above) because there's precious little we 2543 // can do about it. A settings error is reported, though. 2544 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2545 false /* boot complete */); 2546 } 2547 2548 // Now that we know all the packages we are keeping, 2549 // read and update their last usage times. 2550 mPackageUsage.readLP(); 2551 2552 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2553 SystemClock.uptimeMillis()); 2554 Slog.i(TAG, "Time to scan packages: " 2555 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2556 + " seconds"); 2557 2558 // If the platform SDK has changed since the last time we booted, 2559 // we need to re-grant app permission to catch any new ones that 2560 // appear. This is really a hack, and means that apps can in some 2561 // cases get permissions that the user didn't initially explicitly 2562 // allow... it would be nice to have some better way to handle 2563 // this situation. 2564 int updateFlags = UPDATE_PERMISSIONS_ALL; 2565 if (ver.sdkVersion != mSdkVersion) { 2566 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2567 + mSdkVersion + "; regranting permissions for internal storage"); 2568 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2569 } 2570 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2571 ver.sdkVersion = mSdkVersion; 2572 2573 // If this is the first boot or an update from pre-M, and it is a normal 2574 // boot, then we need to initialize the default preferred apps across 2575 // all defined users. 2576 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2577 for (UserInfo user : sUserManager.getUsers(true)) { 2578 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2579 applyFactoryDefaultBrowserLPw(user.id); 2580 primeDomainVerificationsLPw(user.id); 2581 } 2582 } 2583 2584 // Prepare storage for system user really early during boot, 2585 // since core system apps like SettingsProvider and SystemUI 2586 // can't wait for user to start 2587 final int storageFlags; 2588 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2589 storageFlags = StorageManager.FLAG_STORAGE_DE; 2590 } else { 2591 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2592 } 2593 reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2594 storageFlags); 2595 2596 // If this is first boot after an OTA, and a normal boot, then 2597 // we need to clear code cache directories. 2598 if (mIsUpgrade && !onlyCore) { 2599 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2600 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2601 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2602 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2603 // No apps are running this early, so no need to freeze 2604 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2605 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2606 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2607 } 2608 clearAppProfilesLIF(ps.pkg); 2609 } 2610 ver.fingerprint = Build.FINGERPRINT; 2611 } 2612 2613 checkDefaultBrowser(); 2614 2615 // clear only after permissions and other defaults have been updated 2616 mExistingSystemPackages.clear(); 2617 mPromoteSystemApps = false; 2618 2619 // All the changes are done during package scanning. 2620 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2621 2622 // can downgrade to reader 2623 mSettings.writeLPr(); 2624 2625 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2626 SystemClock.uptimeMillis()); 2627 2628 if (!mOnlyCore) { 2629 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2630 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2631 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2632 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2633 mIntentFilterVerifierComponent); 2634 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2635 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 2636 getRequiredSharedLibraryLPr( 2637 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED); 2638 } else { 2639 mRequiredVerifierPackage = null; 2640 mRequiredInstallerPackage = null; 2641 mIntentFilterVerifierComponent = null; 2642 mIntentFilterVerifier = null; 2643 mServicesSystemSharedLibraryPackageName = null; 2644 } 2645 2646 mInstallerService = new PackageInstallerService(context, this); 2647 2648 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2649 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2650 // both the installer and resolver must be present to enable ephemeral 2651 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2652 if (DEBUG_EPHEMERAL) { 2653 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2654 + " installer:" + ephemeralInstallerComponent); 2655 } 2656 mEphemeralResolverComponent = ephemeralResolverComponent; 2657 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2658 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2659 mEphemeralResolverConnection = 2660 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2661 } else { 2662 if (DEBUG_EPHEMERAL) { 2663 final String missingComponent = 2664 (ephemeralResolverComponent == null) 2665 ? (ephemeralInstallerComponent == null) 2666 ? "resolver and installer" 2667 : "resolver" 2668 : "installer"; 2669 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2670 } 2671 mEphemeralResolverComponent = null; 2672 mEphemeralInstallerComponent = null; 2673 mEphemeralResolverConnection = null; 2674 } 2675 2676 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2677 } // synchronized (mPackages) 2678 } // synchronized (mInstallLock) 2679 2680 // Now after opening every single application zip, make sure they 2681 // are all flushed. Not really needed, but keeps things nice and 2682 // tidy. 2683 Runtime.getRuntime().gc(); 2684 2685 // The initial scanning above does many calls into installd while 2686 // holding the mPackages lock, but we're mostly interested in yelling 2687 // once we have a booted system. 2688 mInstaller.setWarnIfHeld(mPackages); 2689 2690 // Expose private service for system components to use. 2691 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2692 } 2693 2694 @Override 2695 public boolean isFirstBoot() { 2696 return !mRestoredSettings; 2697 } 2698 2699 @Override 2700 public boolean isOnlyCoreApps() { 2701 return mOnlyCore; 2702 } 2703 2704 @Override 2705 public boolean isUpgrade() { 2706 return mIsUpgrade; 2707 } 2708 2709 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2710 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2711 2712 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2713 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2714 UserHandle.USER_SYSTEM); 2715 if (matches.size() == 1) { 2716 return matches.get(0).getComponentInfo().packageName; 2717 } else { 2718 Log.e(TAG, "There should probably be exactly one verifier; found " + matches); 2719 return null; 2720 } 2721 } 2722 2723 private @NonNull String getRequiredSharedLibraryLPr(String libraryName) { 2724 synchronized (mPackages) { 2725 SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName); 2726 if (libraryEntry == null) { 2727 throw new IllegalStateException("Missing required shared library:" + libraryName); 2728 } 2729 return libraryEntry.apk; 2730 } 2731 } 2732 2733 private @NonNull String getRequiredInstallerLPr() { 2734 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2735 intent.addCategory(Intent.CATEGORY_DEFAULT); 2736 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2737 2738 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2739 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2740 UserHandle.USER_SYSTEM); 2741 if (matches.size() == 1) { 2742 ResolveInfo resolveInfo = matches.get(0); 2743 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 2744 throw new RuntimeException("The installer must be a privileged app"); 2745 } 2746 return matches.get(0).getComponentInfo().packageName; 2747 } else { 2748 throw new RuntimeException("There must be exactly one installer; found " + matches); 2749 } 2750 } 2751 2752 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2753 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2754 2755 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2756 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2757 UserHandle.USER_SYSTEM); 2758 ResolveInfo best = null; 2759 final int N = matches.size(); 2760 for (int i = 0; i < N; i++) { 2761 final ResolveInfo cur = matches.get(i); 2762 final String packageName = cur.getComponentInfo().packageName; 2763 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2764 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2765 continue; 2766 } 2767 2768 if (best == null || cur.priority > best.priority) { 2769 best = cur; 2770 } 2771 } 2772 2773 if (best != null) { 2774 return best.getComponentInfo().getComponentName(); 2775 } else { 2776 throw new RuntimeException("There must be at least one intent filter verifier"); 2777 } 2778 } 2779 2780 private @Nullable ComponentName getEphemeralResolverLPr() { 2781 final String[] packageArray = 2782 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2783 if (packageArray.length == 0) { 2784 if (DEBUG_EPHEMERAL) { 2785 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2786 } 2787 return null; 2788 } 2789 2790 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2791 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 2792 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2793 UserHandle.USER_SYSTEM); 2794 2795 final int N = resolvers.size(); 2796 if (N == 0) { 2797 if (DEBUG_EPHEMERAL) { 2798 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2799 } 2800 return null; 2801 } 2802 2803 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2804 for (int i = 0; i < N; i++) { 2805 final ResolveInfo info = resolvers.get(i); 2806 2807 if (info.serviceInfo == null) { 2808 continue; 2809 } 2810 2811 final String packageName = info.serviceInfo.packageName; 2812 if (!possiblePackages.contains(packageName)) { 2813 if (DEBUG_EPHEMERAL) { 2814 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2815 + " pkg: " + packageName + ", info:" + info); 2816 } 2817 continue; 2818 } 2819 2820 if (DEBUG_EPHEMERAL) { 2821 Slog.v(TAG, "Ephemeral resolver found;" 2822 + " pkg: " + packageName + ", info:" + info); 2823 } 2824 return new ComponentName(packageName, info.serviceInfo.name); 2825 } 2826 if (DEBUG_EPHEMERAL) { 2827 Slog.v(TAG, "Ephemeral resolver NOT found"); 2828 } 2829 return null; 2830 } 2831 2832 private @Nullable ComponentName getEphemeralInstallerLPr() { 2833 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2834 intent.addCategory(Intent.CATEGORY_DEFAULT); 2835 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2836 2837 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2838 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2839 UserHandle.USER_SYSTEM); 2840 if (matches.size() == 0) { 2841 return null; 2842 } else if (matches.size() == 1) { 2843 return matches.get(0).getComponentInfo().getComponentName(); 2844 } else { 2845 throw new RuntimeException( 2846 "There must be at most one ephemeral installer; found " + matches); 2847 } 2848 } 2849 2850 private void primeDomainVerificationsLPw(int userId) { 2851 if (DEBUG_DOMAIN_VERIFICATION) { 2852 Slog.d(TAG, "Priming domain verifications in user " + userId); 2853 } 2854 2855 SystemConfig systemConfig = SystemConfig.getInstance(); 2856 ArraySet<String> packages = systemConfig.getLinkedApps(); 2857 ArraySet<String> domains = new ArraySet<String>(); 2858 2859 for (String packageName : packages) { 2860 PackageParser.Package pkg = mPackages.get(packageName); 2861 if (pkg != null) { 2862 if (!pkg.isSystemApp()) { 2863 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2864 continue; 2865 } 2866 2867 domains.clear(); 2868 for (PackageParser.Activity a : pkg.activities) { 2869 for (ActivityIntentInfo filter : a.intents) { 2870 if (hasValidDomains(filter)) { 2871 domains.addAll(filter.getHostsList()); 2872 } 2873 } 2874 } 2875 2876 if (domains.size() > 0) { 2877 if (DEBUG_DOMAIN_VERIFICATION) { 2878 Slog.v(TAG, " + " + packageName); 2879 } 2880 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2881 // state w.r.t. the formal app-linkage "no verification attempted" state; 2882 // and then 'always' in the per-user state actually used for intent resolution. 2883 final IntentFilterVerificationInfo ivi; 2884 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2885 new ArrayList<String>(domains)); 2886 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2887 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2888 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2889 } else { 2890 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2891 + "' does not handle web links"); 2892 } 2893 } else { 2894 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 2895 } 2896 } 2897 2898 scheduleWritePackageRestrictionsLocked(userId); 2899 scheduleWriteSettingsLocked(); 2900 } 2901 2902 private void applyFactoryDefaultBrowserLPw(int userId) { 2903 // The default browser app's package name is stored in a string resource, 2904 // with a product-specific overlay used for vendor customization. 2905 String browserPkg = mContext.getResources().getString( 2906 com.android.internal.R.string.default_browser); 2907 if (!TextUtils.isEmpty(browserPkg)) { 2908 // non-empty string => required to be a known package 2909 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2910 if (ps == null) { 2911 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2912 browserPkg = null; 2913 } else { 2914 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2915 } 2916 } 2917 2918 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2919 // default. If there's more than one, just leave everything alone. 2920 if (browserPkg == null) { 2921 calculateDefaultBrowserLPw(userId); 2922 } 2923 } 2924 2925 private void calculateDefaultBrowserLPw(int userId) { 2926 List<String> allBrowsers = resolveAllBrowserApps(userId); 2927 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2928 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2929 } 2930 2931 private List<String> resolveAllBrowserApps(int userId) { 2932 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2933 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 2934 PackageManager.MATCH_ALL, userId); 2935 2936 final int count = list.size(); 2937 List<String> result = new ArrayList<String>(count); 2938 for (int i=0; i<count; i++) { 2939 ResolveInfo info = list.get(i); 2940 if (info.activityInfo == null 2941 || !info.handleAllWebDataURI 2942 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2943 || result.contains(info.activityInfo.packageName)) { 2944 continue; 2945 } 2946 result.add(info.activityInfo.packageName); 2947 } 2948 2949 return result; 2950 } 2951 2952 private boolean packageIsBrowser(String packageName, int userId) { 2953 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 2954 PackageManager.MATCH_ALL, userId); 2955 final int N = list.size(); 2956 for (int i = 0; i < N; i++) { 2957 ResolveInfo info = list.get(i); 2958 if (packageName.equals(info.activityInfo.packageName)) { 2959 return true; 2960 } 2961 } 2962 return false; 2963 } 2964 2965 private void checkDefaultBrowser() { 2966 final int myUserId = UserHandle.myUserId(); 2967 final String packageName = getDefaultBrowserPackageName(myUserId); 2968 if (packageName != null) { 2969 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2970 if (info == null) { 2971 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2972 synchronized (mPackages) { 2973 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2974 } 2975 } 2976 } 2977 } 2978 2979 @Override 2980 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2981 throws RemoteException { 2982 try { 2983 return super.onTransact(code, data, reply, flags); 2984 } catch (RuntimeException e) { 2985 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2986 Slog.wtf(TAG, "Package Manager Crash", e); 2987 } 2988 throw e; 2989 } 2990 } 2991 2992 static int[] appendInts(int[] cur, int[] add) { 2993 if (add == null) return cur; 2994 if (cur == null) return add; 2995 final int N = add.length; 2996 for (int i=0; i<N; i++) { 2997 cur = appendInt(cur, add[i]); 2998 } 2999 return cur; 3000 } 3001 3002 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3003 if (!sUserManager.exists(userId)) return null; 3004 if (ps == null) { 3005 return null; 3006 } 3007 final PackageParser.Package p = ps.pkg; 3008 if (p == null) { 3009 return null; 3010 } 3011 3012 final PermissionsState permissionsState = ps.getPermissionsState(); 3013 3014 final int[] gids = permissionsState.computeGids(userId); 3015 final Set<String> permissions = permissionsState.getPermissions(userId); 3016 final PackageUserState state = ps.readUserState(userId); 3017 3018 return PackageParser.generatePackageInfo(p, gids, flags, 3019 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3020 } 3021 3022 @Override 3023 public void checkPackageStartable(String packageName, int userId) { 3024 final boolean userKeyUnlocked = isUserKeyUnlocked(userId); 3025 3026 synchronized (mPackages) { 3027 final PackageSetting ps = mSettings.mPackages.get(packageName); 3028 if (ps == null) { 3029 throw new SecurityException("Package " + packageName + " was not found!"); 3030 } 3031 3032 if (!ps.getInstalled(userId)) { 3033 throw new SecurityException( 3034 "Package " + packageName + " was not installed for user " + userId + "!"); 3035 } 3036 3037 if (mSafeMode && !ps.isSystem()) { 3038 throw new SecurityException("Package " + packageName + " not a system app!"); 3039 } 3040 3041 if (mFrozenPackages.contains(packageName)) { 3042 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3043 } 3044 3045 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3046 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3047 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3048 } 3049 } 3050 } 3051 3052 @Override 3053 public boolean isPackageAvailable(String packageName, int userId) { 3054 if (!sUserManager.exists(userId)) return false; 3055 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3056 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3057 synchronized (mPackages) { 3058 PackageParser.Package p = mPackages.get(packageName); 3059 if (p != null) { 3060 final PackageSetting ps = (PackageSetting) p.mExtras; 3061 if (ps != null) { 3062 final PackageUserState state = ps.readUserState(userId); 3063 if (state != null) { 3064 return PackageParser.isAvailable(state); 3065 } 3066 } 3067 } 3068 } 3069 return false; 3070 } 3071 3072 @Override 3073 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3074 if (!sUserManager.exists(userId)) return null; 3075 flags = updateFlagsForPackage(flags, userId, packageName); 3076 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3077 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3078 // reader 3079 synchronized (mPackages) { 3080 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3081 PackageParser.Package p = null; 3082 if (matchFactoryOnly) { 3083 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3084 if (ps != null) { 3085 return generatePackageInfo(ps, flags, userId); 3086 } 3087 } 3088 if (p == null) { 3089 p = mPackages.get(packageName); 3090 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3091 return null; 3092 } 3093 } 3094 if (DEBUG_PACKAGE_INFO) 3095 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3096 if (p != null) { 3097 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3098 } 3099 if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3100 final PackageSetting ps = mSettings.mPackages.get(packageName); 3101 return generatePackageInfo(ps, flags, userId); 3102 } 3103 } 3104 return null; 3105 } 3106 3107 @Override 3108 public String[] currentToCanonicalPackageNames(String[] names) { 3109 String[] out = new String[names.length]; 3110 // reader 3111 synchronized (mPackages) { 3112 for (int i=names.length-1; i>=0; i--) { 3113 PackageSetting ps = mSettings.mPackages.get(names[i]); 3114 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3115 } 3116 } 3117 return out; 3118 } 3119 3120 @Override 3121 public String[] canonicalToCurrentPackageNames(String[] names) { 3122 String[] out = new String[names.length]; 3123 // reader 3124 synchronized (mPackages) { 3125 for (int i=names.length-1; i>=0; i--) { 3126 String cur = mSettings.mRenamedPackages.get(names[i]); 3127 out[i] = cur != null ? cur : names[i]; 3128 } 3129 } 3130 return out; 3131 } 3132 3133 @Override 3134 public int getPackageUid(String packageName, int flags, int userId) { 3135 if (!sUserManager.exists(userId)) return -1; 3136 flags = updateFlagsForPackage(flags, userId, packageName); 3137 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3138 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3139 3140 // reader 3141 synchronized (mPackages) { 3142 final PackageParser.Package p = mPackages.get(packageName); 3143 if (p != null && p.isMatch(flags)) { 3144 return UserHandle.getUid(userId, p.applicationInfo.uid); 3145 } 3146 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3147 final PackageSetting ps = mSettings.mPackages.get(packageName); 3148 if (ps != null && ps.isMatch(flags)) { 3149 return UserHandle.getUid(userId, ps.appId); 3150 } 3151 } 3152 } 3153 3154 return -1; 3155 } 3156 3157 @Override 3158 public int[] getPackageGids(String packageName, int flags, int userId) { 3159 if (!sUserManager.exists(userId)) return null; 3160 flags = updateFlagsForPackage(flags, userId, packageName); 3161 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3162 false /* requireFullPermission */, false /* checkShell */, 3163 "getPackageGids"); 3164 3165 // reader 3166 synchronized (mPackages) { 3167 final PackageParser.Package p = mPackages.get(packageName); 3168 if (p != null && p.isMatch(flags)) { 3169 PackageSetting ps = (PackageSetting) p.mExtras; 3170 return ps.getPermissionsState().computeGids(userId); 3171 } 3172 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3173 final PackageSetting ps = mSettings.mPackages.get(packageName); 3174 if (ps != null && ps.isMatch(flags)) { 3175 return ps.getPermissionsState().computeGids(userId); 3176 } 3177 } 3178 } 3179 3180 return null; 3181 } 3182 3183 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3184 if (bp.perm != null) { 3185 return PackageParser.generatePermissionInfo(bp.perm, flags); 3186 } 3187 PermissionInfo pi = new PermissionInfo(); 3188 pi.name = bp.name; 3189 pi.packageName = bp.sourcePackage; 3190 pi.nonLocalizedLabel = bp.name; 3191 pi.protectionLevel = bp.protectionLevel; 3192 return pi; 3193 } 3194 3195 @Override 3196 public PermissionInfo getPermissionInfo(String name, int flags) { 3197 // reader 3198 synchronized (mPackages) { 3199 final BasePermission p = mSettings.mPermissions.get(name); 3200 if (p != null) { 3201 return generatePermissionInfo(p, flags); 3202 } 3203 return null; 3204 } 3205 } 3206 3207 @Override 3208 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3209 int flags) { 3210 // reader 3211 synchronized (mPackages) { 3212 if (group != null && !mPermissionGroups.containsKey(group)) { 3213 // This is thrown as NameNotFoundException 3214 return null; 3215 } 3216 3217 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3218 for (BasePermission p : mSettings.mPermissions.values()) { 3219 if (group == null) { 3220 if (p.perm == null || p.perm.info.group == null) { 3221 out.add(generatePermissionInfo(p, flags)); 3222 } 3223 } else { 3224 if (p.perm != null && group.equals(p.perm.info.group)) { 3225 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3226 } 3227 } 3228 } 3229 return new ParceledListSlice<>(out); 3230 } 3231 } 3232 3233 @Override 3234 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3235 // reader 3236 synchronized (mPackages) { 3237 return PackageParser.generatePermissionGroupInfo( 3238 mPermissionGroups.get(name), flags); 3239 } 3240 } 3241 3242 @Override 3243 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3244 // reader 3245 synchronized (mPackages) { 3246 final int N = mPermissionGroups.size(); 3247 ArrayList<PermissionGroupInfo> out 3248 = new ArrayList<PermissionGroupInfo>(N); 3249 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3250 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3251 } 3252 return new ParceledListSlice<>(out); 3253 } 3254 } 3255 3256 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3257 int userId) { 3258 if (!sUserManager.exists(userId)) return null; 3259 PackageSetting ps = mSettings.mPackages.get(packageName); 3260 if (ps != null) { 3261 if (ps.pkg == null) { 3262 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3263 if (pInfo != null) { 3264 return pInfo.applicationInfo; 3265 } 3266 return null; 3267 } 3268 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3269 ps.readUserState(userId), userId); 3270 } 3271 return null; 3272 } 3273 3274 @Override 3275 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3276 if (!sUserManager.exists(userId)) return null; 3277 flags = updateFlagsForApplication(flags, userId, packageName); 3278 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3279 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3280 // writer 3281 synchronized (mPackages) { 3282 PackageParser.Package p = mPackages.get(packageName); 3283 if (DEBUG_PACKAGE_INFO) Log.v( 3284 TAG, "getApplicationInfo " + packageName 3285 + ": " + p); 3286 if (p != null) { 3287 PackageSetting ps = mSettings.mPackages.get(packageName); 3288 if (ps == null) return null; 3289 // Note: isEnabledLP() does not apply here - always return info 3290 return PackageParser.generateApplicationInfo( 3291 p, flags, ps.readUserState(userId), userId); 3292 } 3293 if ("android".equals(packageName)||"system".equals(packageName)) { 3294 return mAndroidApplication; 3295 } 3296 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3297 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3298 } 3299 } 3300 return null; 3301 } 3302 3303 @Override 3304 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3305 final IPackageDataObserver observer) { 3306 mContext.enforceCallingOrSelfPermission( 3307 android.Manifest.permission.CLEAR_APP_CACHE, null); 3308 // Queue up an async operation since clearing cache may take a little while. 3309 mHandler.post(new Runnable() { 3310 public void run() { 3311 mHandler.removeCallbacks(this); 3312 boolean success = true; 3313 synchronized (mInstallLock) { 3314 try { 3315 mInstaller.freeCache(volumeUuid, freeStorageSize); 3316 } catch (InstallerException e) { 3317 Slog.w(TAG, "Couldn't clear application caches: " + e); 3318 success = false; 3319 } 3320 } 3321 if (observer != null) { 3322 try { 3323 observer.onRemoveCompleted(null, success); 3324 } catch (RemoteException e) { 3325 Slog.w(TAG, "RemoveException when invoking call back"); 3326 } 3327 } 3328 } 3329 }); 3330 } 3331 3332 @Override 3333 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3334 final IntentSender pi) { 3335 mContext.enforceCallingOrSelfPermission( 3336 android.Manifest.permission.CLEAR_APP_CACHE, null); 3337 // Queue up an async operation since clearing cache may take a little while. 3338 mHandler.post(new Runnable() { 3339 public void run() { 3340 mHandler.removeCallbacks(this); 3341 boolean success = true; 3342 synchronized (mInstallLock) { 3343 try { 3344 mInstaller.freeCache(volumeUuid, freeStorageSize); 3345 } catch (InstallerException e) { 3346 Slog.w(TAG, "Couldn't clear application caches: " + e); 3347 success = false; 3348 } 3349 } 3350 if(pi != null) { 3351 try { 3352 // Callback via pending intent 3353 int code = success ? 1 : 0; 3354 pi.sendIntent(null, code, null, 3355 null, null); 3356 } catch (SendIntentException e1) { 3357 Slog.i(TAG, "Failed to send pending intent"); 3358 } 3359 } 3360 } 3361 }); 3362 } 3363 3364 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3365 synchronized (mInstallLock) { 3366 try { 3367 mInstaller.freeCache(volumeUuid, freeStorageSize); 3368 } catch (InstallerException e) { 3369 throw new IOException("Failed to free enough space", e); 3370 } 3371 } 3372 } 3373 3374 /** 3375 * Return if the user key is currently unlocked. 3376 */ 3377 private boolean isUserKeyUnlocked(int userId) { 3378 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 3379 final IMountService mount = IMountService.Stub 3380 .asInterface(ServiceManager.getService("mount")); 3381 if (mount == null) { 3382 Slog.w(TAG, "Early during boot, assuming locked"); 3383 return false; 3384 } 3385 final long token = Binder.clearCallingIdentity(); 3386 try { 3387 return mount.isUserKeyUnlocked(userId); 3388 } catch (RemoteException e) { 3389 throw e.rethrowAsRuntimeException(); 3390 } finally { 3391 Binder.restoreCallingIdentity(token); 3392 } 3393 } else { 3394 return true; 3395 } 3396 } 3397 3398 /** 3399 * Update given flags based on encryption status of current user. 3400 */ 3401 private int updateFlags(int flags, int userId) { 3402 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3403 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3404 // Caller expressed an explicit opinion about what encryption 3405 // aware/unaware components they want to see, so fall through and 3406 // give them what they want 3407 } else { 3408 // Caller expressed no opinion, so match based on user state 3409 if (isUserKeyUnlocked(userId)) { 3410 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3411 } else { 3412 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3413 } 3414 } 3415 return flags; 3416 } 3417 3418 /** 3419 * Update given flags when being used to request {@link PackageInfo}. 3420 */ 3421 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3422 boolean triaged = true; 3423 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3424 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3425 // Caller is asking for component details, so they'd better be 3426 // asking for specific encryption matching behavior, or be triaged 3427 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3428 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3429 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3430 triaged = false; 3431 } 3432 } 3433 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3434 | PackageManager.MATCH_SYSTEM_ONLY 3435 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3436 triaged = false; 3437 } 3438 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3439 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3440 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3441 } 3442 return updateFlags(flags, userId); 3443 } 3444 3445 /** 3446 * Update given flags when being used to request {@link ApplicationInfo}. 3447 */ 3448 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3449 return updateFlagsForPackage(flags, userId, cookie); 3450 } 3451 3452 /** 3453 * Update given flags when being used to request {@link ComponentInfo}. 3454 */ 3455 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3456 if (cookie instanceof Intent) { 3457 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3458 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3459 } 3460 } 3461 3462 boolean triaged = true; 3463 // Caller is asking for component details, so they'd better be 3464 // asking for specific encryption matching behavior, or be triaged 3465 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3466 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3467 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3468 triaged = false; 3469 } 3470 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3471 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3472 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3473 } 3474 3475 return updateFlags(flags, userId); 3476 } 3477 3478 /** 3479 * Update given flags when being used to request {@link ResolveInfo}. 3480 */ 3481 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3482 // Safe mode means we shouldn't match any third-party components 3483 if (mSafeMode) { 3484 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3485 } 3486 3487 return updateFlagsForComponent(flags, userId, cookie); 3488 } 3489 3490 @Override 3491 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3492 if (!sUserManager.exists(userId)) return null; 3493 flags = updateFlagsForComponent(flags, userId, component); 3494 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3495 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3496 synchronized (mPackages) { 3497 PackageParser.Activity a = mActivities.mActivities.get(component); 3498 3499 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3500 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3501 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3502 if (ps == null) return null; 3503 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3504 userId); 3505 } 3506 if (mResolveComponentName.equals(component)) { 3507 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3508 new PackageUserState(), userId); 3509 } 3510 } 3511 return null; 3512 } 3513 3514 @Override 3515 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3516 String resolvedType) { 3517 synchronized (mPackages) { 3518 if (component.equals(mResolveComponentName)) { 3519 // The resolver supports EVERYTHING! 3520 return true; 3521 } 3522 PackageParser.Activity a = mActivities.mActivities.get(component); 3523 if (a == null) { 3524 return false; 3525 } 3526 for (int i=0; i<a.intents.size(); i++) { 3527 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3528 intent.getData(), intent.getCategories(), TAG) >= 0) { 3529 return true; 3530 } 3531 } 3532 return false; 3533 } 3534 } 3535 3536 @Override 3537 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3538 if (!sUserManager.exists(userId)) return null; 3539 flags = updateFlagsForComponent(flags, userId, component); 3540 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3541 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3542 synchronized (mPackages) { 3543 PackageParser.Activity a = mReceivers.mActivities.get(component); 3544 if (DEBUG_PACKAGE_INFO) Log.v( 3545 TAG, "getReceiverInfo " + component + ": " + a); 3546 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3547 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3548 if (ps == null) return null; 3549 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3550 userId); 3551 } 3552 } 3553 return null; 3554 } 3555 3556 @Override 3557 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3558 if (!sUserManager.exists(userId)) return null; 3559 flags = updateFlagsForComponent(flags, userId, component); 3560 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3561 false /* requireFullPermission */, false /* checkShell */, "get service info"); 3562 synchronized (mPackages) { 3563 PackageParser.Service s = mServices.mServices.get(component); 3564 if (DEBUG_PACKAGE_INFO) Log.v( 3565 TAG, "getServiceInfo " + component + ": " + s); 3566 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3567 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3568 if (ps == null) return null; 3569 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3570 userId); 3571 } 3572 } 3573 return null; 3574 } 3575 3576 @Override 3577 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3578 if (!sUserManager.exists(userId)) return null; 3579 flags = updateFlagsForComponent(flags, userId, component); 3580 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3581 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 3582 synchronized (mPackages) { 3583 PackageParser.Provider p = mProviders.mProviders.get(component); 3584 if (DEBUG_PACKAGE_INFO) Log.v( 3585 TAG, "getProviderInfo " + component + ": " + p); 3586 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3587 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3588 if (ps == null) return null; 3589 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3590 userId); 3591 } 3592 } 3593 return null; 3594 } 3595 3596 @Override 3597 public String[] getSystemSharedLibraryNames() { 3598 Set<String> libSet; 3599 synchronized (mPackages) { 3600 libSet = mSharedLibraries.keySet(); 3601 int size = libSet.size(); 3602 if (size > 0) { 3603 String[] libs = new String[size]; 3604 libSet.toArray(libs); 3605 return libs; 3606 } 3607 } 3608 return null; 3609 } 3610 3611 @Override 3612 public @NonNull String getServicesSystemSharedLibraryPackageName() { 3613 synchronized (mPackages) { 3614 return mServicesSystemSharedLibraryPackageName; 3615 } 3616 } 3617 3618 @Override 3619 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 3620 synchronized (mPackages) { 3621 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values()); 3622 3623 final FeatureInfo fi = new FeatureInfo(); 3624 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3625 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3626 res.add(fi); 3627 3628 return new ParceledListSlice<>(res); 3629 } 3630 } 3631 3632 @Override 3633 public boolean hasSystemFeature(String name, int version) { 3634 synchronized (mPackages) { 3635 final FeatureInfo feat = mAvailableFeatures.get(name); 3636 if (feat == null) { 3637 return false; 3638 } else { 3639 return feat.version >= version; 3640 } 3641 } 3642 } 3643 3644 @Override 3645 public int checkPermission(String permName, String pkgName, int userId) { 3646 if (!sUserManager.exists(userId)) { 3647 return PackageManager.PERMISSION_DENIED; 3648 } 3649 3650 synchronized (mPackages) { 3651 final PackageParser.Package p = mPackages.get(pkgName); 3652 if (p != null && p.mExtras != null) { 3653 final PackageSetting ps = (PackageSetting) p.mExtras; 3654 final PermissionsState permissionsState = ps.getPermissionsState(); 3655 if (permissionsState.hasPermission(permName, userId)) { 3656 return PackageManager.PERMISSION_GRANTED; 3657 } 3658 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3659 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3660 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3661 return PackageManager.PERMISSION_GRANTED; 3662 } 3663 } 3664 } 3665 3666 return PackageManager.PERMISSION_DENIED; 3667 } 3668 3669 @Override 3670 public int checkUidPermission(String permName, int uid) { 3671 final int userId = UserHandle.getUserId(uid); 3672 3673 if (!sUserManager.exists(userId)) { 3674 return PackageManager.PERMISSION_DENIED; 3675 } 3676 3677 synchronized (mPackages) { 3678 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3679 if (obj != null) { 3680 final SettingBase ps = (SettingBase) obj; 3681 final PermissionsState permissionsState = ps.getPermissionsState(); 3682 if (permissionsState.hasPermission(permName, userId)) { 3683 return PackageManager.PERMISSION_GRANTED; 3684 } 3685 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3686 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3687 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3688 return PackageManager.PERMISSION_GRANTED; 3689 } 3690 } else { 3691 ArraySet<String> perms = mSystemPermissions.get(uid); 3692 if (perms != null) { 3693 if (perms.contains(permName)) { 3694 return PackageManager.PERMISSION_GRANTED; 3695 } 3696 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3697 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3698 return PackageManager.PERMISSION_GRANTED; 3699 } 3700 } 3701 } 3702 } 3703 3704 return PackageManager.PERMISSION_DENIED; 3705 } 3706 3707 @Override 3708 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3709 if (UserHandle.getCallingUserId() != userId) { 3710 mContext.enforceCallingPermission( 3711 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3712 "isPermissionRevokedByPolicy for user " + userId); 3713 } 3714 3715 if (checkPermission(permission, packageName, userId) 3716 == PackageManager.PERMISSION_GRANTED) { 3717 return false; 3718 } 3719 3720 final long identity = Binder.clearCallingIdentity(); 3721 try { 3722 final int flags = getPermissionFlags(permission, packageName, userId); 3723 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3724 } finally { 3725 Binder.restoreCallingIdentity(identity); 3726 } 3727 } 3728 3729 @Override 3730 public String getPermissionControllerPackageName() { 3731 synchronized (mPackages) { 3732 return mRequiredInstallerPackage; 3733 } 3734 } 3735 3736 /** 3737 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3738 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3739 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3740 * @param message the message to log on security exception 3741 */ 3742 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3743 boolean checkShell, String message) { 3744 if (userId < 0) { 3745 throw new IllegalArgumentException("Invalid userId " + userId); 3746 } 3747 if (checkShell) { 3748 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3749 } 3750 if (userId == UserHandle.getUserId(callingUid)) return; 3751 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3752 if (requireFullPermission) { 3753 mContext.enforceCallingOrSelfPermission( 3754 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3755 } else { 3756 try { 3757 mContext.enforceCallingOrSelfPermission( 3758 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3759 } catch (SecurityException se) { 3760 mContext.enforceCallingOrSelfPermission( 3761 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3762 } 3763 } 3764 } 3765 } 3766 3767 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3768 if (callingUid == Process.SHELL_UID) { 3769 if (userHandle >= 0 3770 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3771 throw new SecurityException("Shell does not have permission to access user " 3772 + userHandle); 3773 } else if (userHandle < 0) { 3774 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3775 + Debug.getCallers(3)); 3776 } 3777 } 3778 } 3779 3780 private BasePermission findPermissionTreeLP(String permName) { 3781 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3782 if (permName.startsWith(bp.name) && 3783 permName.length() > bp.name.length() && 3784 permName.charAt(bp.name.length()) == '.') { 3785 return bp; 3786 } 3787 } 3788 return null; 3789 } 3790 3791 private BasePermission checkPermissionTreeLP(String permName) { 3792 if (permName != null) { 3793 BasePermission bp = findPermissionTreeLP(permName); 3794 if (bp != null) { 3795 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3796 return bp; 3797 } 3798 throw new SecurityException("Calling uid " 3799 + Binder.getCallingUid() 3800 + " is not allowed to add to permission tree " 3801 + bp.name + " owned by uid " + bp.uid); 3802 } 3803 } 3804 throw new SecurityException("No permission tree found for " + permName); 3805 } 3806 3807 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3808 if (s1 == null) { 3809 return s2 == null; 3810 } 3811 if (s2 == null) { 3812 return false; 3813 } 3814 if (s1.getClass() != s2.getClass()) { 3815 return false; 3816 } 3817 return s1.equals(s2); 3818 } 3819 3820 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3821 if (pi1.icon != pi2.icon) return false; 3822 if (pi1.logo != pi2.logo) return false; 3823 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3824 if (!compareStrings(pi1.name, pi2.name)) return false; 3825 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3826 // We'll take care of setting this one. 3827 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3828 // These are not currently stored in settings. 3829 //if (!compareStrings(pi1.group, pi2.group)) return false; 3830 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3831 //if (pi1.labelRes != pi2.labelRes) return false; 3832 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3833 return true; 3834 } 3835 3836 int permissionInfoFootprint(PermissionInfo info) { 3837 int size = info.name.length(); 3838 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3839 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3840 return size; 3841 } 3842 3843 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3844 int size = 0; 3845 for (BasePermission perm : mSettings.mPermissions.values()) { 3846 if (perm.uid == tree.uid) { 3847 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3848 } 3849 } 3850 return size; 3851 } 3852 3853 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3854 // We calculate the max size of permissions defined by this uid and throw 3855 // if that plus the size of 'info' would exceed our stated maximum. 3856 if (tree.uid != Process.SYSTEM_UID) { 3857 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3858 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3859 throw new SecurityException("Permission tree size cap exceeded"); 3860 } 3861 } 3862 } 3863 3864 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3865 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3866 throw new SecurityException("Label must be specified in permission"); 3867 } 3868 BasePermission tree = checkPermissionTreeLP(info.name); 3869 BasePermission bp = mSettings.mPermissions.get(info.name); 3870 boolean added = bp == null; 3871 boolean changed = true; 3872 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3873 if (added) { 3874 enforcePermissionCapLocked(info, tree); 3875 bp = new BasePermission(info.name, tree.sourcePackage, 3876 BasePermission.TYPE_DYNAMIC); 3877 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3878 throw new SecurityException( 3879 "Not allowed to modify non-dynamic permission " 3880 + info.name); 3881 } else { 3882 if (bp.protectionLevel == fixedLevel 3883 && bp.perm.owner.equals(tree.perm.owner) 3884 && bp.uid == tree.uid 3885 && comparePermissionInfos(bp.perm.info, info)) { 3886 changed = false; 3887 } 3888 } 3889 bp.protectionLevel = fixedLevel; 3890 info = new PermissionInfo(info); 3891 info.protectionLevel = fixedLevel; 3892 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3893 bp.perm.info.packageName = tree.perm.info.packageName; 3894 bp.uid = tree.uid; 3895 if (added) { 3896 mSettings.mPermissions.put(info.name, bp); 3897 } 3898 if (changed) { 3899 if (!async) { 3900 mSettings.writeLPr(); 3901 } else { 3902 scheduleWriteSettingsLocked(); 3903 } 3904 } 3905 return added; 3906 } 3907 3908 @Override 3909 public boolean addPermission(PermissionInfo info) { 3910 synchronized (mPackages) { 3911 return addPermissionLocked(info, false); 3912 } 3913 } 3914 3915 @Override 3916 public boolean addPermissionAsync(PermissionInfo info) { 3917 synchronized (mPackages) { 3918 return addPermissionLocked(info, true); 3919 } 3920 } 3921 3922 @Override 3923 public void removePermission(String name) { 3924 synchronized (mPackages) { 3925 checkPermissionTreeLP(name); 3926 BasePermission bp = mSettings.mPermissions.get(name); 3927 if (bp != null) { 3928 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3929 throw new SecurityException( 3930 "Not allowed to modify non-dynamic permission " 3931 + name); 3932 } 3933 mSettings.mPermissions.remove(name); 3934 mSettings.writeLPr(); 3935 } 3936 } 3937 } 3938 3939 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 3940 BasePermission bp) { 3941 int index = pkg.requestedPermissions.indexOf(bp.name); 3942 if (index == -1) { 3943 throw new SecurityException("Package " + pkg.packageName 3944 + " has not requested permission " + bp.name); 3945 } 3946 if (!bp.isRuntime() && !bp.isDevelopment()) { 3947 throw new SecurityException("Permission " + bp.name 3948 + " is not a changeable permission type"); 3949 } 3950 } 3951 3952 @Override 3953 public void grantRuntimePermission(String packageName, String name, final int userId) { 3954 if (!sUserManager.exists(userId)) { 3955 Log.e(TAG, "No such user:" + userId); 3956 return; 3957 } 3958 3959 mContext.enforceCallingOrSelfPermission( 3960 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 3961 "grantRuntimePermission"); 3962 3963 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3964 true /* requireFullPermission */, true /* checkShell */, 3965 "grantRuntimePermission"); 3966 3967 final int uid; 3968 final SettingBase sb; 3969 3970 synchronized (mPackages) { 3971 final PackageParser.Package pkg = mPackages.get(packageName); 3972 if (pkg == null) { 3973 throw new IllegalArgumentException("Unknown package: " + packageName); 3974 } 3975 3976 final BasePermission bp = mSettings.mPermissions.get(name); 3977 if (bp == null) { 3978 throw new IllegalArgumentException("Unknown permission: " + name); 3979 } 3980 3981 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3982 3983 // If a permission review is required for legacy apps we represent 3984 // their permissions as always granted runtime ones since we need 3985 // to keep the review required permission flag per user while an 3986 // install permission's state is shared across all users. 3987 if (Build.PERMISSIONS_REVIEW_REQUIRED 3988 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 3989 && bp.isRuntime()) { 3990 return; 3991 } 3992 3993 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3994 sb = (SettingBase) pkg.mExtras; 3995 if (sb == null) { 3996 throw new IllegalArgumentException("Unknown package: " + packageName); 3997 } 3998 3999 final PermissionsState permissionsState = sb.getPermissionsState(); 4000 4001 final int flags = permissionsState.getPermissionFlags(name, userId); 4002 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4003 throw new SecurityException("Cannot grant system fixed permission " 4004 + name + " for package " + packageName); 4005 } 4006 4007 if (bp.isDevelopment()) { 4008 // Development permissions must be handled specially, since they are not 4009 // normal runtime permissions. For now they apply to all users. 4010 if (permissionsState.grantInstallPermission(bp) != 4011 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4012 scheduleWriteSettingsLocked(); 4013 } 4014 return; 4015 } 4016 4017 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4018 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4019 return; 4020 } 4021 4022 final int result = permissionsState.grantRuntimePermission(bp, userId); 4023 switch (result) { 4024 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4025 return; 4026 } 4027 4028 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4029 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4030 mHandler.post(new Runnable() { 4031 @Override 4032 public void run() { 4033 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4034 } 4035 }); 4036 } 4037 break; 4038 } 4039 4040 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4041 4042 // Not critical if that is lost - app has to request again. 4043 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4044 } 4045 4046 // Only need to do this if user is initialized. Otherwise it's a new user 4047 // and there are no processes running as the user yet and there's no need 4048 // to make an expensive call to remount processes for the changed permissions. 4049 if (READ_EXTERNAL_STORAGE.equals(name) 4050 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4051 final long token = Binder.clearCallingIdentity(); 4052 try { 4053 if (sUserManager.isInitialized(userId)) { 4054 MountServiceInternal mountServiceInternal = LocalServices.getService( 4055 MountServiceInternal.class); 4056 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 4057 } 4058 } finally { 4059 Binder.restoreCallingIdentity(token); 4060 } 4061 } 4062 } 4063 4064 @Override 4065 public void revokeRuntimePermission(String packageName, String name, int userId) { 4066 if (!sUserManager.exists(userId)) { 4067 Log.e(TAG, "No such user:" + userId); 4068 return; 4069 } 4070 4071 mContext.enforceCallingOrSelfPermission( 4072 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4073 "revokeRuntimePermission"); 4074 4075 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4076 true /* requireFullPermission */, true /* checkShell */, 4077 "revokeRuntimePermission"); 4078 4079 final int appId; 4080 4081 synchronized (mPackages) { 4082 final PackageParser.Package pkg = mPackages.get(packageName); 4083 if (pkg == null) { 4084 throw new IllegalArgumentException("Unknown package: " + packageName); 4085 } 4086 4087 final BasePermission bp = mSettings.mPermissions.get(name); 4088 if (bp == null) { 4089 throw new IllegalArgumentException("Unknown permission: " + name); 4090 } 4091 4092 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4093 4094 // If a permission review is required for legacy apps we represent 4095 // their permissions as always granted runtime ones since we need 4096 // to keep the review required permission flag per user while an 4097 // install permission's state is shared across all users. 4098 if (Build.PERMISSIONS_REVIEW_REQUIRED 4099 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4100 && bp.isRuntime()) { 4101 return; 4102 } 4103 4104 SettingBase 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 revoke 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.revokeInstallPermission(bp) != 4121 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4122 scheduleWriteSettingsLocked(); 4123 } 4124 return; 4125 } 4126 4127 if (permissionsState.revokeRuntimePermission(bp, userId) == 4128 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4129 return; 4130 } 4131 4132 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4133 4134 // Critical, after this call app should never have the permission. 4135 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4136 4137 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4138 } 4139 4140 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4141 } 4142 4143 @Override 4144 public void resetRuntimePermissions() { 4145 mContext.enforceCallingOrSelfPermission( 4146 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4147 "revokeRuntimePermission"); 4148 4149 int callingUid = Binder.getCallingUid(); 4150 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4151 mContext.enforceCallingOrSelfPermission( 4152 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4153 "resetRuntimePermissions"); 4154 } 4155 4156 synchronized (mPackages) { 4157 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4158 for (int userId : UserManagerService.getInstance().getUserIds()) { 4159 final int packageCount = mPackages.size(); 4160 for (int i = 0; i < packageCount; i++) { 4161 PackageParser.Package pkg = mPackages.valueAt(i); 4162 if (!(pkg.mExtras instanceof PackageSetting)) { 4163 continue; 4164 } 4165 PackageSetting ps = (PackageSetting) pkg.mExtras; 4166 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4167 } 4168 } 4169 } 4170 } 4171 4172 @Override 4173 public int getPermissionFlags(String name, String packageName, int userId) { 4174 if (!sUserManager.exists(userId)) { 4175 return 0; 4176 } 4177 4178 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4179 4180 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4181 true /* requireFullPermission */, false /* checkShell */, 4182 "getPermissionFlags"); 4183 4184 synchronized (mPackages) { 4185 final PackageParser.Package pkg = mPackages.get(packageName); 4186 if (pkg == null) { 4187 throw new IllegalArgumentException("Unknown package: " + packageName); 4188 } 4189 4190 final BasePermission bp = mSettings.mPermissions.get(name); 4191 if (bp == null) { 4192 throw new IllegalArgumentException("Unknown permission: " + name); 4193 } 4194 4195 SettingBase sb = (SettingBase) pkg.mExtras; 4196 if (sb == null) { 4197 throw new IllegalArgumentException("Unknown package: " + packageName); 4198 } 4199 4200 PermissionsState permissionsState = sb.getPermissionsState(); 4201 return permissionsState.getPermissionFlags(name, userId); 4202 } 4203 } 4204 4205 @Override 4206 public void updatePermissionFlags(String name, String packageName, int flagMask, 4207 int flagValues, int userId) { 4208 if (!sUserManager.exists(userId)) { 4209 return; 4210 } 4211 4212 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4213 4214 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4215 true /* requireFullPermission */, true /* checkShell */, 4216 "updatePermissionFlags"); 4217 4218 // Only the system can change these flags and nothing else. 4219 if (getCallingUid() != Process.SYSTEM_UID) { 4220 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4221 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4222 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4223 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4224 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4225 } 4226 4227 synchronized (mPackages) { 4228 final PackageParser.Package pkg = mPackages.get(packageName); 4229 if (pkg == null) { 4230 throw new IllegalArgumentException("Unknown package: " + packageName); 4231 } 4232 4233 final BasePermission bp = mSettings.mPermissions.get(name); 4234 if (bp == null) { 4235 throw new IllegalArgumentException("Unknown permission: " + name); 4236 } 4237 4238 SettingBase sb = (SettingBase) pkg.mExtras; 4239 if (sb == null) { 4240 throw new IllegalArgumentException("Unknown package: " + packageName); 4241 } 4242 4243 PermissionsState permissionsState = sb.getPermissionsState(); 4244 4245 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4246 4247 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4248 // Install and runtime permissions are stored in different places, 4249 // so figure out what permission changed and persist the change. 4250 if (permissionsState.getInstallPermissionState(name) != null) { 4251 scheduleWriteSettingsLocked(); 4252 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4253 || hadState) { 4254 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4255 } 4256 } 4257 } 4258 } 4259 4260 /** 4261 * Update the permission flags for all packages and runtime permissions of a user in order 4262 * to allow device or profile owner to remove POLICY_FIXED. 4263 */ 4264 @Override 4265 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4266 if (!sUserManager.exists(userId)) { 4267 return; 4268 } 4269 4270 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4271 4272 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4273 true /* requireFullPermission */, true /* checkShell */, 4274 "updatePermissionFlagsForAllApps"); 4275 4276 // Only the system can change system fixed flags. 4277 if (getCallingUid() != Process.SYSTEM_UID) { 4278 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4279 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4280 } 4281 4282 synchronized (mPackages) { 4283 boolean changed = false; 4284 final int packageCount = mPackages.size(); 4285 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4286 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4287 SettingBase sb = (SettingBase) pkg.mExtras; 4288 if (sb == null) { 4289 continue; 4290 } 4291 PermissionsState permissionsState = sb.getPermissionsState(); 4292 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4293 userId, flagMask, flagValues); 4294 } 4295 if (changed) { 4296 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4297 } 4298 } 4299 } 4300 4301 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4302 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4303 != PackageManager.PERMISSION_GRANTED 4304 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4305 != PackageManager.PERMISSION_GRANTED) { 4306 throw new SecurityException(message + " requires " 4307 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4308 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4309 } 4310 } 4311 4312 @Override 4313 public boolean shouldShowRequestPermissionRationale(String permissionName, 4314 String packageName, int userId) { 4315 if (UserHandle.getCallingUserId() != userId) { 4316 mContext.enforceCallingPermission( 4317 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4318 "canShowRequestPermissionRationale for user " + userId); 4319 } 4320 4321 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4322 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4323 return false; 4324 } 4325 4326 if (checkPermission(permissionName, packageName, userId) 4327 == PackageManager.PERMISSION_GRANTED) { 4328 return false; 4329 } 4330 4331 final int flags; 4332 4333 final long identity = Binder.clearCallingIdentity(); 4334 try { 4335 flags = getPermissionFlags(permissionName, 4336 packageName, userId); 4337 } finally { 4338 Binder.restoreCallingIdentity(identity); 4339 } 4340 4341 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4342 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4343 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4344 4345 if ((flags & fixedFlags) != 0) { 4346 return false; 4347 } 4348 4349 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4350 } 4351 4352 @Override 4353 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4354 mContext.enforceCallingOrSelfPermission( 4355 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4356 "addOnPermissionsChangeListener"); 4357 4358 synchronized (mPackages) { 4359 mOnPermissionChangeListeners.addListenerLocked(listener); 4360 } 4361 } 4362 4363 @Override 4364 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4365 synchronized (mPackages) { 4366 mOnPermissionChangeListeners.removeListenerLocked(listener); 4367 } 4368 } 4369 4370 @Override 4371 public boolean isProtectedBroadcast(String actionName) { 4372 synchronized (mPackages) { 4373 if (mProtectedBroadcasts.contains(actionName)) { 4374 return true; 4375 } else if (actionName != null) { 4376 // TODO: remove these terrible hacks 4377 if (actionName.startsWith("android.net.netmon.lingerExpired") 4378 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4379 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 4380 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 4381 return true; 4382 } 4383 } 4384 } 4385 return false; 4386 } 4387 4388 @Override 4389 public int checkSignatures(String pkg1, String pkg2) { 4390 synchronized (mPackages) { 4391 final PackageParser.Package p1 = mPackages.get(pkg1); 4392 final PackageParser.Package p2 = mPackages.get(pkg2); 4393 if (p1 == null || p1.mExtras == null 4394 || p2 == null || p2.mExtras == null) { 4395 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4396 } 4397 return compareSignatures(p1.mSignatures, p2.mSignatures); 4398 } 4399 } 4400 4401 @Override 4402 public int checkUidSignatures(int uid1, int uid2) { 4403 // Map to base uids. 4404 uid1 = UserHandle.getAppId(uid1); 4405 uid2 = UserHandle.getAppId(uid2); 4406 // reader 4407 synchronized (mPackages) { 4408 Signature[] s1; 4409 Signature[] s2; 4410 Object obj = mSettings.getUserIdLPr(uid1); 4411 if (obj != null) { 4412 if (obj instanceof SharedUserSetting) { 4413 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4414 } else if (obj instanceof PackageSetting) { 4415 s1 = ((PackageSetting)obj).signatures.mSignatures; 4416 } else { 4417 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4418 } 4419 } else { 4420 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4421 } 4422 obj = mSettings.getUserIdLPr(uid2); 4423 if (obj != null) { 4424 if (obj instanceof SharedUserSetting) { 4425 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4426 } else if (obj instanceof PackageSetting) { 4427 s2 = ((PackageSetting)obj).signatures.mSignatures; 4428 } else { 4429 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4430 } 4431 } else { 4432 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4433 } 4434 return compareSignatures(s1, s2); 4435 } 4436 } 4437 4438 /** 4439 * This method should typically only be used when granting or revoking 4440 * permissions, since the app may immediately restart after this call. 4441 * <p> 4442 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 4443 * guard your work against the app being relaunched. 4444 */ 4445 private void killUid(int appId, int userId, String reason) { 4446 final long identity = Binder.clearCallingIdentity(); 4447 try { 4448 IActivityManager am = ActivityManagerNative.getDefault(); 4449 if (am != null) { 4450 try { 4451 am.killUid(appId, userId, reason); 4452 } catch (RemoteException e) { 4453 /* ignore - same process */ 4454 } 4455 } 4456 } finally { 4457 Binder.restoreCallingIdentity(identity); 4458 } 4459 } 4460 4461 /** 4462 * Compares two sets of signatures. Returns: 4463 * <br /> 4464 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4465 * <br /> 4466 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4467 * <br /> 4468 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4469 * <br /> 4470 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4471 * <br /> 4472 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4473 */ 4474 static int compareSignatures(Signature[] s1, Signature[] s2) { 4475 if (s1 == null) { 4476 return s2 == null 4477 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4478 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4479 } 4480 4481 if (s2 == null) { 4482 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4483 } 4484 4485 if (s1.length != s2.length) { 4486 return PackageManager.SIGNATURE_NO_MATCH; 4487 } 4488 4489 // Since both signature sets are of size 1, we can compare without HashSets. 4490 if (s1.length == 1) { 4491 return s1[0].equals(s2[0]) ? 4492 PackageManager.SIGNATURE_MATCH : 4493 PackageManager.SIGNATURE_NO_MATCH; 4494 } 4495 4496 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4497 for (Signature sig : s1) { 4498 set1.add(sig); 4499 } 4500 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4501 for (Signature sig : s2) { 4502 set2.add(sig); 4503 } 4504 // Make sure s2 contains all signatures in s1. 4505 if (set1.equals(set2)) { 4506 return PackageManager.SIGNATURE_MATCH; 4507 } 4508 return PackageManager.SIGNATURE_NO_MATCH; 4509 } 4510 4511 /** 4512 * If the database version for this type of package (internal storage or 4513 * external storage) is less than the version where package signatures 4514 * were updated, return true. 4515 */ 4516 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4517 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4518 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4519 } 4520 4521 /** 4522 * Used for backward compatibility to make sure any packages with 4523 * certificate chains get upgraded to the new style. {@code existingSigs} 4524 * will be in the old format (since they were stored on disk from before the 4525 * system upgrade) and {@code scannedSigs} will be in the newer format. 4526 */ 4527 private int compareSignaturesCompat(PackageSignatures existingSigs, 4528 PackageParser.Package scannedPkg) { 4529 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4530 return PackageManager.SIGNATURE_NO_MATCH; 4531 } 4532 4533 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4534 for (Signature sig : existingSigs.mSignatures) { 4535 existingSet.add(sig); 4536 } 4537 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4538 for (Signature sig : scannedPkg.mSignatures) { 4539 try { 4540 Signature[] chainSignatures = sig.getChainSignatures(); 4541 for (Signature chainSig : chainSignatures) { 4542 scannedCompatSet.add(chainSig); 4543 } 4544 } catch (CertificateEncodingException e) { 4545 scannedCompatSet.add(sig); 4546 } 4547 } 4548 /* 4549 * Make sure the expanded scanned set contains all signatures in the 4550 * existing one. 4551 */ 4552 if (scannedCompatSet.equals(existingSet)) { 4553 // Migrate the old signatures to the new scheme. 4554 existingSigs.assignSignatures(scannedPkg.mSignatures); 4555 // The new KeySets will be re-added later in the scanning process. 4556 synchronized (mPackages) { 4557 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4558 } 4559 return PackageManager.SIGNATURE_MATCH; 4560 } 4561 return PackageManager.SIGNATURE_NO_MATCH; 4562 } 4563 4564 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4565 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4566 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4567 } 4568 4569 private int compareSignaturesRecover(PackageSignatures existingSigs, 4570 PackageParser.Package scannedPkg) { 4571 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4572 return PackageManager.SIGNATURE_NO_MATCH; 4573 } 4574 4575 String msg = null; 4576 try { 4577 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4578 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4579 + scannedPkg.packageName); 4580 return PackageManager.SIGNATURE_MATCH; 4581 } 4582 } catch (CertificateException e) { 4583 msg = e.getMessage(); 4584 } 4585 4586 logCriticalInfo(Log.INFO, 4587 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4588 return PackageManager.SIGNATURE_NO_MATCH; 4589 } 4590 4591 @Override 4592 public List<String> getAllPackages() { 4593 synchronized (mPackages) { 4594 return new ArrayList<String>(mPackages.keySet()); 4595 } 4596 } 4597 4598 @Override 4599 public String[] getPackagesForUid(int uid) { 4600 uid = UserHandle.getAppId(uid); 4601 // reader 4602 synchronized (mPackages) { 4603 Object obj = mSettings.getUserIdLPr(uid); 4604 if (obj instanceof SharedUserSetting) { 4605 final SharedUserSetting sus = (SharedUserSetting) obj; 4606 final int N = sus.packages.size(); 4607 final String[] res = new String[N]; 4608 final Iterator<PackageSetting> it = sus.packages.iterator(); 4609 int i = 0; 4610 while (it.hasNext()) { 4611 res[i++] = it.next().name; 4612 } 4613 return res; 4614 } else if (obj instanceof PackageSetting) { 4615 final PackageSetting ps = (PackageSetting) obj; 4616 return new String[] { ps.name }; 4617 } 4618 } 4619 return null; 4620 } 4621 4622 @Override 4623 public String getNameForUid(int uid) { 4624 // reader 4625 synchronized (mPackages) { 4626 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4627 if (obj instanceof SharedUserSetting) { 4628 final SharedUserSetting sus = (SharedUserSetting) obj; 4629 return sus.name + ":" + sus.userId; 4630 } else if (obj instanceof PackageSetting) { 4631 final PackageSetting ps = (PackageSetting) obj; 4632 return ps.name; 4633 } 4634 } 4635 return null; 4636 } 4637 4638 @Override 4639 public int getUidForSharedUser(String sharedUserName) { 4640 if(sharedUserName == null) { 4641 return -1; 4642 } 4643 // reader 4644 synchronized (mPackages) { 4645 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4646 if (suid == null) { 4647 return -1; 4648 } 4649 return suid.userId; 4650 } 4651 } 4652 4653 @Override 4654 public int getFlagsForUid(int uid) { 4655 synchronized (mPackages) { 4656 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4657 if (obj instanceof SharedUserSetting) { 4658 final SharedUserSetting sus = (SharedUserSetting) obj; 4659 return sus.pkgFlags; 4660 } else if (obj instanceof PackageSetting) { 4661 final PackageSetting ps = (PackageSetting) obj; 4662 return ps.pkgFlags; 4663 } 4664 } 4665 return 0; 4666 } 4667 4668 @Override 4669 public int getPrivateFlagsForUid(int uid) { 4670 synchronized (mPackages) { 4671 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4672 if (obj instanceof SharedUserSetting) { 4673 final SharedUserSetting sus = (SharedUserSetting) obj; 4674 return sus.pkgPrivateFlags; 4675 } else if (obj instanceof PackageSetting) { 4676 final PackageSetting ps = (PackageSetting) obj; 4677 return ps.pkgPrivateFlags; 4678 } 4679 } 4680 return 0; 4681 } 4682 4683 @Override 4684 public boolean isUidPrivileged(int uid) { 4685 uid = UserHandle.getAppId(uid); 4686 // reader 4687 synchronized (mPackages) { 4688 Object obj = mSettings.getUserIdLPr(uid); 4689 if (obj instanceof SharedUserSetting) { 4690 final SharedUserSetting sus = (SharedUserSetting) obj; 4691 final Iterator<PackageSetting> it = sus.packages.iterator(); 4692 while (it.hasNext()) { 4693 if (it.next().isPrivileged()) { 4694 return true; 4695 } 4696 } 4697 } else if (obj instanceof PackageSetting) { 4698 final PackageSetting ps = (PackageSetting) obj; 4699 return ps.isPrivileged(); 4700 } 4701 } 4702 return false; 4703 } 4704 4705 @Override 4706 public String[] getAppOpPermissionPackages(String permissionName) { 4707 synchronized (mPackages) { 4708 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4709 if (pkgs == null) { 4710 return null; 4711 } 4712 return pkgs.toArray(new String[pkgs.size()]); 4713 } 4714 } 4715 4716 @Override 4717 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4718 int flags, int userId) { 4719 try { 4720 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 4721 4722 if (!sUserManager.exists(userId)) return null; 4723 flags = updateFlagsForResolve(flags, userId, intent); 4724 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4725 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 4726 4727 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 4728 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 4729 flags, userId); 4730 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4731 4732 final ResolveInfo bestChoice = 4733 chooseBestActivity(intent, resolvedType, flags, query, userId); 4734 4735 if (isEphemeralAllowed(intent, query, userId)) { 4736 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 4737 final EphemeralResolveInfo ai = 4738 getEphemeralResolveInfo(intent, resolvedType, userId); 4739 if (ai != null) { 4740 if (DEBUG_EPHEMERAL) { 4741 Slog.v(TAG, "Returning an EphemeralResolveInfo"); 4742 } 4743 bestChoice.ephemeralInstaller = mEphemeralInstallerInfo; 4744 bestChoice.ephemeralResolveInfo = ai; 4745 } 4746 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4747 } 4748 return bestChoice; 4749 } finally { 4750 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4751 } 4752 } 4753 4754 @Override 4755 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4756 IntentFilter filter, int match, ComponentName activity) { 4757 final int userId = UserHandle.getCallingUserId(); 4758 if (DEBUG_PREFERRED) { 4759 Log.v(TAG, "setLastChosenActivity intent=" + intent 4760 + " resolvedType=" + resolvedType 4761 + " flags=" + flags 4762 + " filter=" + filter 4763 + " match=" + match 4764 + " activity=" + activity); 4765 filter.dump(new PrintStreamPrinter(System.out), " "); 4766 } 4767 intent.setComponent(null); 4768 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4769 userId); 4770 // Find any earlier preferred or last chosen entries and nuke them 4771 findPreferredActivity(intent, resolvedType, 4772 flags, query, 0, false, true, false, userId); 4773 // Add the new activity as the last chosen for this filter 4774 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4775 "Setting last chosen"); 4776 } 4777 4778 @Override 4779 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4780 final int userId = UserHandle.getCallingUserId(); 4781 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4782 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4783 userId); 4784 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4785 false, false, false, userId); 4786 } 4787 4788 4789 private boolean isEphemeralAllowed( 4790 Intent intent, List<ResolveInfo> resolvedActivites, int userId) { 4791 // Short circuit and return early if possible. 4792 if (DISABLE_EPHEMERAL_APPS) { 4793 return false; 4794 } 4795 final int callingUser = UserHandle.getCallingUserId(); 4796 if (callingUser != UserHandle.USER_SYSTEM) { 4797 return false; 4798 } 4799 if (mEphemeralResolverConnection == null) { 4800 return false; 4801 } 4802 if (intent.getComponent() != null) { 4803 return false; 4804 } 4805 if (intent.getPackage() != null) { 4806 return false; 4807 } 4808 final boolean isWebUri = hasWebURI(intent); 4809 if (!isWebUri) { 4810 return false; 4811 } 4812 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4813 synchronized (mPackages) { 4814 final int count = resolvedActivites.size(); 4815 for (int n = 0; n < count; n++) { 4816 ResolveInfo info = resolvedActivites.get(n); 4817 String packageName = info.activityInfo.packageName; 4818 PackageSetting ps = mSettings.mPackages.get(packageName); 4819 if (ps != null) { 4820 // Try to get the status from User settings first 4821 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4822 int status = (int) (packedStatus >> 32); 4823 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4824 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4825 if (DEBUG_EPHEMERAL) { 4826 Slog.v(TAG, "DENY ephemeral apps;" 4827 + " pkg: " + packageName + ", status: " + status); 4828 } 4829 return false; 4830 } 4831 } 4832 } 4833 } 4834 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4835 return true; 4836 } 4837 4838 private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType, 4839 int userId) { 4840 MessageDigest digest = null; 4841 try { 4842 digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM); 4843 } catch (NoSuchAlgorithmException e) { 4844 // If we can't create a digest, ignore ephemeral apps. 4845 return null; 4846 } 4847 4848 final byte[] hostBytes = intent.getData().getHost().getBytes(); 4849 final byte[] digestBytes = digest.digest(hostBytes); 4850 int shaPrefix = 4851 digestBytes[0] << 24 4852 | digestBytes[1] << 16 4853 | digestBytes[2] << 8 4854 | digestBytes[3] << 0; 4855 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4856 mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix); 4857 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4858 // No hash prefix match; there are no ephemeral apps for this domain. 4859 return null; 4860 } 4861 for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) { 4862 EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i); 4863 if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) { 4864 continue; 4865 } 4866 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 4867 // No filters; this should never happen. 4868 if (filters.isEmpty()) { 4869 continue; 4870 } 4871 // We have a domain match; resolve the filters to see if anything matches. 4872 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4873 for (int j = filters.size() - 1; j >= 0; --j) { 4874 final EphemeralResolveIntentInfo intentInfo = 4875 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 4876 ephemeralResolver.addFilter(intentInfo); 4877 } 4878 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 4879 intent, resolvedType, false /*defaultOnly*/, userId); 4880 if (!matchedResolveInfoList.isEmpty()) { 4881 return matchedResolveInfoList.get(0); 4882 } 4883 } 4884 // Hash or filter mis-match; no ephemeral apps for this domain. 4885 return null; 4886 } 4887 4888 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4889 int flags, List<ResolveInfo> query, int userId) { 4890 if (query != null) { 4891 final int N = query.size(); 4892 if (N == 1) { 4893 return query.get(0); 4894 } else if (N > 1) { 4895 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4896 // If there is more than one activity with the same priority, 4897 // then let the user decide between them. 4898 ResolveInfo r0 = query.get(0); 4899 ResolveInfo r1 = query.get(1); 4900 if (DEBUG_INTENT_MATCHING || debug) { 4901 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4902 + r1.activityInfo.name + "=" + r1.priority); 4903 } 4904 // If the first activity has a higher priority, or a different 4905 // default, then it is always desirable to pick it. 4906 if (r0.priority != r1.priority 4907 || r0.preferredOrder != r1.preferredOrder 4908 || r0.isDefault != r1.isDefault) { 4909 return query.get(0); 4910 } 4911 // If we have saved a preference for a preferred activity for 4912 // this Intent, use that. 4913 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4914 flags, query, r0.priority, true, false, debug, userId); 4915 if (ri != null) { 4916 return ri; 4917 } 4918 ri = new ResolveInfo(mResolveInfo); 4919 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4920 ri.activityInfo.applicationInfo = new ApplicationInfo( 4921 ri.activityInfo.applicationInfo); 4922 if (userId != 0) { 4923 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4924 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4925 } 4926 // Make sure that the resolver is displayable in car mode 4927 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 4928 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 4929 return ri; 4930 } 4931 } 4932 return null; 4933 } 4934 4935 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4936 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4937 final int N = query.size(); 4938 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4939 .get(userId); 4940 // Get the list of persistent preferred activities that handle the intent 4941 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4942 List<PersistentPreferredActivity> pprefs = ppir != null 4943 ? ppir.queryIntent(intent, resolvedType, 4944 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4945 : null; 4946 if (pprefs != null && pprefs.size() > 0) { 4947 final int M = pprefs.size(); 4948 for (int i=0; i<M; i++) { 4949 final PersistentPreferredActivity ppa = pprefs.get(i); 4950 if (DEBUG_PREFERRED || debug) { 4951 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4952 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4953 + "\n component=" + ppa.mComponent); 4954 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4955 } 4956 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4957 flags | MATCH_DISABLED_COMPONENTS, userId); 4958 if (DEBUG_PREFERRED || debug) { 4959 Slog.v(TAG, "Found persistent preferred activity:"); 4960 if (ai != null) { 4961 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4962 } else { 4963 Slog.v(TAG, " null"); 4964 } 4965 } 4966 if (ai == null) { 4967 // This previously registered persistent preferred activity 4968 // component is no longer known. Ignore it and do NOT remove it. 4969 continue; 4970 } 4971 for (int j=0; j<N; j++) { 4972 final ResolveInfo ri = query.get(j); 4973 if (!ri.activityInfo.applicationInfo.packageName 4974 .equals(ai.applicationInfo.packageName)) { 4975 continue; 4976 } 4977 if (!ri.activityInfo.name.equals(ai.name)) { 4978 continue; 4979 } 4980 // Found a persistent preference that can handle the intent. 4981 if (DEBUG_PREFERRED || debug) { 4982 Slog.v(TAG, "Returning persistent preferred activity: " + 4983 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4984 } 4985 return ri; 4986 } 4987 } 4988 } 4989 return null; 4990 } 4991 4992 // TODO: handle preferred activities missing while user has amnesia 4993 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4994 List<ResolveInfo> query, int priority, boolean always, 4995 boolean removeMatches, boolean debug, int userId) { 4996 if (!sUserManager.exists(userId)) return null; 4997 flags = updateFlagsForResolve(flags, userId, intent); 4998 // writer 4999 synchronized (mPackages) { 5000 if (intent.getSelector() != null) { 5001 intent = intent.getSelector(); 5002 } 5003 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 5004 5005 // Try to find a matching persistent preferred activity. 5006 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5007 debug, userId); 5008 5009 // If a persistent preferred activity matched, use it. 5010 if (pri != null) { 5011 return pri; 5012 } 5013 5014 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5015 // Get the list of preferred activities that handle the intent 5016 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5017 List<PreferredActivity> prefs = pir != null 5018 ? pir.queryIntent(intent, resolvedType, 5019 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5020 : null; 5021 if (prefs != null && prefs.size() > 0) { 5022 boolean changed = false; 5023 try { 5024 // First figure out how good the original match set is. 5025 // We will only allow preferred activities that came 5026 // from the same match quality. 5027 int match = 0; 5028 5029 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5030 5031 final int N = query.size(); 5032 for (int j=0; j<N; j++) { 5033 final ResolveInfo ri = query.get(j); 5034 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5035 + ": 0x" + Integer.toHexString(match)); 5036 if (ri.match > match) { 5037 match = ri.match; 5038 } 5039 } 5040 5041 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5042 + Integer.toHexString(match)); 5043 5044 match &= IntentFilter.MATCH_CATEGORY_MASK; 5045 final int M = prefs.size(); 5046 for (int i=0; i<M; i++) { 5047 final PreferredActivity pa = prefs.get(i); 5048 if (DEBUG_PREFERRED || debug) { 5049 Slog.v(TAG, "Checking PreferredActivity ds=" 5050 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5051 + "\n component=" + pa.mPref.mComponent); 5052 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5053 } 5054 if (pa.mPref.mMatch != match) { 5055 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5056 + Integer.toHexString(pa.mPref.mMatch)); 5057 continue; 5058 } 5059 // If it's not an "always" type preferred activity and that's what we're 5060 // looking for, skip it. 5061 if (always && !pa.mPref.mAlways) { 5062 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5063 continue; 5064 } 5065 final ActivityInfo ai = getActivityInfo( 5066 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5067 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5068 userId); 5069 if (DEBUG_PREFERRED || debug) { 5070 Slog.v(TAG, "Found preferred activity:"); 5071 if (ai != null) { 5072 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5073 } else { 5074 Slog.v(TAG, " null"); 5075 } 5076 } 5077 if (ai == null) { 5078 // This previously registered preferred activity 5079 // component is no longer known. Most likely an update 5080 // to the app was installed and in the new version this 5081 // component no longer exists. Clean it up by removing 5082 // it from the preferred activities list, and skip it. 5083 Slog.w(TAG, "Removing dangling preferred activity: " 5084 + pa.mPref.mComponent); 5085 pir.removeFilter(pa); 5086 changed = true; 5087 continue; 5088 } 5089 for (int j=0; j<N; j++) { 5090 final ResolveInfo ri = query.get(j); 5091 if (!ri.activityInfo.applicationInfo.packageName 5092 .equals(ai.applicationInfo.packageName)) { 5093 continue; 5094 } 5095 if (!ri.activityInfo.name.equals(ai.name)) { 5096 continue; 5097 } 5098 5099 if (removeMatches) { 5100 pir.removeFilter(pa); 5101 changed = true; 5102 if (DEBUG_PREFERRED) { 5103 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 5104 } 5105 break; 5106 } 5107 5108 // Okay we found a previously set preferred or last chosen app. 5109 // If the result set is different from when this 5110 // was created, we need to clear it and re-ask the 5111 // user their preference, if we're looking for an "always" type entry. 5112 if (always && !pa.mPref.sameSet(query)) { 5113 Slog.i(TAG, "Result set changed, dropping preferred activity for " 5114 + intent + " type " + resolvedType); 5115 if (DEBUG_PREFERRED) { 5116 Slog.v(TAG, "Removing preferred activity since set changed " 5117 + pa.mPref.mComponent); 5118 } 5119 pir.removeFilter(pa); 5120 // Re-add the filter as a "last chosen" entry (!always) 5121 PreferredActivity lastChosen = new PreferredActivity( 5122 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5123 pir.addFilter(lastChosen); 5124 changed = true; 5125 return null; 5126 } 5127 5128 // Yay! Either the set matched or we're looking for the last chosen 5129 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5130 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5131 return ri; 5132 } 5133 } 5134 } finally { 5135 if (changed) { 5136 if (DEBUG_PREFERRED) { 5137 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5138 } 5139 scheduleWritePackageRestrictionsLocked(userId); 5140 } 5141 } 5142 } 5143 } 5144 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5145 return null; 5146 } 5147 5148 /* 5149 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5150 */ 5151 @Override 5152 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5153 int targetUserId) { 5154 mContext.enforceCallingOrSelfPermission( 5155 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5156 List<CrossProfileIntentFilter> matches = 5157 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5158 if (matches != null) { 5159 int size = matches.size(); 5160 for (int i = 0; i < size; i++) { 5161 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5162 } 5163 } 5164 if (hasWebURI(intent)) { 5165 // cross-profile app linking works only towards the parent. 5166 final UserInfo parent = getProfileParent(sourceUserId); 5167 synchronized(mPackages) { 5168 int flags = updateFlagsForResolve(0, parent.id, intent); 5169 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5170 intent, resolvedType, flags, sourceUserId, parent.id); 5171 return xpDomainInfo != null; 5172 } 5173 } 5174 return false; 5175 } 5176 5177 private UserInfo getProfileParent(int userId) { 5178 final long identity = Binder.clearCallingIdentity(); 5179 try { 5180 return sUserManager.getProfileParent(userId); 5181 } finally { 5182 Binder.restoreCallingIdentity(identity); 5183 } 5184 } 5185 5186 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5187 String resolvedType, int userId) { 5188 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5189 if (resolver != null) { 5190 return resolver.queryIntent(intent, resolvedType, false, userId); 5191 } 5192 return null; 5193 } 5194 5195 @Override 5196 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5197 String resolvedType, int flags, int userId) { 5198 try { 5199 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5200 5201 return new ParceledListSlice<>( 5202 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5203 } finally { 5204 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5205 } 5206 } 5207 5208 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5209 String resolvedType, int flags, int userId) { 5210 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5211 flags = updateFlagsForResolve(flags, userId, intent); 5212 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5213 false /* requireFullPermission */, false /* checkShell */, 5214 "query intent activities"); 5215 ComponentName comp = intent.getComponent(); 5216 if (comp == null) { 5217 if (intent.getSelector() != null) { 5218 intent = intent.getSelector(); 5219 comp = intent.getComponent(); 5220 } 5221 } 5222 5223 if (comp != null) { 5224 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5225 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5226 if (ai != null) { 5227 final ResolveInfo ri = new ResolveInfo(); 5228 ri.activityInfo = ai; 5229 list.add(ri); 5230 } 5231 return list; 5232 } 5233 5234 // reader 5235 synchronized (mPackages) { 5236 final String pkgName = intent.getPackage(); 5237 if (pkgName == null) { 5238 List<CrossProfileIntentFilter> matchingFilters = 5239 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5240 // Check for results that need to skip the current profile. 5241 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5242 resolvedType, flags, userId); 5243 if (xpResolveInfo != null) { 5244 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 5245 result.add(xpResolveInfo); 5246 return filterIfNotSystemUser(result, userId); 5247 } 5248 5249 // Check for results in the current profile. 5250 List<ResolveInfo> result = mActivities.queryIntent( 5251 intent, resolvedType, flags, userId); 5252 result = filterIfNotSystemUser(result, userId); 5253 5254 // Check for cross profile results. 5255 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5256 xpResolveInfo = queryCrossProfileIntents( 5257 matchingFilters, intent, resolvedType, flags, userId, 5258 hasNonNegativePriorityResult); 5259 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5260 boolean isVisibleToUser = filterIfNotSystemUser( 5261 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5262 if (isVisibleToUser) { 5263 result.add(xpResolveInfo); 5264 Collections.sort(result, mResolvePrioritySorter); 5265 } 5266 } 5267 if (hasWebURI(intent)) { 5268 CrossProfileDomainInfo xpDomainInfo = null; 5269 final UserInfo parent = getProfileParent(userId); 5270 if (parent != null) { 5271 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5272 flags, userId, parent.id); 5273 } 5274 if (xpDomainInfo != null) { 5275 if (xpResolveInfo != null) { 5276 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5277 // in the result. 5278 result.remove(xpResolveInfo); 5279 } 5280 if (result.size() == 0) { 5281 result.add(xpDomainInfo.resolveInfo); 5282 return result; 5283 } 5284 } else if (result.size() <= 1) { 5285 return result; 5286 } 5287 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 5288 xpDomainInfo, userId); 5289 Collections.sort(result, mResolvePrioritySorter); 5290 } 5291 return result; 5292 } 5293 final PackageParser.Package pkg = mPackages.get(pkgName); 5294 if (pkg != null) { 5295 return filterIfNotSystemUser( 5296 mActivities.queryIntentForPackage( 5297 intent, resolvedType, flags, pkg.activities, userId), 5298 userId); 5299 } 5300 return new ArrayList<ResolveInfo>(); 5301 } 5302 } 5303 5304 private static class CrossProfileDomainInfo { 5305 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5306 ResolveInfo resolveInfo; 5307 /* Best domain verification status of the activities found in the other profile */ 5308 int bestDomainVerificationStatus; 5309 } 5310 5311 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5312 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5313 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5314 sourceUserId)) { 5315 return null; 5316 } 5317 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5318 resolvedType, flags, parentUserId); 5319 5320 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5321 return null; 5322 } 5323 CrossProfileDomainInfo result = null; 5324 int size = resultTargetUser.size(); 5325 for (int i = 0; i < size; i++) { 5326 ResolveInfo riTargetUser = resultTargetUser.get(i); 5327 // Intent filter verification is only for filters that specify a host. So don't return 5328 // those that handle all web uris. 5329 if (riTargetUser.handleAllWebDataURI) { 5330 continue; 5331 } 5332 String packageName = riTargetUser.activityInfo.packageName; 5333 PackageSetting ps = mSettings.mPackages.get(packageName); 5334 if (ps == null) { 5335 continue; 5336 } 5337 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5338 int status = (int)(verificationState >> 32); 5339 if (result == null) { 5340 result = new CrossProfileDomainInfo(); 5341 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5342 sourceUserId, parentUserId); 5343 result.bestDomainVerificationStatus = status; 5344 } else { 5345 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5346 result.bestDomainVerificationStatus); 5347 } 5348 } 5349 // Don't consider matches with status NEVER across profiles. 5350 if (result != null && result.bestDomainVerificationStatus 5351 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5352 return null; 5353 } 5354 return result; 5355 } 5356 5357 /** 5358 * Verification statuses are ordered from the worse to the best, except for 5359 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5360 */ 5361 private int bestDomainVerificationStatus(int status1, int status2) { 5362 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5363 return status2; 5364 } 5365 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5366 return status1; 5367 } 5368 return (int) MathUtils.max(status1, status2); 5369 } 5370 5371 private boolean isUserEnabled(int userId) { 5372 long callingId = Binder.clearCallingIdentity(); 5373 try { 5374 UserInfo userInfo = sUserManager.getUserInfo(userId); 5375 return userInfo != null && userInfo.isEnabled(); 5376 } finally { 5377 Binder.restoreCallingIdentity(callingId); 5378 } 5379 } 5380 5381 /** 5382 * Filter out activities with systemUserOnly flag set, when current user is not System. 5383 * 5384 * @return filtered list 5385 */ 5386 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5387 if (userId == UserHandle.USER_SYSTEM) { 5388 return resolveInfos; 5389 } 5390 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5391 ResolveInfo info = resolveInfos.get(i); 5392 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5393 resolveInfos.remove(i); 5394 } 5395 } 5396 return resolveInfos; 5397 } 5398 5399 /** 5400 * @param resolveInfos list of resolve infos in descending priority order 5401 * @return if the list contains a resolve info with non-negative priority 5402 */ 5403 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5404 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5405 } 5406 5407 private static boolean hasWebURI(Intent intent) { 5408 if (intent.getData() == null) { 5409 return false; 5410 } 5411 final String scheme = intent.getScheme(); 5412 if (TextUtils.isEmpty(scheme)) { 5413 return false; 5414 } 5415 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5416 } 5417 5418 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5419 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5420 int userId) { 5421 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5422 5423 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5424 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5425 candidates.size()); 5426 } 5427 5428 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5429 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5430 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5431 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5432 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5433 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5434 5435 synchronized (mPackages) { 5436 final int count = candidates.size(); 5437 // First, try to use linked apps. Partition the candidates into four lists: 5438 // one for the final results, one for the "do not use ever", one for "undefined status" 5439 // and finally one for "browser app type". 5440 for (int n=0; n<count; n++) { 5441 ResolveInfo info = candidates.get(n); 5442 String packageName = info.activityInfo.packageName; 5443 PackageSetting ps = mSettings.mPackages.get(packageName); 5444 if (ps != null) { 5445 // Add to the special match all list (Browser use case) 5446 if (info.handleAllWebDataURI) { 5447 matchAllList.add(info); 5448 continue; 5449 } 5450 // Try to get the status from User settings first 5451 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5452 int status = (int)(packedStatus >> 32); 5453 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5454 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5455 if (DEBUG_DOMAIN_VERIFICATION) { 5456 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5457 + " : linkgen=" + linkGeneration); 5458 } 5459 // Use link-enabled generation as preferredOrder, i.e. 5460 // prefer newly-enabled over earlier-enabled. 5461 info.preferredOrder = linkGeneration; 5462 alwaysList.add(info); 5463 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5464 if (DEBUG_DOMAIN_VERIFICATION) { 5465 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5466 } 5467 neverList.add(info); 5468 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5469 if (DEBUG_DOMAIN_VERIFICATION) { 5470 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5471 } 5472 alwaysAskList.add(info); 5473 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5474 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5475 if (DEBUG_DOMAIN_VERIFICATION) { 5476 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5477 } 5478 undefinedList.add(info); 5479 } 5480 } 5481 } 5482 5483 // We'll want to include browser possibilities in a few cases 5484 boolean includeBrowser = false; 5485 5486 // First try to add the "always" resolution(s) for the current user, if any 5487 if (alwaysList.size() > 0) { 5488 result.addAll(alwaysList); 5489 } else { 5490 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5491 result.addAll(undefinedList); 5492 // Maybe add one for the other profile. 5493 if (xpDomainInfo != null && ( 5494 xpDomainInfo.bestDomainVerificationStatus 5495 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5496 result.add(xpDomainInfo.resolveInfo); 5497 } 5498 includeBrowser = true; 5499 } 5500 5501 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5502 // If there were 'always' entries their preferred order has been set, so we also 5503 // back that off to make the alternatives equivalent 5504 if (alwaysAskList.size() > 0) { 5505 for (ResolveInfo i : result) { 5506 i.preferredOrder = 0; 5507 } 5508 result.addAll(alwaysAskList); 5509 includeBrowser = true; 5510 } 5511 5512 if (includeBrowser) { 5513 // Also add browsers (all of them or only the default one) 5514 if (DEBUG_DOMAIN_VERIFICATION) { 5515 Slog.v(TAG, " ...including browsers in candidate set"); 5516 } 5517 if ((matchFlags & MATCH_ALL) != 0) { 5518 result.addAll(matchAllList); 5519 } else { 5520 // Browser/generic handling case. If there's a default browser, go straight 5521 // to that (but only if there is no other higher-priority match). 5522 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5523 int maxMatchPrio = 0; 5524 ResolveInfo defaultBrowserMatch = null; 5525 final int numCandidates = matchAllList.size(); 5526 for (int n = 0; n < numCandidates; n++) { 5527 ResolveInfo info = matchAllList.get(n); 5528 // track the highest overall match priority... 5529 if (info.priority > maxMatchPrio) { 5530 maxMatchPrio = info.priority; 5531 } 5532 // ...and the highest-priority default browser match 5533 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5534 if (defaultBrowserMatch == null 5535 || (defaultBrowserMatch.priority < info.priority)) { 5536 if (debug) { 5537 Slog.v(TAG, "Considering default browser match " + info); 5538 } 5539 defaultBrowserMatch = info; 5540 } 5541 } 5542 } 5543 if (defaultBrowserMatch != null 5544 && defaultBrowserMatch.priority >= maxMatchPrio 5545 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5546 { 5547 if (debug) { 5548 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5549 } 5550 result.add(defaultBrowserMatch); 5551 } else { 5552 result.addAll(matchAllList); 5553 } 5554 } 5555 5556 // If there is nothing selected, add all candidates and remove the ones that the user 5557 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5558 if (result.size() == 0) { 5559 result.addAll(candidates); 5560 result.removeAll(neverList); 5561 } 5562 } 5563 } 5564 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5565 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5566 result.size()); 5567 for (ResolveInfo info : result) { 5568 Slog.v(TAG, " + " + info.activityInfo); 5569 } 5570 } 5571 return result; 5572 } 5573 5574 // Returns a packed value as a long: 5575 // 5576 // high 'int'-sized word: link status: undefined/ask/never/always. 5577 // low 'int'-sized word: relative priority among 'always' results. 5578 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5579 long result = ps.getDomainVerificationStatusForUser(userId); 5580 // if none available, get the master status 5581 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5582 if (ps.getIntentFilterVerificationInfo() != null) { 5583 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5584 } 5585 } 5586 return result; 5587 } 5588 5589 private ResolveInfo querySkipCurrentProfileIntents( 5590 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5591 int flags, int sourceUserId) { 5592 if (matchingFilters != null) { 5593 int size = matchingFilters.size(); 5594 for (int i = 0; i < size; i ++) { 5595 CrossProfileIntentFilter filter = matchingFilters.get(i); 5596 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5597 // Checking if there are activities in the target user that can handle the 5598 // intent. 5599 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5600 resolvedType, flags, sourceUserId); 5601 if (resolveInfo != null) { 5602 return resolveInfo; 5603 } 5604 } 5605 } 5606 } 5607 return null; 5608 } 5609 5610 // Return matching ResolveInfo in target user if any. 5611 private ResolveInfo queryCrossProfileIntents( 5612 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5613 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5614 if (matchingFilters != null) { 5615 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5616 // match the same intent. For performance reasons, it is better not to 5617 // run queryIntent twice for the same userId 5618 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5619 int size = matchingFilters.size(); 5620 for (int i = 0; i < size; i++) { 5621 CrossProfileIntentFilter filter = matchingFilters.get(i); 5622 int targetUserId = filter.getTargetUserId(); 5623 boolean skipCurrentProfile = 5624 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5625 boolean skipCurrentProfileIfNoMatchFound = 5626 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5627 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5628 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5629 // Checking if there are activities in the target user that can handle the 5630 // intent. 5631 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5632 resolvedType, flags, sourceUserId); 5633 if (resolveInfo != null) return resolveInfo; 5634 alreadyTriedUserIds.put(targetUserId, true); 5635 } 5636 } 5637 } 5638 return null; 5639 } 5640 5641 /** 5642 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5643 * will forward the intent to the filter's target user. 5644 * Otherwise, returns null. 5645 */ 5646 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5647 String resolvedType, int flags, int sourceUserId) { 5648 int targetUserId = filter.getTargetUserId(); 5649 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5650 resolvedType, flags, targetUserId); 5651 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5652 // If all the matches in the target profile are suspended, return null. 5653 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5654 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5655 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5656 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5657 targetUserId); 5658 } 5659 } 5660 } 5661 return null; 5662 } 5663 5664 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5665 int sourceUserId, int targetUserId) { 5666 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5667 long ident = Binder.clearCallingIdentity(); 5668 boolean targetIsProfile; 5669 try { 5670 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5671 } finally { 5672 Binder.restoreCallingIdentity(ident); 5673 } 5674 String className; 5675 if (targetIsProfile) { 5676 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5677 } else { 5678 className = FORWARD_INTENT_TO_PARENT; 5679 } 5680 ComponentName forwardingActivityComponentName = new ComponentName( 5681 mAndroidApplication.packageName, className); 5682 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5683 sourceUserId); 5684 if (!targetIsProfile) { 5685 forwardingActivityInfo.showUserIcon = targetUserId; 5686 forwardingResolveInfo.noResourceId = true; 5687 } 5688 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5689 forwardingResolveInfo.priority = 0; 5690 forwardingResolveInfo.preferredOrder = 0; 5691 forwardingResolveInfo.match = 0; 5692 forwardingResolveInfo.isDefault = true; 5693 forwardingResolveInfo.filter = filter; 5694 forwardingResolveInfo.targetUserId = targetUserId; 5695 return forwardingResolveInfo; 5696 } 5697 5698 @Override 5699 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5700 Intent[] specifics, String[] specificTypes, Intent intent, 5701 String resolvedType, int flags, int userId) { 5702 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 5703 specificTypes, intent, resolvedType, flags, userId)); 5704 } 5705 5706 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 5707 Intent[] specifics, String[] specificTypes, Intent intent, 5708 String resolvedType, int flags, int userId) { 5709 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5710 flags = updateFlagsForResolve(flags, userId, intent); 5711 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5712 false /* requireFullPermission */, false /* checkShell */, 5713 "query intent activity options"); 5714 final String resultsAction = intent.getAction(); 5715 5716 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 5717 | PackageManager.GET_RESOLVED_FILTER, userId); 5718 5719 if (DEBUG_INTENT_MATCHING) { 5720 Log.v(TAG, "Query " + intent + ": " + results); 5721 } 5722 5723 int specificsPos = 0; 5724 int N; 5725 5726 // todo: note that the algorithm used here is O(N^2). This 5727 // isn't a problem in our current environment, but if we start running 5728 // into situations where we have more than 5 or 10 matches then this 5729 // should probably be changed to something smarter... 5730 5731 // First we go through and resolve each of the specific items 5732 // that were supplied, taking care of removing any corresponding 5733 // duplicate items in the generic resolve list. 5734 if (specifics != null) { 5735 for (int i=0; i<specifics.length; i++) { 5736 final Intent sintent = specifics[i]; 5737 if (sintent == null) { 5738 continue; 5739 } 5740 5741 if (DEBUG_INTENT_MATCHING) { 5742 Log.v(TAG, "Specific #" + i + ": " + sintent); 5743 } 5744 5745 String action = sintent.getAction(); 5746 if (resultsAction != null && resultsAction.equals(action)) { 5747 // If this action was explicitly requested, then don't 5748 // remove things that have it. 5749 action = null; 5750 } 5751 5752 ResolveInfo ri = null; 5753 ActivityInfo ai = null; 5754 5755 ComponentName comp = sintent.getComponent(); 5756 if (comp == null) { 5757 ri = resolveIntent( 5758 sintent, 5759 specificTypes != null ? specificTypes[i] : null, 5760 flags, userId); 5761 if (ri == null) { 5762 continue; 5763 } 5764 if (ri == mResolveInfo) { 5765 // ACK! Must do something better with this. 5766 } 5767 ai = ri.activityInfo; 5768 comp = new ComponentName(ai.applicationInfo.packageName, 5769 ai.name); 5770 } else { 5771 ai = getActivityInfo(comp, flags, userId); 5772 if (ai == null) { 5773 continue; 5774 } 5775 } 5776 5777 // Look for any generic query activities that are duplicates 5778 // of this specific one, and remove them from the results. 5779 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5780 N = results.size(); 5781 int j; 5782 for (j=specificsPos; j<N; j++) { 5783 ResolveInfo sri = results.get(j); 5784 if ((sri.activityInfo.name.equals(comp.getClassName()) 5785 && sri.activityInfo.applicationInfo.packageName.equals( 5786 comp.getPackageName())) 5787 || (action != null && sri.filter.matchAction(action))) { 5788 results.remove(j); 5789 if (DEBUG_INTENT_MATCHING) Log.v( 5790 TAG, "Removing duplicate item from " + j 5791 + " due to specific " + specificsPos); 5792 if (ri == null) { 5793 ri = sri; 5794 } 5795 j--; 5796 N--; 5797 } 5798 } 5799 5800 // Add this specific item to its proper place. 5801 if (ri == null) { 5802 ri = new ResolveInfo(); 5803 ri.activityInfo = ai; 5804 } 5805 results.add(specificsPos, ri); 5806 ri.specificIndex = i; 5807 specificsPos++; 5808 } 5809 } 5810 5811 // Now we go through the remaining generic results and remove any 5812 // duplicate actions that are found here. 5813 N = results.size(); 5814 for (int i=specificsPos; i<N-1; i++) { 5815 final ResolveInfo rii = results.get(i); 5816 if (rii.filter == null) { 5817 continue; 5818 } 5819 5820 // Iterate over all of the actions of this result's intent 5821 // filter... typically this should be just one. 5822 final Iterator<String> it = rii.filter.actionsIterator(); 5823 if (it == null) { 5824 continue; 5825 } 5826 while (it.hasNext()) { 5827 final String action = it.next(); 5828 if (resultsAction != null && resultsAction.equals(action)) { 5829 // If this action was explicitly requested, then don't 5830 // remove things that have it. 5831 continue; 5832 } 5833 for (int j=i+1; j<N; j++) { 5834 final ResolveInfo rij = results.get(j); 5835 if (rij.filter != null && rij.filter.hasAction(action)) { 5836 results.remove(j); 5837 if (DEBUG_INTENT_MATCHING) Log.v( 5838 TAG, "Removing duplicate item from " + j 5839 + " due to action " + action + " at " + i); 5840 j--; 5841 N--; 5842 } 5843 } 5844 } 5845 5846 // If the caller didn't request filter information, drop it now 5847 // so we don't have to marshall/unmarshall it. 5848 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5849 rii.filter = null; 5850 } 5851 } 5852 5853 // Filter out the caller activity if so requested. 5854 if (caller != null) { 5855 N = results.size(); 5856 for (int i=0; i<N; i++) { 5857 ActivityInfo ainfo = results.get(i).activityInfo; 5858 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5859 && caller.getClassName().equals(ainfo.name)) { 5860 results.remove(i); 5861 break; 5862 } 5863 } 5864 } 5865 5866 // If the caller didn't request filter information, 5867 // drop them now so we don't have to 5868 // marshall/unmarshall it. 5869 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5870 N = results.size(); 5871 for (int i=0; i<N; i++) { 5872 results.get(i).filter = null; 5873 } 5874 } 5875 5876 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5877 return results; 5878 } 5879 5880 @Override 5881 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 5882 String resolvedType, int flags, int userId) { 5883 return new ParceledListSlice<>( 5884 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 5885 } 5886 5887 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 5888 String resolvedType, int flags, int userId) { 5889 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5890 flags = updateFlagsForResolve(flags, userId, intent); 5891 ComponentName comp = intent.getComponent(); 5892 if (comp == null) { 5893 if (intent.getSelector() != null) { 5894 intent = intent.getSelector(); 5895 comp = intent.getComponent(); 5896 } 5897 } 5898 if (comp != null) { 5899 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5900 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5901 if (ai != null) { 5902 ResolveInfo ri = new ResolveInfo(); 5903 ri.activityInfo = ai; 5904 list.add(ri); 5905 } 5906 return list; 5907 } 5908 5909 // reader 5910 synchronized (mPackages) { 5911 String pkgName = intent.getPackage(); 5912 if (pkgName == null) { 5913 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5914 } 5915 final PackageParser.Package pkg = mPackages.get(pkgName); 5916 if (pkg != null) { 5917 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5918 userId); 5919 } 5920 return Collections.emptyList(); 5921 } 5922 } 5923 5924 @Override 5925 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5926 if (!sUserManager.exists(userId)) return null; 5927 flags = updateFlagsForResolve(flags, userId, intent); 5928 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 5929 if (query != null) { 5930 if (query.size() >= 1) { 5931 // If there is more than one service with the same priority, 5932 // just arbitrarily pick the first one. 5933 return query.get(0); 5934 } 5935 } 5936 return null; 5937 } 5938 5939 @Override 5940 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 5941 String resolvedType, int flags, int userId) { 5942 return new ParceledListSlice<>( 5943 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 5944 } 5945 5946 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 5947 String resolvedType, int flags, int userId) { 5948 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5949 flags = updateFlagsForResolve(flags, userId, intent); 5950 ComponentName comp = intent.getComponent(); 5951 if (comp == null) { 5952 if (intent.getSelector() != null) { 5953 intent = intent.getSelector(); 5954 comp = intent.getComponent(); 5955 } 5956 } 5957 if (comp != null) { 5958 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5959 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5960 if (si != null) { 5961 final ResolveInfo ri = new ResolveInfo(); 5962 ri.serviceInfo = si; 5963 list.add(ri); 5964 } 5965 return list; 5966 } 5967 5968 // reader 5969 synchronized (mPackages) { 5970 String pkgName = intent.getPackage(); 5971 if (pkgName == null) { 5972 return mServices.queryIntent(intent, resolvedType, flags, userId); 5973 } 5974 final PackageParser.Package pkg = mPackages.get(pkgName); 5975 if (pkg != null) { 5976 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5977 userId); 5978 } 5979 return Collections.emptyList(); 5980 } 5981 } 5982 5983 @Override 5984 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 5985 String resolvedType, int flags, int userId) { 5986 return new ParceledListSlice<>( 5987 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 5988 } 5989 5990 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 5991 Intent intent, String resolvedType, int flags, int userId) { 5992 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5993 flags = updateFlagsForResolve(flags, userId, intent); 5994 ComponentName comp = intent.getComponent(); 5995 if (comp == null) { 5996 if (intent.getSelector() != null) { 5997 intent = intent.getSelector(); 5998 comp = intent.getComponent(); 5999 } 6000 } 6001 if (comp != null) { 6002 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6003 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 6004 if (pi != null) { 6005 final ResolveInfo ri = new ResolveInfo(); 6006 ri.providerInfo = pi; 6007 list.add(ri); 6008 } 6009 return list; 6010 } 6011 6012 // reader 6013 synchronized (mPackages) { 6014 String pkgName = intent.getPackage(); 6015 if (pkgName == null) { 6016 return mProviders.queryIntent(intent, resolvedType, flags, userId); 6017 } 6018 final PackageParser.Package pkg = mPackages.get(pkgName); 6019 if (pkg != null) { 6020 return mProviders.queryIntentForPackage( 6021 intent, resolvedType, flags, pkg.providers, userId); 6022 } 6023 return Collections.emptyList(); 6024 } 6025 } 6026 6027 @Override 6028 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 6029 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6030 flags = updateFlagsForPackage(flags, userId, null); 6031 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6032 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6033 true /* requireFullPermission */, false /* checkShell */, 6034 "get installed packages"); 6035 6036 // writer 6037 synchronized (mPackages) { 6038 ArrayList<PackageInfo> list; 6039 if (listUninstalled) { 6040 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 6041 for (PackageSetting ps : mSettings.mPackages.values()) { 6042 final PackageInfo pi; 6043 if (ps.pkg != null) { 6044 pi = generatePackageInfo(ps, flags, userId); 6045 } else { 6046 pi = generatePackageInfo(ps, flags, userId); 6047 } 6048 if (pi != null) { 6049 list.add(pi); 6050 } 6051 } 6052 } else { 6053 list = new ArrayList<PackageInfo>(mPackages.size()); 6054 for (PackageParser.Package p : mPackages.values()) { 6055 final PackageInfo pi = 6056 generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 6057 if (pi != null) { 6058 list.add(pi); 6059 } 6060 } 6061 } 6062 6063 return new ParceledListSlice<PackageInfo>(list); 6064 } 6065 } 6066 6067 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 6068 String[] permissions, boolean[] tmp, int flags, int userId) { 6069 int numMatch = 0; 6070 final PermissionsState permissionsState = ps.getPermissionsState(); 6071 for (int i=0; i<permissions.length; i++) { 6072 final String permission = permissions[i]; 6073 if (permissionsState.hasPermission(permission, userId)) { 6074 tmp[i] = true; 6075 numMatch++; 6076 } else { 6077 tmp[i] = false; 6078 } 6079 } 6080 if (numMatch == 0) { 6081 return; 6082 } 6083 final PackageInfo pi; 6084 if (ps.pkg != null) { 6085 pi = generatePackageInfo(ps, flags, userId); 6086 } else { 6087 pi = generatePackageInfo(ps, flags, userId); 6088 } 6089 // The above might return null in cases of uninstalled apps or install-state 6090 // skew across users/profiles. 6091 if (pi != null) { 6092 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 6093 if (numMatch == permissions.length) { 6094 pi.requestedPermissions = permissions; 6095 } else { 6096 pi.requestedPermissions = new String[numMatch]; 6097 numMatch = 0; 6098 for (int i=0; i<permissions.length; i++) { 6099 if (tmp[i]) { 6100 pi.requestedPermissions[numMatch] = permissions[i]; 6101 numMatch++; 6102 } 6103 } 6104 } 6105 } 6106 list.add(pi); 6107 } 6108 } 6109 6110 @Override 6111 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 6112 String[] permissions, int flags, int userId) { 6113 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6114 flags = updateFlagsForPackage(flags, userId, permissions); 6115 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6116 6117 // writer 6118 synchronized (mPackages) { 6119 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 6120 boolean[] tmpBools = new boolean[permissions.length]; 6121 if (listUninstalled) { 6122 for (PackageSetting ps : mSettings.mPackages.values()) { 6123 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 6124 } 6125 } else { 6126 for (PackageParser.Package pkg : mPackages.values()) { 6127 PackageSetting ps = (PackageSetting)pkg.mExtras; 6128 if (ps != null) { 6129 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6130 userId); 6131 } 6132 } 6133 } 6134 6135 return new ParceledListSlice<PackageInfo>(list); 6136 } 6137 } 6138 6139 @Override 6140 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 6141 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6142 flags = updateFlagsForApplication(flags, userId, null); 6143 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6144 6145 // writer 6146 synchronized (mPackages) { 6147 ArrayList<ApplicationInfo> list; 6148 if (listUninstalled) { 6149 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 6150 for (PackageSetting ps : mSettings.mPackages.values()) { 6151 ApplicationInfo ai; 6152 if (ps.pkg != null) { 6153 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 6154 ps.readUserState(userId), userId); 6155 } else { 6156 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 6157 } 6158 if (ai != null) { 6159 list.add(ai); 6160 } 6161 } 6162 } else { 6163 list = new ArrayList<ApplicationInfo>(mPackages.size()); 6164 for (PackageParser.Package p : mPackages.values()) { 6165 if (p.mExtras != null) { 6166 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6167 ((PackageSetting)p.mExtras).readUserState(userId), userId); 6168 if (ai != null) { 6169 list.add(ai); 6170 } 6171 } 6172 } 6173 } 6174 6175 return new ParceledListSlice<ApplicationInfo>(list); 6176 } 6177 } 6178 6179 @Override 6180 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 6181 if (DISABLE_EPHEMERAL_APPS) { 6182 return null; 6183 } 6184 6185 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6186 "getEphemeralApplications"); 6187 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6188 true /* requireFullPermission */, false /* checkShell */, 6189 "getEphemeralApplications"); 6190 synchronized (mPackages) { 6191 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 6192 .getEphemeralApplicationsLPw(userId); 6193 if (ephemeralApps != null) { 6194 return new ParceledListSlice<>(ephemeralApps); 6195 } 6196 } 6197 return null; 6198 } 6199 6200 @Override 6201 public boolean isEphemeralApplication(String packageName, int userId) { 6202 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6203 true /* requireFullPermission */, false /* checkShell */, 6204 "isEphemeral"); 6205 if (DISABLE_EPHEMERAL_APPS) { 6206 return false; 6207 } 6208 6209 if (!isCallerSameApp(packageName)) { 6210 return false; 6211 } 6212 synchronized (mPackages) { 6213 PackageParser.Package pkg = mPackages.get(packageName); 6214 if (pkg != null) { 6215 return pkg.applicationInfo.isEphemeralApp(); 6216 } 6217 } 6218 return false; 6219 } 6220 6221 @Override 6222 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6223 if (DISABLE_EPHEMERAL_APPS) { 6224 return null; 6225 } 6226 6227 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6228 true /* requireFullPermission */, false /* checkShell */, 6229 "getCookie"); 6230 if (!isCallerSameApp(packageName)) { 6231 return null; 6232 } 6233 synchronized (mPackages) { 6234 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6235 packageName, userId); 6236 } 6237 } 6238 6239 @Override 6240 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6241 if (DISABLE_EPHEMERAL_APPS) { 6242 return true; 6243 } 6244 6245 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6246 true /* requireFullPermission */, true /* checkShell */, 6247 "setCookie"); 6248 if (!isCallerSameApp(packageName)) { 6249 return false; 6250 } 6251 synchronized (mPackages) { 6252 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6253 packageName, cookie, userId); 6254 } 6255 } 6256 6257 @Override 6258 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6259 if (DISABLE_EPHEMERAL_APPS) { 6260 return null; 6261 } 6262 6263 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6264 "getEphemeralApplicationIcon"); 6265 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6266 true /* requireFullPermission */, false /* checkShell */, 6267 "getEphemeralApplicationIcon"); 6268 synchronized (mPackages) { 6269 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6270 packageName, userId); 6271 } 6272 } 6273 6274 private boolean isCallerSameApp(String packageName) { 6275 PackageParser.Package pkg = mPackages.get(packageName); 6276 return pkg != null 6277 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6278 } 6279 6280 @Override 6281 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 6282 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 6283 } 6284 6285 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 6286 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6287 6288 // reader 6289 synchronized (mPackages) { 6290 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6291 final int userId = UserHandle.getCallingUserId(); 6292 while (i.hasNext()) { 6293 final PackageParser.Package p = i.next(); 6294 if (p.applicationInfo == null) continue; 6295 6296 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 6297 && !p.applicationInfo.isDirectBootAware(); 6298 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 6299 && p.applicationInfo.isDirectBootAware(); 6300 6301 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6302 && (!mSafeMode || isSystemApp(p)) 6303 && (matchesUnaware || matchesAware)) { 6304 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6305 if (ps != null) { 6306 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6307 ps.readUserState(userId), userId); 6308 if (ai != null) { 6309 finalList.add(ai); 6310 } 6311 } 6312 } 6313 } 6314 } 6315 6316 return finalList; 6317 } 6318 6319 @Override 6320 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6321 if (!sUserManager.exists(userId)) return null; 6322 flags = updateFlagsForComponent(flags, userId, name); 6323 // reader 6324 synchronized (mPackages) { 6325 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6326 PackageSetting ps = provider != null 6327 ? mSettings.mPackages.get(provider.owner.packageName) 6328 : null; 6329 return ps != null 6330 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6331 ? PackageParser.generateProviderInfo(provider, flags, 6332 ps.readUserState(userId), userId) 6333 : null; 6334 } 6335 } 6336 6337 /** 6338 * @deprecated 6339 */ 6340 @Deprecated 6341 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6342 // reader 6343 synchronized (mPackages) { 6344 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6345 .entrySet().iterator(); 6346 final int userId = UserHandle.getCallingUserId(); 6347 while (i.hasNext()) { 6348 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6349 PackageParser.Provider p = entry.getValue(); 6350 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6351 6352 if (ps != null && p.syncable 6353 && (!mSafeMode || (p.info.applicationInfo.flags 6354 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6355 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6356 ps.readUserState(userId), userId); 6357 if (info != null) { 6358 outNames.add(entry.getKey()); 6359 outInfo.add(info); 6360 } 6361 } 6362 } 6363 } 6364 } 6365 6366 @Override 6367 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6368 int uid, int flags) { 6369 final int userId = processName != null ? UserHandle.getUserId(uid) 6370 : UserHandle.getCallingUserId(); 6371 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6372 flags = updateFlagsForComponent(flags, userId, processName); 6373 6374 ArrayList<ProviderInfo> finalList = null; 6375 // reader 6376 synchronized (mPackages) { 6377 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6378 while (i.hasNext()) { 6379 final PackageParser.Provider p = i.next(); 6380 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6381 if (ps != null && p.info.authority != null 6382 && (processName == null 6383 || (p.info.processName.equals(processName) 6384 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6385 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6386 if (finalList == null) { 6387 finalList = new ArrayList<ProviderInfo>(3); 6388 } 6389 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6390 ps.readUserState(userId), userId); 6391 if (info != null) { 6392 finalList.add(info); 6393 } 6394 } 6395 } 6396 } 6397 6398 if (finalList != null) { 6399 Collections.sort(finalList, mProviderInitOrderSorter); 6400 return new ParceledListSlice<ProviderInfo>(finalList); 6401 } 6402 6403 return ParceledListSlice.emptyList(); 6404 } 6405 6406 @Override 6407 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6408 // reader 6409 synchronized (mPackages) { 6410 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6411 return PackageParser.generateInstrumentationInfo(i, flags); 6412 } 6413 } 6414 6415 @Override 6416 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 6417 String targetPackage, int flags) { 6418 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 6419 } 6420 6421 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 6422 int flags) { 6423 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 6424 6425 // reader 6426 synchronized (mPackages) { 6427 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6428 while (i.hasNext()) { 6429 final PackageParser.Instrumentation p = i.next(); 6430 if (targetPackage == null 6431 || targetPackage.equals(p.info.targetPackage)) { 6432 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6433 flags); 6434 if (ii != null) { 6435 finalList.add(ii); 6436 } 6437 } 6438 } 6439 } 6440 6441 return finalList; 6442 } 6443 6444 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6445 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6446 if (overlays == null) { 6447 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6448 return; 6449 } 6450 for (PackageParser.Package opkg : overlays.values()) { 6451 // Not much to do if idmap fails: we already logged the error 6452 // and we certainly don't want to abort installation of pkg simply 6453 // because an overlay didn't fit properly. For these reasons, 6454 // ignore the return value of createIdmapForPackagePairLI. 6455 createIdmapForPackagePairLI(pkg, opkg); 6456 } 6457 } 6458 6459 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6460 PackageParser.Package opkg) { 6461 if (!opkg.mTrustedOverlay) { 6462 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6463 opkg.baseCodePath + ": overlay not trusted"); 6464 return false; 6465 } 6466 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6467 if (overlaySet == null) { 6468 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6469 opkg.baseCodePath + " but target package has no known overlays"); 6470 return false; 6471 } 6472 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6473 // TODO: generate idmap for split APKs 6474 try { 6475 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6476 } catch (InstallerException e) { 6477 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6478 + opkg.baseCodePath); 6479 return false; 6480 } 6481 PackageParser.Package[] overlayArray = 6482 overlaySet.values().toArray(new PackageParser.Package[0]); 6483 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6484 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6485 return p1.mOverlayPriority - p2.mOverlayPriority; 6486 } 6487 }; 6488 Arrays.sort(overlayArray, cmp); 6489 6490 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6491 int i = 0; 6492 for (PackageParser.Package p : overlayArray) { 6493 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6494 } 6495 return true; 6496 } 6497 6498 private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6499 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6500 try { 6501 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6502 } finally { 6503 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6504 } 6505 } 6506 6507 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6508 final File[] files = dir.listFiles(); 6509 if (ArrayUtils.isEmpty(files)) { 6510 Log.d(TAG, "No files in app dir " + dir); 6511 return; 6512 } 6513 6514 if (DEBUG_PACKAGE_SCANNING) { 6515 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6516 + " flags=0x" + Integer.toHexString(parseFlags)); 6517 } 6518 6519 for (File file : files) { 6520 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6521 && !PackageInstallerService.isStageName(file.getName()); 6522 if (!isPackage) { 6523 // Ignore entries which are not packages 6524 continue; 6525 } 6526 try { 6527 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6528 scanFlags, currentTime, null); 6529 } catch (PackageManagerException e) { 6530 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6531 6532 // Delete invalid userdata apps 6533 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6534 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6535 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6536 removeCodePathLI(file); 6537 } 6538 } 6539 } 6540 } 6541 6542 private static File getSettingsProblemFile() { 6543 File dataDir = Environment.getDataDirectory(); 6544 File systemDir = new File(dataDir, "system"); 6545 File fname = new File(systemDir, "uiderrors.txt"); 6546 return fname; 6547 } 6548 6549 static void reportSettingsProblem(int priority, String msg) { 6550 logCriticalInfo(priority, msg); 6551 } 6552 6553 static void logCriticalInfo(int priority, String msg) { 6554 Slog.println(priority, TAG, msg); 6555 EventLogTags.writePmCriticalInfo(msg); 6556 try { 6557 File fname = getSettingsProblemFile(); 6558 FileOutputStream out = new FileOutputStream(fname, true); 6559 PrintWriter pw = new FastPrintWriter(out); 6560 SimpleDateFormat formatter = new SimpleDateFormat(); 6561 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6562 pw.println(dateString + ": " + msg); 6563 pw.close(); 6564 FileUtils.setPermissions( 6565 fname.toString(), 6566 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6567 -1, -1); 6568 } catch (java.io.IOException e) { 6569 } 6570 } 6571 6572 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6573 int parseFlags) throws PackageManagerException { 6574 if (ps != null 6575 && ps.codePath.equals(srcFile) 6576 && ps.timeStamp == srcFile.lastModified() 6577 && !isCompatSignatureUpdateNeeded(pkg) 6578 && !isRecoverSignatureUpdateNeeded(pkg)) { 6579 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6580 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6581 ArraySet<PublicKey> signingKs; 6582 synchronized (mPackages) { 6583 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6584 } 6585 if (ps.signatures.mSignatures != null 6586 && ps.signatures.mSignatures.length != 0 6587 && signingKs != null) { 6588 // Optimization: reuse the existing cached certificates 6589 // if the package appears to be unchanged. 6590 pkg.mSignatures = ps.signatures.mSignatures; 6591 pkg.mSigningKeys = signingKs; 6592 return; 6593 } 6594 6595 Slog.w(TAG, "PackageSetting for " + ps.name 6596 + " is missing signatures. Collecting certs again to recover them."); 6597 } else { 6598 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6599 } 6600 6601 try { 6602 PackageParser.collectCertificates(pkg, parseFlags); 6603 } catch (PackageParserException e) { 6604 throw PackageManagerException.from(e); 6605 } 6606 } 6607 6608 /** 6609 * Traces a package scan. 6610 * @see #scanPackageLI(File, int, int, long, UserHandle) 6611 */ 6612 private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags, 6613 long currentTime, UserHandle user) throws PackageManagerException { 6614 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6615 try { 6616 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6617 } finally { 6618 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6619 } 6620 } 6621 6622 /** 6623 * Scans a package and returns the newly parsed package. 6624 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6625 */ 6626 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6627 long currentTime, UserHandle user) throws PackageManagerException { 6628 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6629 parseFlags |= mDefParseFlags; 6630 PackageParser pp = new PackageParser(); 6631 pp.setSeparateProcesses(mSeparateProcesses); 6632 pp.setOnlyCoreApps(mOnlyCore); 6633 pp.setDisplayMetrics(mMetrics); 6634 6635 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6636 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6637 } 6638 6639 final PackageParser.Package pkg; 6640 try { 6641 pkg = pp.parsePackage(scanFile, parseFlags); 6642 } catch (PackageParserException e) { 6643 throw PackageManagerException.from(e); 6644 } 6645 6646 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6647 } 6648 6649 /** 6650 * Scans a package and returns the newly parsed package. 6651 * @throws PackageManagerException on a parse error. 6652 */ 6653 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6654 int parseFlags, int scanFlags, long currentTime, UserHandle user) 6655 throws PackageManagerException { 6656 // If the package has children and this is the first dive in the function 6657 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6658 // packages (parent and children) would be successfully scanned before the 6659 // actual scan since scanning mutates internal state and we want to atomically 6660 // install the package and its children. 6661 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6662 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6663 scanFlags |= SCAN_CHECK_ONLY; 6664 } 6665 } else { 6666 scanFlags &= ~SCAN_CHECK_ONLY; 6667 } 6668 6669 // Scan the parent 6670 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, parseFlags, 6671 scanFlags, currentTime, user); 6672 6673 // Scan the children 6674 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6675 for (int i = 0; i < childCount; i++) { 6676 PackageParser.Package childPackage = pkg.childPackages.get(i); 6677 scanPackageInternalLI(childPackage, scanFile, parseFlags, scanFlags, 6678 currentTime, user); 6679 } 6680 6681 6682 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6683 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6684 } 6685 6686 return scannedPkg; 6687 } 6688 6689 /** 6690 * Scans a package and returns the newly parsed package. 6691 * @throws PackageManagerException on a parse error. 6692 */ 6693 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6694 int parseFlags, int scanFlags, long currentTime, UserHandle user) 6695 throws PackageManagerException { 6696 PackageSetting ps = null; 6697 PackageSetting updatedPkg; 6698 // reader 6699 synchronized (mPackages) { 6700 // Look to see if we already know about this package. 6701 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6702 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6703 // This package has been renamed to its original name. Let's 6704 // use that. 6705 ps = mSettings.peekPackageLPr(oldName); 6706 } 6707 // If there was no original package, see one for the real package name. 6708 if (ps == null) { 6709 ps = mSettings.peekPackageLPr(pkg.packageName); 6710 } 6711 // Check to see if this package could be hiding/updating a system 6712 // package. Must look for it either under the original or real 6713 // package name depending on our state. 6714 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6715 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6716 6717 // If this is a package we don't know about on the system partition, we 6718 // may need to remove disabled child packages on the system partition 6719 // or may need to not add child packages if the parent apk is updated 6720 // on the data partition and no longer defines this child package. 6721 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6722 // If this is a parent package for an updated system app and this system 6723 // app got an OTA update which no longer defines some of the child packages 6724 // we have to prune them from the disabled system packages. 6725 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6726 if (disabledPs != null) { 6727 final int scannedChildCount = (pkg.childPackages != null) 6728 ? pkg.childPackages.size() : 0; 6729 final int disabledChildCount = disabledPs.childPackageNames != null 6730 ? disabledPs.childPackageNames.size() : 0; 6731 for (int i = 0; i < disabledChildCount; i++) { 6732 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6733 boolean disabledPackageAvailable = false; 6734 for (int j = 0; j < scannedChildCount; j++) { 6735 PackageParser.Package childPkg = pkg.childPackages.get(j); 6736 if (childPkg.packageName.equals(disabledChildPackageName)) { 6737 disabledPackageAvailable = true; 6738 break; 6739 } 6740 } 6741 if (!disabledPackageAvailable) { 6742 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6743 } 6744 } 6745 } 6746 } 6747 } 6748 6749 boolean updatedPkgBetter = false; 6750 // First check if this is a system package that may involve an update 6751 if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6752 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6753 // it needs to drop FLAG_PRIVILEGED. 6754 if (locationIsPrivileged(scanFile)) { 6755 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6756 } else { 6757 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6758 } 6759 6760 if (ps != null && !ps.codePath.equals(scanFile)) { 6761 // The path has changed from what was last scanned... check the 6762 // version of the new path against what we have stored to determine 6763 // what to do. 6764 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6765 if (pkg.mVersionCode <= ps.versionCode) { 6766 // The system package has been updated and the code path does not match 6767 // Ignore entry. Skip it. 6768 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6769 + " ignored: updated version " + ps.versionCode 6770 + " better than this " + pkg.mVersionCode); 6771 if (!updatedPkg.codePath.equals(scanFile)) { 6772 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6773 + ps.name + " changing from " + updatedPkg.codePathString 6774 + " to " + scanFile); 6775 updatedPkg.codePath = scanFile; 6776 updatedPkg.codePathString = scanFile.toString(); 6777 updatedPkg.resourcePath = scanFile; 6778 updatedPkg.resourcePathString = scanFile.toString(); 6779 } 6780 updatedPkg.pkg = pkg; 6781 updatedPkg.versionCode = pkg.mVersionCode; 6782 6783 // Update the disabled system child packages to point to the package too. 6784 final int childCount = updatedPkg.childPackageNames != null 6785 ? updatedPkg.childPackageNames.size() : 0; 6786 for (int i = 0; i < childCount; i++) { 6787 String childPackageName = updatedPkg.childPackageNames.get(i); 6788 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 6789 childPackageName); 6790 if (updatedChildPkg != null) { 6791 updatedChildPkg.pkg = pkg; 6792 updatedChildPkg.versionCode = pkg.mVersionCode; 6793 } 6794 } 6795 6796 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 6797 + scanFile + " ignored: updated version " + ps.versionCode 6798 + " better than this " + pkg.mVersionCode); 6799 } else { 6800 // The current app on the system partition is better than 6801 // what we have updated to on the data partition; switch 6802 // back to the system partition version. 6803 // At this point, its safely assumed that package installation for 6804 // apps in system partition will go through. If not there won't be a working 6805 // version of the app 6806 // writer 6807 synchronized (mPackages) { 6808 // Just remove the loaded entries from package lists. 6809 mPackages.remove(ps.name); 6810 } 6811 6812 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6813 + " reverting from " + ps.codePathString 6814 + ": new version " + pkg.mVersionCode 6815 + " better than installed " + ps.versionCode); 6816 6817 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6818 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6819 synchronized (mInstallLock) { 6820 args.cleanUpResourcesLI(); 6821 } 6822 synchronized (mPackages) { 6823 mSettings.enableSystemPackageLPw(ps.name); 6824 } 6825 updatedPkgBetter = true; 6826 } 6827 } 6828 } 6829 6830 if (updatedPkg != null) { 6831 // An updated system app will not have the PARSE_IS_SYSTEM flag set 6832 // initially 6833 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 6834 6835 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 6836 // flag set initially 6837 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 6838 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 6839 } 6840 } 6841 6842 // Verify certificates against what was last scanned 6843 collectCertificatesLI(ps, pkg, scanFile, parseFlags); 6844 6845 /* 6846 * A new system app appeared, but we already had a non-system one of the 6847 * same name installed earlier. 6848 */ 6849 boolean shouldHideSystemApp = false; 6850 if (updatedPkg == null && ps != null 6851 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 6852 /* 6853 * Check to make sure the signatures match first. If they don't, 6854 * wipe the installed application and its data. 6855 */ 6856 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 6857 != PackageManager.SIGNATURE_MATCH) { 6858 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 6859 + " signatures don't match existing userdata copy; removing"); 6860 try (PackageFreezer freezer = freezePackage(pkg.packageName, 6861 "scanPackageInternalLI")) { 6862 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 6863 } 6864 ps = null; 6865 } else { 6866 /* 6867 * If the newly-added system app is an older version than the 6868 * already installed version, hide it. It will be scanned later 6869 * and re-added like an update. 6870 */ 6871 if (pkg.mVersionCode <= ps.versionCode) { 6872 shouldHideSystemApp = true; 6873 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 6874 + " but new version " + pkg.mVersionCode + " better than installed " 6875 + ps.versionCode + "; hiding system"); 6876 } else { 6877 /* 6878 * The newly found system app is a newer version that the 6879 * one previously installed. Simply remove the 6880 * already-installed application and replace it with our own 6881 * while keeping the application data. 6882 */ 6883 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6884 + " reverting from " + ps.codePathString + ": new version " 6885 + pkg.mVersionCode + " better than installed " + ps.versionCode); 6886 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6887 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6888 synchronized (mInstallLock) { 6889 args.cleanUpResourcesLI(); 6890 } 6891 } 6892 } 6893 } 6894 6895 // The apk is forward locked (not public) if its code and resources 6896 // are kept in different files. (except for app in either system or 6897 // vendor path). 6898 // TODO grab this value from PackageSettings 6899 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6900 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 6901 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 6902 } 6903 } 6904 6905 // TODO: extend to support forward-locked splits 6906 String resourcePath = null; 6907 String baseResourcePath = null; 6908 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 6909 if (ps != null && ps.resourcePathString != null) { 6910 resourcePath = ps.resourcePathString; 6911 baseResourcePath = ps.resourcePathString; 6912 } else { 6913 // Should not happen at all. Just log an error. 6914 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 6915 } 6916 } else { 6917 resourcePath = pkg.codePath; 6918 baseResourcePath = pkg.baseCodePath; 6919 } 6920 6921 // Set application objects path explicitly. 6922 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 6923 pkg.setApplicationInfoCodePath(pkg.codePath); 6924 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 6925 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 6926 pkg.setApplicationInfoResourcePath(resourcePath); 6927 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 6928 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 6929 6930 // Note that we invoke the following method only if we are about to unpack an application 6931 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 6932 | SCAN_UPDATE_SIGNATURE, currentTime, user); 6933 6934 /* 6935 * If the system app should be overridden by a previously installed 6936 * data, hide the system app now and let the /data/app scan pick it up 6937 * again. 6938 */ 6939 if (shouldHideSystemApp) { 6940 synchronized (mPackages) { 6941 mSettings.disableSystemPackageLPw(pkg.packageName, true); 6942 } 6943 } 6944 6945 return scannedPkg; 6946 } 6947 6948 private static String fixProcessName(String defProcessName, 6949 String processName, int uid) { 6950 if (processName == null) { 6951 return defProcessName; 6952 } 6953 return processName; 6954 } 6955 6956 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 6957 throws PackageManagerException { 6958 if (pkgSetting.signatures.mSignatures != null) { 6959 // Already existing package. Make sure signatures match 6960 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 6961 == PackageManager.SIGNATURE_MATCH; 6962 if (!match) { 6963 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 6964 == PackageManager.SIGNATURE_MATCH; 6965 } 6966 if (!match) { 6967 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 6968 == PackageManager.SIGNATURE_MATCH; 6969 } 6970 if (!match) { 6971 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 6972 + pkg.packageName + " signatures do not match the " 6973 + "previously installed version; ignoring!"); 6974 } 6975 } 6976 6977 // Check for shared user signatures 6978 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 6979 // Already existing package. Make sure signatures match 6980 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6981 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 6982 if (!match) { 6983 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 6984 == PackageManager.SIGNATURE_MATCH; 6985 } 6986 if (!match) { 6987 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 6988 == PackageManager.SIGNATURE_MATCH; 6989 } 6990 if (!match) { 6991 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 6992 "Package " + pkg.packageName 6993 + " has no signatures that match those in shared user " 6994 + pkgSetting.sharedUser.name + "; ignoring!"); 6995 } 6996 } 6997 } 6998 6999 /** 7000 * Enforces that only the system UID or root's UID can call a method exposed 7001 * via Binder. 7002 * 7003 * @param message used as message if SecurityException is thrown 7004 * @throws SecurityException if the caller is not system or root 7005 */ 7006 private static final void enforceSystemOrRoot(String message) { 7007 final int uid = Binder.getCallingUid(); 7008 if (uid != Process.SYSTEM_UID && uid != 0) { 7009 throw new SecurityException(message); 7010 } 7011 } 7012 7013 @Override 7014 public void performFstrimIfNeeded() { 7015 enforceSystemOrRoot("Only the system can request fstrim"); 7016 7017 // Before everything else, see whether we need to fstrim. 7018 try { 7019 IMountService ms = PackageHelper.getMountService(); 7020 if (ms != null) { 7021 final boolean isUpgrade = isUpgrade(); 7022 boolean doTrim = isUpgrade; 7023 if (doTrim) { 7024 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 7025 } else { 7026 final long interval = android.provider.Settings.Global.getLong( 7027 mContext.getContentResolver(), 7028 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 7029 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 7030 if (interval > 0) { 7031 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 7032 if (timeSinceLast > interval) { 7033 doTrim = true; 7034 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 7035 + "; running immediately"); 7036 } 7037 } 7038 } 7039 if (doTrim) { 7040 if (!isFirstBoot()) { 7041 try { 7042 ActivityManagerNative.getDefault().showBootMessage( 7043 mContext.getResources().getString( 7044 R.string.android_upgrading_fstrim), true); 7045 } catch (RemoteException e) { 7046 } 7047 } 7048 ms.runMaintenance(); 7049 } 7050 } else { 7051 Slog.e(TAG, "Mount service unavailable!"); 7052 } 7053 } catch (RemoteException e) { 7054 // Can't happen; MountService is local 7055 } 7056 } 7057 7058 @Override 7059 public void updatePackagesIfNeeded() { 7060 enforceSystemOrRoot("Only the system can request package update"); 7061 7062 // We need to re-extract after an OTA. 7063 boolean causeUpgrade = isUpgrade(); 7064 7065 // First boot or factory reset. 7066 // Note: we also handle devices that are upgrading to N right now as if it is their 7067 // first boot, as they do not have profile data. 7068 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 7069 7070 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 7071 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 7072 7073 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 7074 return; 7075 } 7076 7077 List<PackageParser.Package> pkgs; 7078 synchronized (mPackages) { 7079 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 7080 } 7081 7082 UsageStatsManager usageMgr = 7083 (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 7084 7085 int curr = 0; 7086 int total = pkgs.size(); 7087 for (PackageParser.Package pkg : pkgs) { 7088 curr++; 7089 7090 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 7091 if (DEBUG_DEXOPT) { 7092 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 7093 } 7094 continue; 7095 } 7096 7097 if (!causeFirstBoot && usageMgr.isAppInactive(pkg.packageName)) { 7098 if (DEBUG_DEXOPT) { 7099 Log.i(TAG, "Skipping update of of idle app " + pkg.packageName); 7100 } 7101 continue; 7102 } 7103 7104 if (DEBUG_DEXOPT) { 7105 Log.i(TAG, "Extracting app " + curr + " of " + total + ": " + pkg.packageName); 7106 } 7107 7108 if (!isFirstBoot()) { 7109 try { 7110 ActivityManagerNative.getDefault().showBootMessage( 7111 mContext.getResources().getString(R.string.android_upgrading_apk, 7112 curr, total), true); 7113 } catch (RemoteException e) { 7114 } 7115 } 7116 7117 performDexOpt(pkg.packageName, 7118 null /* instructionSet */, 7119 false /* checkProfiles */, 7120 causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT, 7121 false /* force */); 7122 } 7123 } 7124 7125 @Override 7126 public void notifyPackageUse(String packageName) { 7127 synchronized (mPackages) { 7128 PackageParser.Package p = mPackages.get(packageName); 7129 if (p == null) { 7130 return; 7131 } 7132 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 7133 } 7134 } 7135 7136 // TODO: this is not used nor needed. Delete it. 7137 @Override 7138 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 7139 return performDexOptTraced(packageName, instructionSet, false /* checkProfiles */, 7140 getFullCompilerFilter(), false /* force */); 7141 } 7142 7143 @Override 7144 public boolean performDexOpt(String packageName, String instructionSet, 7145 boolean checkProfiles, int compileReason, boolean force) { 7146 return performDexOptTraced(packageName, instructionSet, checkProfiles, 7147 getCompilerFilterForReason(compileReason), force); 7148 } 7149 7150 @Override 7151 public boolean performDexOptMode(String packageName, String instructionSet, 7152 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7153 return performDexOptTraced(packageName, instructionSet, checkProfiles, 7154 targetCompilerFilter, force); 7155 } 7156 7157 private boolean performDexOptTraced(String packageName, String instructionSet, 7158 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7159 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7160 try { 7161 return performDexOptInternal(packageName, instructionSet, checkProfiles, 7162 targetCompilerFilter, force); 7163 } finally { 7164 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7165 } 7166 } 7167 7168 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 7169 // if the package can now be considered up to date for the given filter. 7170 private boolean performDexOptInternal(String packageName, String instructionSet, 7171 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7172 PackageParser.Package p; 7173 final String targetInstructionSet; 7174 synchronized (mPackages) { 7175 p = mPackages.get(packageName); 7176 if (p == null) { 7177 return false; 7178 } 7179 mPackageUsage.write(false); 7180 7181 targetInstructionSet = instructionSet != null ? instructionSet : 7182 getPrimaryInstructionSet(p.applicationInfo); 7183 } 7184 long callingId = Binder.clearCallingIdentity(); 7185 try { 7186 synchronized (mInstallLock) { 7187 final String[] instructionSets = new String[] { targetInstructionSet }; 7188 int result = performDexOptInternalWithDependenciesLI(p, instructionSets, 7189 checkProfiles, targetCompilerFilter, force); 7190 return result != PackageDexOptimizer.DEX_OPT_FAILED; 7191 } 7192 } finally { 7193 Binder.restoreCallingIdentity(callingId); 7194 } 7195 } 7196 7197 public ArraySet<String> getOptimizablePackages() { 7198 ArraySet<String> pkgs = new ArraySet<String>(); 7199 synchronized (mPackages) { 7200 for (PackageParser.Package p : mPackages.values()) { 7201 if (PackageDexOptimizer.canOptimizePackage(p)) { 7202 pkgs.add(p.packageName); 7203 } 7204 } 7205 } 7206 return pkgs; 7207 } 7208 7209 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7210 String instructionSets[], boolean checkProfiles, String targetCompilerFilter, 7211 boolean force) { 7212 // Select the dex optimizer based on the force parameter. 7213 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7214 // allocate an object here. 7215 PackageDexOptimizer pdo = force 7216 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7217 : mPackageDexOptimizer; 7218 7219 // Optimize all dependencies first. Note: we ignore the return value and march on 7220 // on errors. 7221 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7222 if (!deps.isEmpty()) { 7223 for (PackageParser.Package depPackage : deps) { 7224 // TODO: Analyze and investigate if we (should) profile libraries. 7225 // Currently this will do a full compilation of the library by default. 7226 pdo.performDexOpt(depPackage, instructionSets, false /* checkProfiles */, 7227 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY)); 7228 } 7229 } 7230 7231 return pdo.performDexOpt(p, instructionSets, checkProfiles, targetCompilerFilter); 7232 } 7233 7234 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7235 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7236 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7237 Set<String> collectedNames = new HashSet<>(); 7238 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7239 7240 retValue.remove(p); 7241 7242 return retValue; 7243 } else { 7244 return Collections.emptyList(); 7245 } 7246 } 7247 7248 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7249 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7250 if (!collectedNames.contains(p.packageName)) { 7251 collectedNames.add(p.packageName); 7252 collected.add(p); 7253 7254 if (p.usesLibraries != null) { 7255 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7256 } 7257 if (p.usesOptionalLibraries != null) { 7258 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7259 collectedNames); 7260 } 7261 } 7262 } 7263 7264 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7265 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7266 for (String libName : libs) { 7267 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7268 if (libPkg != null) { 7269 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7270 } 7271 } 7272 } 7273 7274 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7275 synchronized (mPackages) { 7276 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7277 if (lib != null && lib.apk != null) { 7278 return mPackages.get(lib.apk); 7279 } 7280 } 7281 return null; 7282 } 7283 7284 public void shutdown() { 7285 mPackageUsage.write(true); 7286 } 7287 7288 @Override 7289 public void forceDexOpt(String packageName) { 7290 enforceSystemOrRoot("forceDexOpt"); 7291 7292 PackageParser.Package pkg; 7293 synchronized (mPackages) { 7294 pkg = mPackages.get(packageName); 7295 if (pkg == null) { 7296 throw new IllegalArgumentException("Unknown package: " + packageName); 7297 } 7298 } 7299 7300 synchronized (mInstallLock) { 7301 final String[] instructionSets = new String[] { 7302 getPrimaryInstructionSet(pkg.applicationInfo) }; 7303 7304 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7305 7306 // Whoever is calling forceDexOpt wants a fully compiled package. 7307 // Don't use profiles since that may cause compilation to be skipped. 7308 final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets, 7309 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7310 true /* force */); 7311 7312 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7313 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7314 throw new IllegalStateException("Failed to dexopt: " + res); 7315 } 7316 } 7317 } 7318 7319 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7320 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7321 Slog.w(TAG, "Unable to update from " + oldPkg.name 7322 + " to " + newPkg.packageName 7323 + ": old package not in system partition"); 7324 return false; 7325 } else if (mPackages.get(oldPkg.name) != null) { 7326 Slog.w(TAG, "Unable to update from " + oldPkg.name 7327 + " to " + newPkg.packageName 7328 + ": old package still exists"); 7329 return false; 7330 } 7331 return true; 7332 } 7333 7334 void removeCodePathLI(File codePath) { 7335 if (codePath.isDirectory()) { 7336 try { 7337 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7338 } catch (InstallerException e) { 7339 Slog.w(TAG, "Failed to remove code path", e); 7340 } 7341 } else { 7342 codePath.delete(); 7343 } 7344 } 7345 7346 private int[] resolveUserIds(int userId) { 7347 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 7348 } 7349 7350 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7351 if (pkg == null) { 7352 Slog.wtf(TAG, "Package was null!", new Throwable()); 7353 return; 7354 } 7355 clearAppDataLeafLIF(pkg, userId, flags); 7356 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7357 for (int i = 0; i < childCount; i++) { 7358 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7359 } 7360 } 7361 7362 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7363 final PackageSetting ps; 7364 synchronized (mPackages) { 7365 ps = mSettings.mPackages.get(pkg.packageName); 7366 } 7367 for (int realUserId : resolveUserIds(userId)) { 7368 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7369 try { 7370 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7371 ceDataInode); 7372 } catch (InstallerException e) { 7373 Slog.w(TAG, String.valueOf(e)); 7374 } 7375 } 7376 } 7377 7378 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7379 if (pkg == null) { 7380 Slog.wtf(TAG, "Package was null!", new Throwable()); 7381 return; 7382 } 7383 destroyAppDataLeafLIF(pkg, userId, flags); 7384 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7385 for (int i = 0; i < childCount; i++) { 7386 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7387 } 7388 } 7389 7390 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7391 final PackageSetting ps; 7392 synchronized (mPackages) { 7393 ps = mSettings.mPackages.get(pkg.packageName); 7394 } 7395 for (int realUserId : resolveUserIds(userId)) { 7396 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7397 try { 7398 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7399 ceDataInode); 7400 } catch (InstallerException e) { 7401 Slog.w(TAG, String.valueOf(e)); 7402 } 7403 } 7404 } 7405 7406 private void destroyAppProfilesLIF(PackageParser.Package pkg) { 7407 if (pkg == null) { 7408 Slog.wtf(TAG, "Package was null!", new Throwable()); 7409 return; 7410 } 7411 destroyAppProfilesLeafLIF(pkg); 7412 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7413 for (int i = 0; i < childCount; i++) { 7414 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 7415 } 7416 } 7417 7418 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 7419 try { 7420 mInstaller.destroyAppProfiles(pkg.packageName); 7421 } catch (InstallerException e) { 7422 Slog.w(TAG, String.valueOf(e)); 7423 } 7424 } 7425 7426 private void clearAppProfilesLIF(PackageParser.Package pkg) { 7427 if (pkg == null) { 7428 Slog.wtf(TAG, "Package was null!", new Throwable()); 7429 return; 7430 } 7431 clearAppProfilesLeafLIF(pkg); 7432 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7433 for (int i = 0; i < childCount; i++) { 7434 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 7435 } 7436 } 7437 7438 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 7439 try { 7440 mInstaller.clearAppProfiles(pkg.packageName); 7441 } catch (InstallerException e) { 7442 Slog.w(TAG, String.valueOf(e)); 7443 } 7444 } 7445 7446 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7447 long lastUpdateTime) { 7448 // Set parent install/update time 7449 PackageSetting ps = (PackageSetting) pkg.mExtras; 7450 if (ps != null) { 7451 ps.firstInstallTime = firstInstallTime; 7452 ps.lastUpdateTime = lastUpdateTime; 7453 } 7454 // Set children install/update time 7455 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7456 for (int i = 0; i < childCount; i++) { 7457 PackageParser.Package childPkg = pkg.childPackages.get(i); 7458 ps = (PackageSetting) childPkg.mExtras; 7459 if (ps != null) { 7460 ps.firstInstallTime = firstInstallTime; 7461 ps.lastUpdateTime = lastUpdateTime; 7462 } 7463 } 7464 } 7465 7466 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7467 PackageParser.Package changingLib) { 7468 if (file.path != null) { 7469 usesLibraryFiles.add(file.path); 7470 return; 7471 } 7472 PackageParser.Package p = mPackages.get(file.apk); 7473 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7474 // If we are doing this while in the middle of updating a library apk, 7475 // then we need to make sure to use that new apk for determining the 7476 // dependencies here. (We haven't yet finished committing the new apk 7477 // to the package manager state.) 7478 if (p == null || p.packageName.equals(changingLib.packageName)) { 7479 p = changingLib; 7480 } 7481 } 7482 if (p != null) { 7483 usesLibraryFiles.addAll(p.getAllCodePaths()); 7484 } 7485 } 7486 7487 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7488 PackageParser.Package changingLib) throws PackageManagerException { 7489 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7490 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7491 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7492 for (int i=0; i<N; i++) { 7493 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7494 if (file == null) { 7495 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7496 "Package " + pkg.packageName + " requires unavailable shared library " 7497 + pkg.usesLibraries.get(i) + "; failing!"); 7498 } 7499 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7500 } 7501 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7502 for (int i=0; i<N; i++) { 7503 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7504 if (file == null) { 7505 Slog.w(TAG, "Package " + pkg.packageName 7506 + " desires unavailable shared library " 7507 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7508 } else { 7509 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7510 } 7511 } 7512 N = usesLibraryFiles.size(); 7513 if (N > 0) { 7514 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7515 } else { 7516 pkg.usesLibraryFiles = null; 7517 } 7518 } 7519 } 7520 7521 private static boolean hasString(List<String> list, List<String> which) { 7522 if (list == null) { 7523 return false; 7524 } 7525 for (int i=list.size()-1; i>=0; i--) { 7526 for (int j=which.size()-1; j>=0; j--) { 7527 if (which.get(j).equals(list.get(i))) { 7528 return true; 7529 } 7530 } 7531 } 7532 return false; 7533 } 7534 7535 private void updateAllSharedLibrariesLPw() { 7536 for (PackageParser.Package pkg : mPackages.values()) { 7537 try { 7538 updateSharedLibrariesLPw(pkg, null); 7539 } catch (PackageManagerException e) { 7540 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7541 } 7542 } 7543 } 7544 7545 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7546 PackageParser.Package changingPkg) { 7547 ArrayList<PackageParser.Package> res = null; 7548 for (PackageParser.Package pkg : mPackages.values()) { 7549 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7550 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7551 if (res == null) { 7552 res = new ArrayList<PackageParser.Package>(); 7553 } 7554 res.add(pkg); 7555 try { 7556 updateSharedLibrariesLPw(pkg, changingPkg); 7557 } catch (PackageManagerException e) { 7558 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7559 } 7560 } 7561 } 7562 return res; 7563 } 7564 7565 /** 7566 * Derive the value of the {@code cpuAbiOverride} based on the provided 7567 * value and an optional stored value from the package settings. 7568 */ 7569 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7570 String cpuAbiOverride = null; 7571 7572 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7573 cpuAbiOverride = null; 7574 } else if (abiOverride != null) { 7575 cpuAbiOverride = abiOverride; 7576 } else if (settings != null) { 7577 cpuAbiOverride = settings.cpuAbiOverrideString; 7578 } 7579 7580 return cpuAbiOverride; 7581 } 7582 7583 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags, 7584 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7585 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7586 // If the package has children and this is the first dive in the function 7587 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7588 // whether all packages (parent and children) would be successfully scanned 7589 // before the actual scan since scanning mutates internal state and we want 7590 // to atomically install the package and its children. 7591 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7592 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7593 scanFlags |= SCAN_CHECK_ONLY; 7594 } 7595 } else { 7596 scanFlags &= ~SCAN_CHECK_ONLY; 7597 } 7598 7599 final PackageParser.Package scannedPkg; 7600 try { 7601 // Scan the parent 7602 scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user); 7603 // Scan the children 7604 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7605 for (int i = 0; i < childCount; i++) { 7606 PackageParser.Package childPkg = pkg.childPackages.get(i); 7607 scanPackageLI(childPkg, parseFlags, 7608 scanFlags, currentTime, user); 7609 } 7610 } finally { 7611 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7612 } 7613 7614 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7615 return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user); 7616 } 7617 7618 return scannedPkg; 7619 } 7620 7621 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 7622 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7623 boolean success = false; 7624 try { 7625 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 7626 currentTime, user); 7627 success = true; 7628 return res; 7629 } finally { 7630 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 7631 // DELETE_DATA_ON_FAILURES is only used by frozen paths 7632 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 7633 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 7634 destroyAppProfilesLIF(pkg); 7635 } 7636 } 7637 } 7638 7639 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 7640 int scanFlags, long currentTime, UserHandle user) 7641 throws PackageManagerException { 7642 final File scanFile = new File(pkg.codePath); 7643 if (pkg.applicationInfo.getCodePath() == null || 7644 pkg.applicationInfo.getResourcePath() == null) { 7645 // Bail out. The resource and code paths haven't been set. 7646 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7647 "Code and resource paths haven't been set correctly"); 7648 } 7649 7650 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 7651 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 7652 } else { 7653 // Only allow system apps to be flagged as core apps. 7654 pkg.coreApp = false; 7655 } 7656 7657 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 7658 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7659 } 7660 7661 if (mCustomResolverComponentName != null && 7662 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 7663 setUpCustomResolverActivity(pkg); 7664 } 7665 7666 if (pkg.packageName.equals("android")) { 7667 synchronized (mPackages) { 7668 if (mAndroidApplication != null) { 7669 Slog.w(TAG, "*************************************************"); 7670 Slog.w(TAG, "Core android package being redefined. Skipping."); 7671 Slog.w(TAG, " file=" + scanFile); 7672 Slog.w(TAG, "*************************************************"); 7673 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7674 "Core android package being redefined. Skipping."); 7675 } 7676 7677 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7678 // Set up information for our fall-back user intent resolution activity. 7679 mPlatformPackage = pkg; 7680 pkg.mVersionCode = mSdkVersion; 7681 mAndroidApplication = pkg.applicationInfo; 7682 7683 if (!mResolverReplaced) { 7684 mResolveActivity.applicationInfo = mAndroidApplication; 7685 mResolveActivity.name = ResolverActivity.class.getName(); 7686 mResolveActivity.packageName = mAndroidApplication.packageName; 7687 mResolveActivity.processName = "system:ui"; 7688 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7689 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 7690 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 7691 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 7692 mResolveActivity.exported = true; 7693 mResolveActivity.enabled = true; 7694 mResolveInfo.activityInfo = mResolveActivity; 7695 mResolveInfo.priority = 0; 7696 mResolveInfo.preferredOrder = 0; 7697 mResolveInfo.match = 0; 7698 mResolveComponentName = new ComponentName( 7699 mAndroidApplication.packageName, mResolveActivity.name); 7700 } 7701 } 7702 } 7703 } 7704 7705 if (DEBUG_PACKAGE_SCANNING) { 7706 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7707 Log.d(TAG, "Scanning package " + pkg.packageName); 7708 } 7709 7710 synchronized (mPackages) { 7711 if (mPackages.containsKey(pkg.packageName) 7712 || mSharedLibraries.containsKey(pkg.packageName)) { 7713 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7714 "Application package " + pkg.packageName 7715 + " already installed. Skipping duplicate."); 7716 } 7717 7718 // If we're only installing presumed-existing packages, require that the 7719 // scanned APK is both already known and at the path previously established 7720 // for it. Previously unknown packages we pick up normally, but if we have an 7721 // a priori expectation about this package's install presence, enforce it. 7722 // With a singular exception for new system packages. When an OTA contains 7723 // a new system package, we allow the codepath to change from a system location 7724 // to the user-installed location. If we don't allow this change, any newer, 7725 // user-installed version of the application will be ignored. 7726 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 7727 if (mExpectingBetter.containsKey(pkg.packageName)) { 7728 logCriticalInfo(Log.WARN, 7729 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 7730 } else { 7731 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 7732 if (known != null) { 7733 if (DEBUG_PACKAGE_SCANNING) { 7734 Log.d(TAG, "Examining " + pkg.codePath 7735 + " and requiring known paths " + known.codePathString 7736 + " & " + known.resourcePathString); 7737 } 7738 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 7739 || !pkg.applicationInfo.getResourcePath().equals( 7740 known.resourcePathString)) { 7741 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 7742 "Application package " + pkg.packageName 7743 + " found at " + pkg.applicationInfo.getCodePath() 7744 + " but expected at " + known.codePathString 7745 + "; ignoring."); 7746 } 7747 } 7748 } 7749 } 7750 } 7751 7752 // Initialize package source and resource directories 7753 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 7754 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 7755 7756 SharedUserSetting suid = null; 7757 PackageSetting pkgSetting = null; 7758 7759 if (!isSystemApp(pkg)) { 7760 // Only system apps can use these features. 7761 pkg.mOriginalPackages = null; 7762 pkg.mRealPackage = null; 7763 pkg.mAdoptPermissions = null; 7764 } 7765 7766 // Getting the package setting may have a side-effect, so if we 7767 // are only checking if scan would succeed, stash a copy of the 7768 // old setting to restore at the end. 7769 PackageSetting nonMutatedPs = null; 7770 7771 // writer 7772 synchronized (mPackages) { 7773 if (pkg.mSharedUserId != null) { 7774 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 7775 if (suid == null) { 7776 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7777 "Creating application package " + pkg.packageName 7778 + " for shared user failed"); 7779 } 7780 if (DEBUG_PACKAGE_SCANNING) { 7781 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7782 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 7783 + "): packages=" + suid.packages); 7784 } 7785 } 7786 7787 // Check if we are renaming from an original package name. 7788 PackageSetting origPackage = null; 7789 String realName = null; 7790 if (pkg.mOriginalPackages != null) { 7791 // This package may need to be renamed to a previously 7792 // installed name. Let's check on that... 7793 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 7794 if (pkg.mOriginalPackages.contains(renamed)) { 7795 // This package had originally been installed as the 7796 // original name, and we have already taken care of 7797 // transitioning to the new one. Just update the new 7798 // one to continue using the old name. 7799 realName = pkg.mRealPackage; 7800 if (!pkg.packageName.equals(renamed)) { 7801 // Callers into this function may have already taken 7802 // care of renaming the package; only do it here if 7803 // it is not already done. 7804 pkg.setPackageName(renamed); 7805 } 7806 7807 } else { 7808 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 7809 if ((origPackage = mSettings.peekPackageLPr( 7810 pkg.mOriginalPackages.get(i))) != null) { 7811 // We do have the package already installed under its 7812 // original name... should we use it? 7813 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 7814 // New package is not compatible with original. 7815 origPackage = null; 7816 continue; 7817 } else if (origPackage.sharedUser != null) { 7818 // Make sure uid is compatible between packages. 7819 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 7820 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 7821 + " to " + pkg.packageName + ": old uid " 7822 + origPackage.sharedUser.name 7823 + " differs from " + pkg.mSharedUserId); 7824 origPackage = null; 7825 continue; 7826 } 7827 } else { 7828 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 7829 + pkg.packageName + " to old name " + origPackage.name); 7830 } 7831 break; 7832 } 7833 } 7834 } 7835 } 7836 7837 if (mTransferedPackages.contains(pkg.packageName)) { 7838 Slog.w(TAG, "Package " + pkg.packageName 7839 + " was transferred to another, but its .apk remains"); 7840 } 7841 7842 // See comments in nonMutatedPs declaration 7843 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7844 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 7845 if (foundPs != null) { 7846 nonMutatedPs = new PackageSetting(foundPs); 7847 } 7848 } 7849 7850 // Just create the setting, don't add it yet. For already existing packages 7851 // the PkgSetting exists already and doesn't have to be created. 7852 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 7853 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 7854 pkg.applicationInfo.primaryCpuAbi, 7855 pkg.applicationInfo.secondaryCpuAbi, 7856 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 7857 user, false); 7858 if (pkgSetting == null) { 7859 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7860 "Creating application package " + pkg.packageName + " failed"); 7861 } 7862 7863 if (pkgSetting.origPackage != null) { 7864 // If we are first transitioning from an original package, 7865 // fix up the new package's name now. We need to do this after 7866 // looking up the package under its new name, so getPackageLP 7867 // can take care of fiddling things correctly. 7868 pkg.setPackageName(origPackage.name); 7869 7870 // File a report about this. 7871 String msg = "New package " + pkgSetting.realName 7872 + " renamed to replace old package " + pkgSetting.name; 7873 reportSettingsProblem(Log.WARN, msg); 7874 7875 // Make a note of it. 7876 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7877 mTransferedPackages.add(origPackage.name); 7878 } 7879 7880 // No longer need to retain this. 7881 pkgSetting.origPackage = null; 7882 } 7883 7884 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 7885 // Make a note of it. 7886 mTransferedPackages.add(pkg.packageName); 7887 } 7888 7889 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 7890 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 7891 } 7892 7893 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7894 // Check all shared libraries and map to their actual file path. 7895 // We only do this here for apps not on a system dir, because those 7896 // are the only ones that can fail an install due to this. We 7897 // will take care of the system apps by updating all of their 7898 // library paths after the scan is done. 7899 updateSharedLibrariesLPw(pkg, null); 7900 } 7901 7902 if (mFoundPolicyFile) { 7903 SELinuxMMAC.assignSeinfoValue(pkg); 7904 } 7905 7906 pkg.applicationInfo.uid = pkgSetting.appId; 7907 pkg.mExtras = pkgSetting; 7908 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 7909 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 7910 // We just determined the app is signed correctly, so bring 7911 // over the latest parsed certs. 7912 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7913 } else { 7914 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7915 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7916 "Package " + pkg.packageName + " upgrade keys do not match the " 7917 + "previously installed version"); 7918 } else { 7919 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7920 String msg = "System package " + pkg.packageName 7921 + " signature changed; retaining data."; 7922 reportSettingsProblem(Log.WARN, msg); 7923 } 7924 } 7925 } else { 7926 try { 7927 verifySignaturesLP(pkgSetting, pkg); 7928 // We just determined the app is signed correctly, so bring 7929 // over the latest parsed certs. 7930 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7931 } catch (PackageManagerException e) { 7932 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7933 throw e; 7934 } 7935 // The signature has changed, but this package is in the system 7936 // image... let's recover! 7937 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7938 // However... if this package is part of a shared user, but it 7939 // doesn't match the signature of the shared user, let's fail. 7940 // What this means is that you can't change the signatures 7941 // associated with an overall shared user, which doesn't seem all 7942 // that unreasonable. 7943 if (pkgSetting.sharedUser != null) { 7944 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7945 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 7946 throw new PackageManagerException( 7947 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 7948 "Signature mismatch for shared user: " 7949 + pkgSetting.sharedUser); 7950 } 7951 } 7952 // File a report about this. 7953 String msg = "System package " + pkg.packageName 7954 + " signature changed; retaining data."; 7955 reportSettingsProblem(Log.WARN, msg); 7956 } 7957 } 7958 // Verify that this new package doesn't have any content providers 7959 // that conflict with existing packages. Only do this if the 7960 // package isn't already installed, since we don't want to break 7961 // things that are installed. 7962 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 7963 final int N = pkg.providers.size(); 7964 int i; 7965 for (i=0; i<N; i++) { 7966 PackageParser.Provider p = pkg.providers.get(i); 7967 if (p.info.authority != null) { 7968 String names[] = p.info.authority.split(";"); 7969 for (int j = 0; j < names.length; j++) { 7970 if (mProvidersByAuthority.containsKey(names[j])) { 7971 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7972 final String otherPackageName = 7973 ((other != null && other.getComponentName() != null) ? 7974 other.getComponentName().getPackageName() : "?"); 7975 throw new PackageManagerException( 7976 INSTALL_FAILED_CONFLICTING_PROVIDER, 7977 "Can't install because provider name " + names[j] 7978 + " (in package " + pkg.applicationInfo.packageName 7979 + ") is already used by " + otherPackageName); 7980 } 7981 } 7982 } 7983 } 7984 } 7985 7986 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 7987 // This package wants to adopt ownership of permissions from 7988 // another package. 7989 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 7990 final String origName = pkg.mAdoptPermissions.get(i); 7991 final PackageSetting orig = mSettings.peekPackageLPr(origName); 7992 if (orig != null) { 7993 if (verifyPackageUpdateLPr(orig, pkg)) { 7994 Slog.i(TAG, "Adopting permissions from " + origName + " to " 7995 + pkg.packageName); 7996 mSettings.transferPermissionsLPw(origName, pkg.packageName); 7997 } 7998 } 7999 } 8000 } 8001 } 8002 8003 final String pkgName = pkg.packageName; 8004 8005 final long scanFileTime = scanFile.lastModified(); 8006 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 8007 pkg.applicationInfo.processName = fixProcessName( 8008 pkg.applicationInfo.packageName, 8009 pkg.applicationInfo.processName, 8010 pkg.applicationInfo.uid); 8011 8012 if (pkg != mPlatformPackage) { 8013 // Get all of our default paths setup 8014 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 8015 } 8016 8017 final String path = scanFile.getPath(); 8018 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 8019 8020 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 8021 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 8022 8023 // Some system apps still use directory structure for native libraries 8024 // in which case we might end up not detecting abi solely based on apk 8025 // structure. Try to detect abi based on directory structure. 8026 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 8027 pkg.applicationInfo.primaryCpuAbi == null) { 8028 setBundledAppAbisAndRoots(pkg, pkgSetting); 8029 setNativeLibraryPaths(pkg); 8030 } 8031 8032 } else { 8033 if ((scanFlags & SCAN_MOVE) != 0) { 8034 // We haven't run dex-opt for this move (since we've moved the compiled output too) 8035 // but we already have this packages package info in the PackageSetting. We just 8036 // use that and derive the native library path based on the new codepath. 8037 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 8038 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 8039 } 8040 8041 // Set native library paths again. For moves, the path will be updated based on the 8042 // ABIs we've determined above. For non-moves, the path will be updated based on the 8043 // ABIs we determined during compilation, but the path will depend on the final 8044 // package path (after the rename away from the stage path). 8045 setNativeLibraryPaths(pkg); 8046 } 8047 8048 // This is a special case for the "system" package, where the ABI is 8049 // dictated by the zygote configuration (and init.rc). We should keep track 8050 // of this ABI so that we can deal with "normal" applications that run under 8051 // the same UID correctly. 8052 if (mPlatformPackage == pkg) { 8053 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 8054 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 8055 } 8056 8057 // If there's a mismatch between the abi-override in the package setting 8058 // and the abiOverride specified for the install. Warn about this because we 8059 // would've already compiled the app without taking the package setting into 8060 // account. 8061 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 8062 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 8063 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 8064 " for package " + pkg.packageName); 8065 } 8066 } 8067 8068 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8069 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8070 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 8071 8072 // Copy the derived override back to the parsed package, so that we can 8073 // update the package settings accordingly. 8074 pkg.cpuAbiOverride = cpuAbiOverride; 8075 8076 if (DEBUG_ABI_SELECTION) { 8077 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 8078 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 8079 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 8080 } 8081 8082 // Push the derived path down into PackageSettings so we know what to 8083 // clean up at uninstall time. 8084 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 8085 8086 if (DEBUG_ABI_SELECTION) { 8087 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 8088 " primary=" + pkg.applicationInfo.primaryCpuAbi + 8089 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 8090 } 8091 8092 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 8093 // We don't do this here during boot because we can do it all 8094 // at once after scanning all existing packages. 8095 // 8096 // We also do this *before* we perform dexopt on this package, so that 8097 // we can avoid redundant dexopts, and also to make sure we've got the 8098 // code and package path correct. 8099 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 8100 pkg, true /* boot complete */); 8101 } 8102 8103 if (mFactoryTest && pkg.requestedPermissions.contains( 8104 android.Manifest.permission.FACTORY_TEST)) { 8105 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 8106 } 8107 8108 ArrayList<PackageParser.Package> clientLibPkgs = null; 8109 8110 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8111 if (nonMutatedPs != null) { 8112 synchronized (mPackages) { 8113 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 8114 } 8115 } 8116 return pkg; 8117 } 8118 8119 // Only privileged apps and updated privileged apps can add child packages. 8120 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 8121 if ((parseFlags & PARSE_IS_PRIVILEGED) == 0) { 8122 throw new PackageManagerException("Only privileged apps and updated " 8123 + "privileged apps can add child packages. Ignoring package " 8124 + pkg.packageName); 8125 } 8126 final int childCount = pkg.childPackages.size(); 8127 for (int i = 0; i < childCount; i++) { 8128 PackageParser.Package childPkg = pkg.childPackages.get(i); 8129 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 8130 childPkg.packageName)) { 8131 throw new PackageManagerException("Cannot override a child package of " 8132 + "another disabled system app. Ignoring package " + pkg.packageName); 8133 } 8134 } 8135 } 8136 8137 // writer 8138 synchronized (mPackages) { 8139 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8140 // Only system apps can add new shared libraries. 8141 if (pkg.libraryNames != null) { 8142 for (int i=0; i<pkg.libraryNames.size(); i++) { 8143 String name = pkg.libraryNames.get(i); 8144 boolean allowed = false; 8145 if (pkg.isUpdatedSystemApp()) { 8146 // New library entries can only be added through the 8147 // system image. This is important to get rid of a lot 8148 // of nasty edge cases: for example if we allowed a non- 8149 // system update of the app to add a library, then uninstalling 8150 // the update would make the library go away, and assumptions 8151 // we made such as through app install filtering would now 8152 // have allowed apps on the device which aren't compatible 8153 // with it. Better to just have the restriction here, be 8154 // conservative, and create many fewer cases that can negatively 8155 // impact the user experience. 8156 final PackageSetting sysPs = mSettings 8157 .getDisabledSystemPkgLPr(pkg.packageName); 8158 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 8159 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 8160 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 8161 allowed = true; 8162 break; 8163 } 8164 } 8165 } 8166 } else { 8167 allowed = true; 8168 } 8169 if (allowed) { 8170 if (!mSharedLibraries.containsKey(name)) { 8171 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 8172 } else if (!name.equals(pkg.packageName)) { 8173 Slog.w(TAG, "Package " + pkg.packageName + " library " 8174 + name + " already exists; skipping"); 8175 } 8176 } else { 8177 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 8178 + name + " that is not declared on system image; skipping"); 8179 } 8180 } 8181 if ((scanFlags & SCAN_BOOTING) == 0) { 8182 // If we are not booting, we need to update any applications 8183 // that are clients of our shared library. If we are booting, 8184 // this will all be done once the scan is complete. 8185 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 8186 } 8187 } 8188 } 8189 } 8190 8191 if ((scanFlags & SCAN_BOOTING) != 0) { 8192 // No apps can run during boot scan, so they don't need to be frozen 8193 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 8194 // Caller asked to not kill app, so it's probably not frozen 8195 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 8196 // Caller asked us to ignore frozen check for some reason; they 8197 // probably didn't know the package name 8198 } else { 8199 // We're doing major surgery on this package, so it better be frozen 8200 // right now to keep it from launching 8201 checkPackageFrozen(pkgName); 8202 } 8203 8204 // Also need to kill any apps that are dependent on the library. 8205 if (clientLibPkgs != null) { 8206 for (int i=0; i<clientLibPkgs.size(); i++) { 8207 PackageParser.Package clientPkg = clientLibPkgs.get(i); 8208 killApplication(clientPkg.applicationInfo.packageName, 8209 clientPkg.applicationInfo.uid, "update lib"); 8210 } 8211 } 8212 8213 // Make sure we're not adding any bogus keyset info 8214 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8215 ksms.assertScannedPackageValid(pkg); 8216 8217 // writer 8218 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 8219 8220 boolean createIdmapFailed = false; 8221 synchronized (mPackages) { 8222 // We don't expect installation to fail beyond this point 8223 8224 // Add the new setting to mSettings 8225 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 8226 // Add the new setting to mPackages 8227 mPackages.put(pkg.applicationInfo.packageName, pkg); 8228 // Make sure we don't accidentally delete its data. 8229 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 8230 while (iter.hasNext()) { 8231 PackageCleanItem item = iter.next(); 8232 if (pkgName.equals(item.packageName)) { 8233 iter.remove(); 8234 } 8235 } 8236 8237 // Take care of first install / last update times. 8238 if (currentTime != 0) { 8239 if (pkgSetting.firstInstallTime == 0) { 8240 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8241 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 8242 pkgSetting.lastUpdateTime = currentTime; 8243 } 8244 } else if (pkgSetting.firstInstallTime == 0) { 8245 // We need *something*. Take time time stamp of the file. 8246 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8247 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8248 if (scanFileTime != pkgSetting.timeStamp) { 8249 // A package on the system image has changed; consider this 8250 // to be an update. 8251 pkgSetting.lastUpdateTime = scanFileTime; 8252 } 8253 } 8254 8255 // Add the package's KeySets to the global KeySetManagerService 8256 ksms.addScannedPackageLPw(pkg); 8257 8258 int N = pkg.providers.size(); 8259 StringBuilder r = null; 8260 int i; 8261 for (i=0; i<N; i++) { 8262 PackageParser.Provider p = pkg.providers.get(i); 8263 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 8264 p.info.processName, pkg.applicationInfo.uid); 8265 mProviders.addProvider(p); 8266 p.syncable = p.info.isSyncable; 8267 if (p.info.authority != null) { 8268 String names[] = p.info.authority.split(";"); 8269 p.info.authority = null; 8270 for (int j = 0; j < names.length; j++) { 8271 if (j == 1 && p.syncable) { 8272 // We only want the first authority for a provider to possibly be 8273 // syncable, so if we already added this provider using a different 8274 // authority clear the syncable flag. We copy the provider before 8275 // changing it because the mProviders object contains a reference 8276 // to a provider that we don't want to change. 8277 // Only do this for the second authority since the resulting provider 8278 // object can be the same for all future authorities for this provider. 8279 p = new PackageParser.Provider(p); 8280 p.syncable = false; 8281 } 8282 if (!mProvidersByAuthority.containsKey(names[j])) { 8283 mProvidersByAuthority.put(names[j], p); 8284 if (p.info.authority == null) { 8285 p.info.authority = names[j]; 8286 } else { 8287 p.info.authority = p.info.authority + ";" + names[j]; 8288 } 8289 if (DEBUG_PACKAGE_SCANNING) { 8290 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 8291 Log.d(TAG, "Registered content provider: " + names[j] 8292 + ", className = " + p.info.name + ", isSyncable = " 8293 + p.info.isSyncable); 8294 } 8295 } else { 8296 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8297 Slog.w(TAG, "Skipping provider name " + names[j] + 8298 " (in package " + pkg.applicationInfo.packageName + 8299 "): name already used by " 8300 + ((other != null && other.getComponentName() != null) 8301 ? other.getComponentName().getPackageName() : "?")); 8302 } 8303 } 8304 } 8305 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8306 if (r == null) { 8307 r = new StringBuilder(256); 8308 } else { 8309 r.append(' '); 8310 } 8311 r.append(p.info.name); 8312 } 8313 } 8314 if (r != null) { 8315 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8316 } 8317 8318 N = pkg.services.size(); 8319 r = null; 8320 for (i=0; i<N; i++) { 8321 PackageParser.Service s = pkg.services.get(i); 8322 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8323 s.info.processName, pkg.applicationInfo.uid); 8324 mServices.addService(s); 8325 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8326 if (r == null) { 8327 r = new StringBuilder(256); 8328 } else { 8329 r.append(' '); 8330 } 8331 r.append(s.info.name); 8332 } 8333 } 8334 if (r != null) { 8335 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8336 } 8337 8338 N = pkg.receivers.size(); 8339 r = null; 8340 for (i=0; i<N; i++) { 8341 PackageParser.Activity a = pkg.receivers.get(i); 8342 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8343 a.info.processName, pkg.applicationInfo.uid); 8344 mReceivers.addActivity(a, "receiver"); 8345 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8346 if (r == null) { 8347 r = new StringBuilder(256); 8348 } else { 8349 r.append(' '); 8350 } 8351 r.append(a.info.name); 8352 } 8353 } 8354 if (r != null) { 8355 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8356 } 8357 8358 N = pkg.activities.size(); 8359 r = null; 8360 for (i=0; i<N; i++) { 8361 PackageParser.Activity a = pkg.activities.get(i); 8362 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8363 a.info.processName, pkg.applicationInfo.uid); 8364 mActivities.addActivity(a, "activity"); 8365 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8366 if (r == null) { 8367 r = new StringBuilder(256); 8368 } else { 8369 r.append(' '); 8370 } 8371 r.append(a.info.name); 8372 } 8373 } 8374 if (r != null) { 8375 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8376 } 8377 8378 N = pkg.permissionGroups.size(); 8379 r = null; 8380 for (i=0; i<N; i++) { 8381 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8382 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8383 if (cur == null) { 8384 mPermissionGroups.put(pg.info.name, pg); 8385 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8386 if (r == null) { 8387 r = new StringBuilder(256); 8388 } else { 8389 r.append(' '); 8390 } 8391 r.append(pg.info.name); 8392 } 8393 } else { 8394 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8395 + pg.info.packageName + " ignored: original from " 8396 + cur.info.packageName); 8397 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8398 if (r == null) { 8399 r = new StringBuilder(256); 8400 } else { 8401 r.append(' '); 8402 } 8403 r.append("DUP:"); 8404 r.append(pg.info.name); 8405 } 8406 } 8407 } 8408 if (r != null) { 8409 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8410 } 8411 8412 N = pkg.permissions.size(); 8413 r = null; 8414 for (i=0; i<N; i++) { 8415 PackageParser.Permission p = pkg.permissions.get(i); 8416 8417 // Assume by default that we did not install this permission into the system. 8418 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8419 8420 // Now that permission groups have a special meaning, we ignore permission 8421 // groups for legacy apps to prevent unexpected behavior. In particular, 8422 // permissions for one app being granted to someone just becase they happen 8423 // to be in a group defined by another app (before this had no implications). 8424 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8425 p.group = mPermissionGroups.get(p.info.group); 8426 // Warn for a permission in an unknown group. 8427 if (p.info.group != null && p.group == null) { 8428 Slog.w(TAG, "Permission " + p.info.name + " from package " 8429 + p.info.packageName + " in an unknown group " + p.info.group); 8430 } 8431 } 8432 8433 ArrayMap<String, BasePermission> permissionMap = 8434 p.tree ? mSettings.mPermissionTrees 8435 : mSettings.mPermissions; 8436 BasePermission bp = permissionMap.get(p.info.name); 8437 8438 // Allow system apps to redefine non-system permissions 8439 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8440 final boolean currentOwnerIsSystem = (bp.perm != null 8441 && isSystemApp(bp.perm.owner)); 8442 if (isSystemApp(p.owner)) { 8443 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8444 // It's a built-in permission and no owner, take ownership now 8445 bp.packageSetting = pkgSetting; 8446 bp.perm = p; 8447 bp.uid = pkg.applicationInfo.uid; 8448 bp.sourcePackage = p.info.packageName; 8449 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8450 } else if (!currentOwnerIsSystem) { 8451 String msg = "New decl " + p.owner + " of permission " 8452 + p.info.name + " is system; overriding " + bp.sourcePackage; 8453 reportSettingsProblem(Log.WARN, msg); 8454 bp = null; 8455 } 8456 } 8457 } 8458 8459 if (bp == null) { 8460 bp = new BasePermission(p.info.name, p.info.packageName, 8461 BasePermission.TYPE_NORMAL); 8462 permissionMap.put(p.info.name, bp); 8463 } 8464 8465 if (bp.perm == null) { 8466 if (bp.sourcePackage == null 8467 || bp.sourcePackage.equals(p.info.packageName)) { 8468 BasePermission tree = findPermissionTreeLP(p.info.name); 8469 if (tree == null 8470 || tree.sourcePackage.equals(p.info.packageName)) { 8471 bp.packageSetting = pkgSetting; 8472 bp.perm = p; 8473 bp.uid = pkg.applicationInfo.uid; 8474 bp.sourcePackage = p.info.packageName; 8475 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8476 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8477 if (r == null) { 8478 r = new StringBuilder(256); 8479 } else { 8480 r.append(' '); 8481 } 8482 r.append(p.info.name); 8483 } 8484 } else { 8485 Slog.w(TAG, "Permission " + p.info.name + " from package " 8486 + p.info.packageName + " ignored: base tree " 8487 + tree.name + " is from package " 8488 + tree.sourcePackage); 8489 } 8490 } else { 8491 Slog.w(TAG, "Permission " + p.info.name + " from package " 8492 + p.info.packageName + " ignored: original from " 8493 + bp.sourcePackage); 8494 } 8495 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8496 if (r == null) { 8497 r = new StringBuilder(256); 8498 } else { 8499 r.append(' '); 8500 } 8501 r.append("DUP:"); 8502 r.append(p.info.name); 8503 } 8504 if (bp.perm == p) { 8505 bp.protectionLevel = p.info.protectionLevel; 8506 } 8507 } 8508 8509 if (r != null) { 8510 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 8511 } 8512 8513 N = pkg.instrumentation.size(); 8514 r = null; 8515 for (i=0; i<N; i++) { 8516 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8517 a.info.packageName = pkg.applicationInfo.packageName; 8518 a.info.sourceDir = pkg.applicationInfo.sourceDir; 8519 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 8520 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 8521 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 8522 a.info.dataDir = pkg.applicationInfo.dataDir; 8523 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 8524 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 8525 8526 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 8527 // need other information about the application, like the ABI and what not ? 8528 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 8529 mInstrumentation.put(a.getComponentName(), a); 8530 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8531 if (r == null) { 8532 r = new StringBuilder(256); 8533 } else { 8534 r.append(' '); 8535 } 8536 r.append(a.info.name); 8537 } 8538 } 8539 if (r != null) { 8540 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 8541 } 8542 8543 if (pkg.protectedBroadcasts != null) { 8544 N = pkg.protectedBroadcasts.size(); 8545 for (i=0; i<N; i++) { 8546 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 8547 } 8548 } 8549 8550 pkgSetting.setTimeStamp(scanFileTime); 8551 8552 // Create idmap files for pairs of (packages, overlay packages). 8553 // Note: "android", ie framework-res.apk, is handled by native layers. 8554 if (pkg.mOverlayTarget != null) { 8555 // This is an overlay package. 8556 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 8557 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 8558 mOverlays.put(pkg.mOverlayTarget, 8559 new ArrayMap<String, PackageParser.Package>()); 8560 } 8561 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 8562 map.put(pkg.packageName, pkg); 8563 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 8564 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 8565 createIdmapFailed = true; 8566 } 8567 } 8568 } else if (mOverlays.containsKey(pkg.packageName) && 8569 !pkg.packageName.equals("android")) { 8570 // This is a regular package, with one or more known overlay packages. 8571 createIdmapsForPackageLI(pkg); 8572 } 8573 } 8574 8575 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8576 8577 if (createIdmapFailed) { 8578 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8579 "scanPackageLI failed to createIdmap"); 8580 } 8581 return pkg; 8582 } 8583 8584 /** 8585 * Derive the ABI of a non-system package located at {@code scanFile}. This information 8586 * is derived purely on the basis of the contents of {@code scanFile} and 8587 * {@code cpuAbiOverride}. 8588 * 8589 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 8590 */ 8591 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 8592 String cpuAbiOverride, boolean extractLibs) 8593 throws PackageManagerException { 8594 // TODO: We can probably be smarter about this stuff. For installed apps, 8595 // we can calculate this information at install time once and for all. For 8596 // system apps, we can probably assume that this information doesn't change 8597 // after the first boot scan. As things stand, we do lots of unnecessary work. 8598 8599 // Give ourselves some initial paths; we'll come back for another 8600 // pass once we've determined ABI below. 8601 setNativeLibraryPaths(pkg); 8602 8603 // We would never need to extract libs for forward-locked and external packages, 8604 // since the container service will do it for us. We shouldn't attempt to 8605 // extract libs from system app when it was not updated. 8606 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 8607 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 8608 extractLibs = false; 8609 } 8610 8611 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 8612 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 8613 8614 NativeLibraryHelper.Handle handle = null; 8615 try { 8616 handle = NativeLibraryHelper.Handle.create(pkg); 8617 // TODO(multiArch): This can be null for apps that didn't go through the 8618 // usual installation process. We can calculate it again, like we 8619 // do during install time. 8620 // 8621 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 8622 // unnecessary. 8623 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 8624 8625 // Null out the abis so that they can be recalculated. 8626 pkg.applicationInfo.primaryCpuAbi = null; 8627 pkg.applicationInfo.secondaryCpuAbi = null; 8628 if (isMultiArch(pkg.applicationInfo)) { 8629 // Warn if we've set an abiOverride for multi-lib packages.. 8630 // By definition, we need to copy both 32 and 64 bit libraries for 8631 // such packages. 8632 if (pkg.cpuAbiOverride != null 8633 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 8634 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 8635 } 8636 8637 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 8638 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 8639 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 8640 if (extractLibs) { 8641 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8642 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 8643 useIsaSpecificSubdirs); 8644 } else { 8645 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 8646 } 8647 } 8648 8649 maybeThrowExceptionForMultiArchCopy( 8650 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 8651 8652 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 8653 if (extractLibs) { 8654 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8655 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 8656 useIsaSpecificSubdirs); 8657 } else { 8658 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 8659 } 8660 } 8661 8662 maybeThrowExceptionForMultiArchCopy( 8663 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 8664 8665 if (abi64 >= 0) { 8666 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 8667 } 8668 8669 if (abi32 >= 0) { 8670 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 8671 if (abi64 >= 0) { 8672 if (pkg.use32bitAbi) { 8673 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 8674 pkg.applicationInfo.primaryCpuAbi = abi; 8675 } else { 8676 pkg.applicationInfo.secondaryCpuAbi = abi; 8677 } 8678 } else { 8679 pkg.applicationInfo.primaryCpuAbi = abi; 8680 } 8681 } 8682 8683 } else { 8684 String[] abiList = (cpuAbiOverride != null) ? 8685 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 8686 8687 // Enable gross and lame hacks for apps that are built with old 8688 // SDK tools. We must scan their APKs for renderscript bitcode and 8689 // not launch them if it's present. Don't bother checking on devices 8690 // that don't have 64 bit support. 8691 boolean needsRenderScriptOverride = false; 8692 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 8693 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 8694 abiList = Build.SUPPORTED_32_BIT_ABIS; 8695 needsRenderScriptOverride = true; 8696 } 8697 8698 final int copyRet; 8699 if (extractLibs) { 8700 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8701 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 8702 } else { 8703 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 8704 } 8705 8706 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 8707 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 8708 "Error unpackaging native libs for app, errorCode=" + copyRet); 8709 } 8710 8711 if (copyRet >= 0) { 8712 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 8713 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 8714 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 8715 } else if (needsRenderScriptOverride) { 8716 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 8717 } 8718 } 8719 } catch (IOException ioe) { 8720 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 8721 } finally { 8722 IoUtils.closeQuietly(handle); 8723 } 8724 8725 // Now that we've calculated the ABIs and determined if it's an internal app, 8726 // we will go ahead and populate the nativeLibraryPath. 8727 setNativeLibraryPaths(pkg); 8728 } 8729 8730 /** 8731 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 8732 * i.e, so that all packages can be run inside a single process if required. 8733 * 8734 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 8735 * this function will either try and make the ABI for all packages in {@code packagesForUser} 8736 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 8737 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 8738 * updating a package that belongs to a shared user. 8739 * 8740 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 8741 * adds unnecessary complexity. 8742 */ 8743 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 8744 PackageParser.Package scannedPackage, boolean bootComplete) { 8745 String requiredInstructionSet = null; 8746 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 8747 requiredInstructionSet = VMRuntime.getInstructionSet( 8748 scannedPackage.applicationInfo.primaryCpuAbi); 8749 } 8750 8751 PackageSetting requirer = null; 8752 for (PackageSetting ps : packagesForUser) { 8753 // If packagesForUser contains scannedPackage, we skip it. This will happen 8754 // when scannedPackage is an update of an existing package. Without this check, 8755 // we will never be able to change the ABI of any package belonging to a shared 8756 // user, even if it's compatible with other packages. 8757 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8758 if (ps.primaryCpuAbiString == null) { 8759 continue; 8760 } 8761 8762 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 8763 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 8764 // We have a mismatch between instruction sets (say arm vs arm64) warn about 8765 // this but there's not much we can do. 8766 String errorMessage = "Instruction set mismatch, " 8767 + ((requirer == null) ? "[caller]" : requirer) 8768 + " requires " + requiredInstructionSet + " whereas " + ps 8769 + " requires " + instructionSet; 8770 Slog.w(TAG, errorMessage); 8771 } 8772 8773 if (requiredInstructionSet == null) { 8774 requiredInstructionSet = instructionSet; 8775 requirer = ps; 8776 } 8777 } 8778 } 8779 8780 if (requiredInstructionSet != null) { 8781 String adjustedAbi; 8782 if (requirer != null) { 8783 // requirer != null implies that either scannedPackage was null or that scannedPackage 8784 // did not require an ABI, in which case we have to adjust scannedPackage to match 8785 // the ABI of the set (which is the same as requirer's ABI) 8786 adjustedAbi = requirer.primaryCpuAbiString; 8787 if (scannedPackage != null) { 8788 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 8789 } 8790 } else { 8791 // requirer == null implies that we're updating all ABIs in the set to 8792 // match scannedPackage. 8793 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 8794 } 8795 8796 for (PackageSetting ps : packagesForUser) { 8797 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8798 if (ps.primaryCpuAbiString != null) { 8799 continue; 8800 } 8801 8802 ps.primaryCpuAbiString = adjustedAbi; 8803 if (ps.pkg != null && ps.pkg.applicationInfo != null && 8804 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 8805 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 8806 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 8807 + " (requirer=" 8808 + (requirer == null ? "null" : requirer.pkg.packageName) 8809 + ", scannedPackage=" 8810 + (scannedPackage != null ? scannedPackage.packageName : "null") 8811 + ")"); 8812 try { 8813 mInstaller.rmdex(ps.codePathString, 8814 getDexCodeInstructionSet(getPreferredInstructionSet())); 8815 } catch (InstallerException ignored) { 8816 } 8817 } 8818 } 8819 } 8820 } 8821 } 8822 8823 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 8824 synchronized (mPackages) { 8825 mResolverReplaced = true; 8826 // Set up information for custom user intent resolution activity. 8827 mResolveActivity.applicationInfo = pkg.applicationInfo; 8828 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 8829 mResolveActivity.packageName = pkg.applicationInfo.packageName; 8830 mResolveActivity.processName = pkg.applicationInfo.packageName; 8831 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8832 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8833 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8834 mResolveActivity.theme = 0; 8835 mResolveActivity.exported = true; 8836 mResolveActivity.enabled = true; 8837 mResolveInfo.activityInfo = mResolveActivity; 8838 mResolveInfo.priority = 0; 8839 mResolveInfo.preferredOrder = 0; 8840 mResolveInfo.match = 0; 8841 mResolveComponentName = mCustomResolverComponentName; 8842 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 8843 mResolveComponentName); 8844 } 8845 } 8846 8847 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 8848 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 8849 8850 // Set up information for ephemeral installer activity 8851 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 8852 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 8853 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 8854 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 8855 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8856 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8857 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8858 mEphemeralInstallerActivity.theme = 0; 8859 mEphemeralInstallerActivity.exported = true; 8860 mEphemeralInstallerActivity.enabled = true; 8861 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 8862 mEphemeralInstallerInfo.priority = 0; 8863 mEphemeralInstallerInfo.preferredOrder = 0; 8864 mEphemeralInstallerInfo.match = 0; 8865 8866 if (DEBUG_EPHEMERAL) { 8867 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 8868 } 8869 } 8870 8871 private static String calculateBundledApkRoot(final String codePathString) { 8872 final File codePath = new File(codePathString); 8873 final File codeRoot; 8874 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 8875 codeRoot = Environment.getRootDirectory(); 8876 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 8877 codeRoot = Environment.getOemDirectory(); 8878 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 8879 codeRoot = Environment.getVendorDirectory(); 8880 } else { 8881 // Unrecognized code path; take its top real segment as the apk root: 8882 // e.g. /something/app/blah.apk => /something 8883 try { 8884 File f = codePath.getCanonicalFile(); 8885 File parent = f.getParentFile(); // non-null because codePath is a file 8886 File tmp; 8887 while ((tmp = parent.getParentFile()) != null) { 8888 f = parent; 8889 parent = tmp; 8890 } 8891 codeRoot = f; 8892 Slog.w(TAG, "Unrecognized code path " 8893 + codePath + " - using " + codeRoot); 8894 } catch (IOException e) { 8895 // Can't canonicalize the code path -- shenanigans? 8896 Slog.w(TAG, "Can't canonicalize code path " + codePath); 8897 return Environment.getRootDirectory().getPath(); 8898 } 8899 } 8900 return codeRoot.getPath(); 8901 } 8902 8903 /** 8904 * Derive and set the location of native libraries for the given package, 8905 * which varies depending on where and how the package was installed. 8906 */ 8907 private void setNativeLibraryPaths(PackageParser.Package pkg) { 8908 final ApplicationInfo info = pkg.applicationInfo; 8909 final String codePath = pkg.codePath; 8910 final File codeFile = new File(codePath); 8911 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 8912 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 8913 8914 info.nativeLibraryRootDir = null; 8915 info.nativeLibraryRootRequiresIsa = false; 8916 info.nativeLibraryDir = null; 8917 info.secondaryNativeLibraryDir = null; 8918 8919 if (isApkFile(codeFile)) { 8920 // Monolithic install 8921 if (bundledApp) { 8922 // If "/system/lib64/apkname" exists, assume that is the per-package 8923 // native library directory to use; otherwise use "/system/lib/apkname". 8924 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 8925 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 8926 getPrimaryInstructionSet(info)); 8927 8928 // This is a bundled system app so choose the path based on the ABI. 8929 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 8930 // is just the default path. 8931 final String apkName = deriveCodePathName(codePath); 8932 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 8933 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 8934 apkName).getAbsolutePath(); 8935 8936 if (info.secondaryCpuAbi != null) { 8937 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 8938 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 8939 secondaryLibDir, apkName).getAbsolutePath(); 8940 } 8941 } else if (asecApp) { 8942 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 8943 .getAbsolutePath(); 8944 } else { 8945 final String apkName = deriveCodePathName(codePath); 8946 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 8947 .getAbsolutePath(); 8948 } 8949 8950 info.nativeLibraryRootRequiresIsa = false; 8951 info.nativeLibraryDir = info.nativeLibraryRootDir; 8952 } else { 8953 // Cluster install 8954 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 8955 info.nativeLibraryRootRequiresIsa = true; 8956 8957 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 8958 getPrimaryInstructionSet(info)).getAbsolutePath(); 8959 8960 if (info.secondaryCpuAbi != null) { 8961 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 8962 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 8963 } 8964 } 8965 } 8966 8967 /** 8968 * Calculate the abis and roots for a bundled app. These can uniquely 8969 * be determined from the contents of the system partition, i.e whether 8970 * it contains 64 or 32 bit shared libraries etc. We do not validate any 8971 * of this information, and instead assume that the system was built 8972 * sensibly. 8973 */ 8974 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 8975 PackageSetting pkgSetting) { 8976 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 8977 8978 // If "/system/lib64/apkname" exists, assume that is the per-package 8979 // native library directory to use; otherwise use "/system/lib/apkname". 8980 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 8981 setBundledAppAbi(pkg, apkRoot, apkName); 8982 // pkgSetting might be null during rescan following uninstall of updates 8983 // to a bundled app, so accommodate that possibility. The settings in 8984 // that case will be established later from the parsed package. 8985 // 8986 // If the settings aren't null, sync them up with what we've just derived. 8987 // note that apkRoot isn't stored in the package settings. 8988 if (pkgSetting != null) { 8989 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8990 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8991 } 8992 } 8993 8994 /** 8995 * Deduces the ABI of a bundled app and sets the relevant fields on the 8996 * parsed pkg object. 8997 * 8998 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 8999 * under which system libraries are installed. 9000 * @param apkName the name of the installed package. 9001 */ 9002 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 9003 final File codeFile = new File(pkg.codePath); 9004 9005 final boolean has64BitLibs; 9006 final boolean has32BitLibs; 9007 if (isApkFile(codeFile)) { 9008 // Monolithic install 9009 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 9010 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 9011 } else { 9012 // Cluster install 9013 final File rootDir = new File(codeFile, LIB_DIR_NAME); 9014 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 9015 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 9016 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 9017 has64BitLibs = (new File(rootDir, isa)).exists(); 9018 } else { 9019 has64BitLibs = false; 9020 } 9021 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 9022 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 9023 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 9024 has32BitLibs = (new File(rootDir, isa)).exists(); 9025 } else { 9026 has32BitLibs = false; 9027 } 9028 } 9029 9030 if (has64BitLibs && !has32BitLibs) { 9031 // The package has 64 bit libs, but not 32 bit libs. Its primary 9032 // ABI should be 64 bit. We can safely assume here that the bundled 9033 // native libraries correspond to the most preferred ABI in the list. 9034 9035 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9036 pkg.applicationInfo.secondaryCpuAbi = null; 9037 } else if (has32BitLibs && !has64BitLibs) { 9038 // The package has 32 bit libs but not 64 bit libs. Its primary 9039 // ABI should be 32 bit. 9040 9041 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9042 pkg.applicationInfo.secondaryCpuAbi = null; 9043 } else if (has32BitLibs && has64BitLibs) { 9044 // The application has both 64 and 32 bit bundled libraries. We check 9045 // here that the app declares multiArch support, and warn if it doesn't. 9046 // 9047 // We will be lenient here and record both ABIs. The primary will be the 9048 // ABI that's higher on the list, i.e, a device that's configured to prefer 9049 // 64 bit apps will see a 64 bit primary ABI, 9050 9051 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 9052 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 9053 } 9054 9055 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 9056 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9057 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9058 } else { 9059 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9060 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9061 } 9062 } else { 9063 pkg.applicationInfo.primaryCpuAbi = null; 9064 pkg.applicationInfo.secondaryCpuAbi = null; 9065 } 9066 } 9067 9068 private void killApplication(String pkgName, int appId, String reason) { 9069 // Request the ActivityManager to kill the process(only for existing packages) 9070 // so that we do not end up in a confused state while the user is still using the older 9071 // version of the application while the new one gets installed. 9072 final long token = Binder.clearCallingIdentity(); 9073 try { 9074 IActivityManager am = ActivityManagerNative.getDefault(); 9075 if (am != null) { 9076 try { 9077 am.killApplicationWithAppId(pkgName, appId, reason); 9078 } catch (RemoteException e) { 9079 } 9080 } 9081 } finally { 9082 Binder.restoreCallingIdentity(token); 9083 } 9084 } 9085 9086 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 9087 // Remove the parent package setting 9088 PackageSetting ps = (PackageSetting) pkg.mExtras; 9089 if (ps != null) { 9090 removePackageLI(ps, chatty); 9091 } 9092 // Remove the child package setting 9093 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9094 for (int i = 0; i < childCount; i++) { 9095 PackageParser.Package childPkg = pkg.childPackages.get(i); 9096 ps = (PackageSetting) childPkg.mExtras; 9097 if (ps != null) { 9098 removePackageLI(ps, chatty); 9099 } 9100 } 9101 } 9102 9103 void removePackageLI(PackageSetting ps, boolean chatty) { 9104 if (DEBUG_INSTALL) { 9105 if (chatty) 9106 Log.d(TAG, "Removing package " + ps.name); 9107 } 9108 9109 // writer 9110 synchronized (mPackages) { 9111 mPackages.remove(ps.name); 9112 final PackageParser.Package pkg = ps.pkg; 9113 if (pkg != null) { 9114 cleanPackageDataStructuresLILPw(pkg, chatty); 9115 } 9116 } 9117 } 9118 9119 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 9120 if (DEBUG_INSTALL) { 9121 if (chatty) 9122 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 9123 } 9124 9125 // writer 9126 synchronized (mPackages) { 9127 // Remove the parent package 9128 mPackages.remove(pkg.applicationInfo.packageName); 9129 cleanPackageDataStructuresLILPw(pkg, chatty); 9130 9131 // Remove the child packages 9132 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9133 for (int i = 0; i < childCount; i++) { 9134 PackageParser.Package childPkg = pkg.childPackages.get(i); 9135 mPackages.remove(childPkg.applicationInfo.packageName); 9136 cleanPackageDataStructuresLILPw(childPkg, chatty); 9137 } 9138 } 9139 } 9140 9141 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 9142 int N = pkg.providers.size(); 9143 StringBuilder r = null; 9144 int i; 9145 for (i=0; i<N; i++) { 9146 PackageParser.Provider p = pkg.providers.get(i); 9147 mProviders.removeProvider(p); 9148 if (p.info.authority == null) { 9149 9150 /* There was another ContentProvider with this authority when 9151 * this app was installed so this authority is null, 9152 * Ignore it as we don't have to unregister the provider. 9153 */ 9154 continue; 9155 } 9156 String names[] = p.info.authority.split(";"); 9157 for (int j = 0; j < names.length; j++) { 9158 if (mProvidersByAuthority.get(names[j]) == p) { 9159 mProvidersByAuthority.remove(names[j]); 9160 if (DEBUG_REMOVE) { 9161 if (chatty) 9162 Log.d(TAG, "Unregistered content provider: " + names[j] 9163 + ", className = " + p.info.name + ", isSyncable = " 9164 + p.info.isSyncable); 9165 } 9166 } 9167 } 9168 if (DEBUG_REMOVE && chatty) { 9169 if (r == null) { 9170 r = new StringBuilder(256); 9171 } else { 9172 r.append(' '); 9173 } 9174 r.append(p.info.name); 9175 } 9176 } 9177 if (r != null) { 9178 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 9179 } 9180 9181 N = pkg.services.size(); 9182 r = null; 9183 for (i=0; i<N; i++) { 9184 PackageParser.Service s = pkg.services.get(i); 9185 mServices.removeService(s); 9186 if (chatty) { 9187 if (r == null) { 9188 r = new StringBuilder(256); 9189 } else { 9190 r.append(' '); 9191 } 9192 r.append(s.info.name); 9193 } 9194 } 9195 if (r != null) { 9196 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 9197 } 9198 9199 N = pkg.receivers.size(); 9200 r = null; 9201 for (i=0; i<N; i++) { 9202 PackageParser.Activity a = pkg.receivers.get(i); 9203 mReceivers.removeActivity(a, "receiver"); 9204 if (DEBUG_REMOVE && chatty) { 9205 if (r == null) { 9206 r = new StringBuilder(256); 9207 } else { 9208 r.append(' '); 9209 } 9210 r.append(a.info.name); 9211 } 9212 } 9213 if (r != null) { 9214 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 9215 } 9216 9217 N = pkg.activities.size(); 9218 r = null; 9219 for (i=0; i<N; i++) { 9220 PackageParser.Activity a = pkg.activities.get(i); 9221 mActivities.removeActivity(a, "activity"); 9222 if (DEBUG_REMOVE && chatty) { 9223 if (r == null) { 9224 r = new StringBuilder(256); 9225 } else { 9226 r.append(' '); 9227 } 9228 r.append(a.info.name); 9229 } 9230 } 9231 if (r != null) { 9232 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 9233 } 9234 9235 N = pkg.permissions.size(); 9236 r = null; 9237 for (i=0; i<N; i++) { 9238 PackageParser.Permission p = pkg.permissions.get(i); 9239 BasePermission bp = mSettings.mPermissions.get(p.info.name); 9240 if (bp == null) { 9241 bp = mSettings.mPermissionTrees.get(p.info.name); 9242 } 9243 if (bp != null && bp.perm == p) { 9244 bp.perm = null; 9245 if (DEBUG_REMOVE && chatty) { 9246 if (r == null) { 9247 r = new StringBuilder(256); 9248 } else { 9249 r.append(' '); 9250 } 9251 r.append(p.info.name); 9252 } 9253 } 9254 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9255 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 9256 if (appOpPkgs != null) { 9257 appOpPkgs.remove(pkg.packageName); 9258 } 9259 } 9260 } 9261 if (r != null) { 9262 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9263 } 9264 9265 N = pkg.requestedPermissions.size(); 9266 r = null; 9267 for (i=0; i<N; i++) { 9268 String perm = pkg.requestedPermissions.get(i); 9269 BasePermission bp = mSettings.mPermissions.get(perm); 9270 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9271 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 9272 if (appOpPkgs != null) { 9273 appOpPkgs.remove(pkg.packageName); 9274 if (appOpPkgs.isEmpty()) { 9275 mAppOpPermissionPackages.remove(perm); 9276 } 9277 } 9278 } 9279 } 9280 if (r != null) { 9281 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9282 } 9283 9284 N = pkg.instrumentation.size(); 9285 r = null; 9286 for (i=0; i<N; i++) { 9287 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9288 mInstrumentation.remove(a.getComponentName()); 9289 if (DEBUG_REMOVE && chatty) { 9290 if (r == null) { 9291 r = new StringBuilder(256); 9292 } else { 9293 r.append(' '); 9294 } 9295 r.append(a.info.name); 9296 } 9297 } 9298 if (r != null) { 9299 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9300 } 9301 9302 r = null; 9303 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9304 // Only system apps can hold shared libraries. 9305 if (pkg.libraryNames != null) { 9306 for (i=0; i<pkg.libraryNames.size(); i++) { 9307 String name = pkg.libraryNames.get(i); 9308 SharedLibraryEntry cur = mSharedLibraries.get(name); 9309 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9310 mSharedLibraries.remove(name); 9311 if (DEBUG_REMOVE && chatty) { 9312 if (r == null) { 9313 r = new StringBuilder(256); 9314 } else { 9315 r.append(' '); 9316 } 9317 r.append(name); 9318 } 9319 } 9320 } 9321 } 9322 } 9323 if (r != null) { 9324 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9325 } 9326 } 9327 9328 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9329 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9330 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9331 return true; 9332 } 9333 } 9334 return false; 9335 } 9336 9337 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9338 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9339 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9340 9341 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9342 // Update the parent permissions 9343 updatePermissionsLPw(pkg.packageName, pkg, flags); 9344 // Update the child permissions 9345 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9346 for (int i = 0; i < childCount; i++) { 9347 PackageParser.Package childPkg = pkg.childPackages.get(i); 9348 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9349 } 9350 } 9351 9352 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9353 int flags) { 9354 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9355 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9356 } 9357 9358 private void updatePermissionsLPw(String changingPkg, 9359 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9360 // Make sure there are no dangling permission trees. 9361 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9362 while (it.hasNext()) { 9363 final BasePermission bp = it.next(); 9364 if (bp.packageSetting == null) { 9365 // We may not yet have parsed the package, so just see if 9366 // we still know about its settings. 9367 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9368 } 9369 if (bp.packageSetting == null) { 9370 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9371 + " from package " + bp.sourcePackage); 9372 it.remove(); 9373 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9374 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9375 Slog.i(TAG, "Removing old permission tree: " + bp.name 9376 + " from package " + bp.sourcePackage); 9377 flags |= UPDATE_PERMISSIONS_ALL; 9378 it.remove(); 9379 } 9380 } 9381 } 9382 9383 // Make sure all dynamic permissions have been assigned to a package, 9384 // and make sure there are no dangling permissions. 9385 it = mSettings.mPermissions.values().iterator(); 9386 while (it.hasNext()) { 9387 final BasePermission bp = it.next(); 9388 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9389 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9390 + bp.name + " pkg=" + bp.sourcePackage 9391 + " info=" + bp.pendingInfo); 9392 if (bp.packageSetting == null && bp.pendingInfo != null) { 9393 final BasePermission tree = findPermissionTreeLP(bp.name); 9394 if (tree != null && tree.perm != null) { 9395 bp.packageSetting = tree.packageSetting; 9396 bp.perm = new PackageParser.Permission(tree.perm.owner, 9397 new PermissionInfo(bp.pendingInfo)); 9398 bp.perm.info.packageName = tree.perm.info.packageName; 9399 bp.perm.info.name = bp.name; 9400 bp.uid = tree.uid; 9401 } 9402 } 9403 } 9404 if (bp.packageSetting == null) { 9405 // We may not yet have parsed the package, so just see if 9406 // we still know about its settings. 9407 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9408 } 9409 if (bp.packageSetting == null) { 9410 Slog.w(TAG, "Removing dangling permission: " + bp.name 9411 + " from package " + bp.sourcePackage); 9412 it.remove(); 9413 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9414 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9415 Slog.i(TAG, "Removing old permission: " + bp.name 9416 + " from package " + bp.sourcePackage); 9417 flags |= UPDATE_PERMISSIONS_ALL; 9418 it.remove(); 9419 } 9420 } 9421 } 9422 9423 // Now update the permissions for all packages, in particular 9424 // replace the granted permissions of the system packages. 9425 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9426 for (PackageParser.Package pkg : mPackages.values()) { 9427 if (pkg != pkgInfo) { 9428 // Only replace for packages on requested volume 9429 final String volumeUuid = getVolumeUuidForPackage(pkg); 9430 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9431 && Objects.equals(replaceVolumeUuid, volumeUuid); 9432 grantPermissionsLPw(pkg, replace, changingPkg); 9433 } 9434 } 9435 } 9436 9437 if (pkgInfo != null) { 9438 // Only replace for packages on requested volume 9439 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9440 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9441 && Objects.equals(replaceVolumeUuid, volumeUuid); 9442 grantPermissionsLPw(pkgInfo, replace, changingPkg); 9443 } 9444 } 9445 9446 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 9447 String packageOfInterest) { 9448 // IMPORTANT: There are two types of permissions: install and runtime. 9449 // Install time permissions are granted when the app is installed to 9450 // all device users and users added in the future. Runtime permissions 9451 // are granted at runtime explicitly to specific users. Normal and signature 9452 // protected permissions are install time permissions. Dangerous permissions 9453 // are install permissions if the app's target SDK is Lollipop MR1 or older, 9454 // otherwise they are runtime permissions. This function does not manage 9455 // runtime permissions except for the case an app targeting Lollipop MR1 9456 // being upgraded to target a newer SDK, in which case dangerous permissions 9457 // are transformed from install time to runtime ones. 9458 9459 final PackageSetting ps = (PackageSetting) pkg.mExtras; 9460 if (ps == null) { 9461 return; 9462 } 9463 9464 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 9465 9466 PermissionsState permissionsState = ps.getPermissionsState(); 9467 PermissionsState origPermissions = permissionsState; 9468 9469 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 9470 9471 boolean runtimePermissionsRevoked = false; 9472 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 9473 9474 boolean changedInstallPermission = false; 9475 9476 if (replace) { 9477 ps.installPermissionsFixed = false; 9478 if (!ps.isSharedUser()) { 9479 origPermissions = new PermissionsState(permissionsState); 9480 permissionsState.reset(); 9481 } else { 9482 // We need to know only about runtime permission changes since the 9483 // calling code always writes the install permissions state but 9484 // the runtime ones are written only if changed. The only cases of 9485 // changed runtime permissions here are promotion of an install to 9486 // runtime and revocation of a runtime from a shared user. 9487 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 9488 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 9489 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 9490 runtimePermissionsRevoked = true; 9491 } 9492 } 9493 } 9494 9495 permissionsState.setGlobalGids(mGlobalGids); 9496 9497 final int N = pkg.requestedPermissions.size(); 9498 for (int i=0; i<N; i++) { 9499 final String name = pkg.requestedPermissions.get(i); 9500 final BasePermission bp = mSettings.mPermissions.get(name); 9501 9502 if (DEBUG_INSTALL) { 9503 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 9504 } 9505 9506 if (bp == null || bp.packageSetting == null) { 9507 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9508 Slog.w(TAG, "Unknown permission " + name 9509 + " in package " + pkg.packageName); 9510 } 9511 continue; 9512 } 9513 9514 final String perm = bp.name; 9515 boolean allowedSig = false; 9516 int grant = GRANT_DENIED; 9517 9518 // Keep track of app op permissions. 9519 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9520 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 9521 if (pkgs == null) { 9522 pkgs = new ArraySet<>(); 9523 mAppOpPermissionPackages.put(bp.name, pkgs); 9524 } 9525 pkgs.add(pkg.packageName); 9526 } 9527 9528 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 9529 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 9530 >= Build.VERSION_CODES.M; 9531 switch (level) { 9532 case PermissionInfo.PROTECTION_NORMAL: { 9533 // For all apps normal permissions are install time ones. 9534 grant = GRANT_INSTALL; 9535 } break; 9536 9537 case PermissionInfo.PROTECTION_DANGEROUS: { 9538 // If a permission review is required for legacy apps we represent 9539 // their permissions as always granted runtime ones since we need 9540 // to keep the review required permission flag per user while an 9541 // install permission's state is shared across all users. 9542 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 9543 // For legacy apps dangerous permissions are install time ones. 9544 grant = GRANT_INSTALL; 9545 } else if (origPermissions.hasInstallPermission(bp.name)) { 9546 // For legacy apps that became modern, install becomes runtime. 9547 grant = GRANT_UPGRADE; 9548 } else if (mPromoteSystemApps 9549 && isSystemApp(ps) 9550 && mExistingSystemPackages.contains(ps.name)) { 9551 // For legacy system apps, install becomes runtime. 9552 // We cannot check hasInstallPermission() for system apps since those 9553 // permissions were granted implicitly and not persisted pre-M. 9554 grant = GRANT_UPGRADE; 9555 } else { 9556 // For modern apps keep runtime permissions unchanged. 9557 grant = GRANT_RUNTIME; 9558 } 9559 } break; 9560 9561 case PermissionInfo.PROTECTION_SIGNATURE: { 9562 // For all apps signature permissions are install time ones. 9563 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 9564 if (allowedSig) { 9565 grant = GRANT_INSTALL; 9566 } 9567 } break; 9568 } 9569 9570 if (DEBUG_INSTALL) { 9571 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 9572 } 9573 9574 if (grant != GRANT_DENIED) { 9575 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 9576 // If this is an existing, non-system package, then 9577 // we can't add any new permissions to it. 9578 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 9579 // Except... if this is a permission that was added 9580 // to the platform (note: need to only do this when 9581 // updating the platform). 9582 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 9583 grant = GRANT_DENIED; 9584 } 9585 } 9586 } 9587 9588 switch (grant) { 9589 case GRANT_INSTALL: { 9590 // Revoke this as runtime permission to handle the case of 9591 // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps 9592 for (int userId : UserManagerService.getInstance().getUserIds()) { 9593 if (origPermissions.getRuntimePermissionState( 9594 bp.name, userId) != null) { 9595 // Revoke the runtime permission and clear the flags. 9596 origPermissions.revokeRuntimePermission(bp, userId); 9597 origPermissions.updatePermissionFlags(bp, userId, 9598 PackageManager.MASK_PERMISSION_FLAGS, 0); 9599 // If we revoked a permission permission, we have to write. 9600 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9601 changedRuntimePermissionUserIds, userId); 9602 } 9603 } 9604 // Grant an install permission. 9605 if (permissionsState.grantInstallPermission(bp) != 9606 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9607 changedInstallPermission = true; 9608 } 9609 } break; 9610 9611 case GRANT_RUNTIME: { 9612 // Grant previously granted runtime permissions. 9613 for (int userId : UserManagerService.getInstance().getUserIds()) { 9614 PermissionState permissionState = origPermissions 9615 .getRuntimePermissionState(bp.name, userId); 9616 int flags = permissionState != null 9617 ? permissionState.getFlags() : 0; 9618 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 9619 if (permissionsState.grantRuntimePermission(bp, userId) == 9620 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9621 // If we cannot put the permission as it was, we have to write. 9622 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9623 changedRuntimePermissionUserIds, userId); 9624 } 9625 // If the app supports runtime permissions no need for a review. 9626 if (Build.PERMISSIONS_REVIEW_REQUIRED 9627 && appSupportsRuntimePermissions 9628 && (flags & PackageManager 9629 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 9630 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 9631 // Since we changed the flags, we have to write. 9632 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9633 changedRuntimePermissionUserIds, userId); 9634 } 9635 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 9636 && !appSupportsRuntimePermissions) { 9637 // For legacy apps that need a permission review, every new 9638 // runtime permission is granted but it is pending a review. 9639 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 9640 permissionsState.grantRuntimePermission(bp, userId); 9641 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 9642 // We changed the permission and flags, hence have to write. 9643 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9644 changedRuntimePermissionUserIds, userId); 9645 } 9646 } 9647 // Propagate the permission flags. 9648 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 9649 } 9650 } break; 9651 9652 case GRANT_UPGRADE: { 9653 // Grant runtime permissions for a previously held install permission. 9654 PermissionState permissionState = origPermissions 9655 .getInstallPermissionState(bp.name); 9656 final int flags = permissionState != null ? permissionState.getFlags() : 0; 9657 9658 if (origPermissions.revokeInstallPermission(bp) 9659 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 9660 // We will be transferring the permission flags, so clear them. 9661 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 9662 PackageManager.MASK_PERMISSION_FLAGS, 0); 9663 changedInstallPermission = true; 9664 } 9665 9666 // If the permission is not to be promoted to runtime we ignore it and 9667 // also its other flags as they are not applicable to install permissions. 9668 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 9669 for (int userId : currentUserIds) { 9670 if (permissionsState.grantRuntimePermission(bp, userId) != 9671 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9672 // Transfer the permission flags. 9673 permissionsState.updatePermissionFlags(bp, userId, 9674 flags, flags); 9675 // If we granted the permission, we have to write. 9676 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9677 changedRuntimePermissionUserIds, userId); 9678 } 9679 } 9680 } 9681 } break; 9682 9683 default: { 9684 if (packageOfInterest == null 9685 || packageOfInterest.equals(pkg.packageName)) { 9686 Slog.w(TAG, "Not granting permission " + perm 9687 + " to package " + pkg.packageName 9688 + " because it was previously installed without"); 9689 } 9690 } break; 9691 } 9692 } else { 9693 if (permissionsState.revokeInstallPermission(bp) != 9694 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9695 // Also drop the permission flags. 9696 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 9697 PackageManager.MASK_PERMISSION_FLAGS, 0); 9698 changedInstallPermission = true; 9699 Slog.i(TAG, "Un-granting permission " + perm 9700 + " from package " + pkg.packageName 9701 + " (protectionLevel=" + bp.protectionLevel 9702 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9703 + ")"); 9704 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 9705 // Don't print warning for app op permissions, since it is fine for them 9706 // not to be granted, there is a UI for the user to decide. 9707 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9708 Slog.w(TAG, "Not granting permission " + perm 9709 + " to package " + pkg.packageName 9710 + " (protectionLevel=" + bp.protectionLevel 9711 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9712 + ")"); 9713 } 9714 } 9715 } 9716 } 9717 9718 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 9719 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 9720 // This is the first that we have heard about this package, so the 9721 // permissions we have now selected are fixed until explicitly 9722 // changed. 9723 ps.installPermissionsFixed = true; 9724 } 9725 9726 // Persist the runtime permissions state for users with changes. If permissions 9727 // were revoked because no app in the shared user declares them we have to 9728 // write synchronously to avoid losing runtime permissions state. 9729 for (int userId : changedRuntimePermissionUserIds) { 9730 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 9731 } 9732 9733 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9734 } 9735 9736 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 9737 boolean allowed = false; 9738 final int NP = PackageParser.NEW_PERMISSIONS.length; 9739 for (int ip=0; ip<NP; ip++) { 9740 final PackageParser.NewPermissionInfo npi 9741 = PackageParser.NEW_PERMISSIONS[ip]; 9742 if (npi.name.equals(perm) 9743 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 9744 allowed = true; 9745 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 9746 + pkg.packageName); 9747 break; 9748 } 9749 } 9750 return allowed; 9751 } 9752 9753 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 9754 BasePermission bp, PermissionsState origPermissions) { 9755 boolean allowed; 9756 allowed = (compareSignatures( 9757 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 9758 == PackageManager.SIGNATURE_MATCH) 9759 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 9760 == PackageManager.SIGNATURE_MATCH); 9761 if (!allowed && (bp.protectionLevel 9762 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 9763 if (isSystemApp(pkg)) { 9764 // For updated system applications, a system permission 9765 // is granted only if it had been defined by the original application. 9766 if (pkg.isUpdatedSystemApp()) { 9767 final PackageSetting sysPs = mSettings 9768 .getDisabledSystemPkgLPr(pkg.packageName); 9769 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 9770 // If the original was granted this permission, we take 9771 // that grant decision as read and propagate it to the 9772 // update. 9773 if (sysPs.isPrivileged()) { 9774 allowed = true; 9775 } 9776 } else { 9777 // The system apk may have been updated with an older 9778 // version of the one on the data partition, but which 9779 // granted a new system permission that it didn't have 9780 // before. In this case we do want to allow the app to 9781 // now get the new permission if the ancestral apk is 9782 // privileged to get it. 9783 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 9784 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 9785 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 9786 allowed = true; 9787 break; 9788 } 9789 } 9790 } 9791 // Also if a privileged parent package on the system image or any of 9792 // its children requested a privileged permission, the updated child 9793 // packages can also get the permission. 9794 if (pkg.parentPackage != null) { 9795 final PackageSetting disabledSysParentPs = mSettings 9796 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 9797 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 9798 && disabledSysParentPs.isPrivileged()) { 9799 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 9800 allowed = true; 9801 } else if (disabledSysParentPs.pkg.childPackages != null) { 9802 final int count = disabledSysParentPs.pkg.childPackages.size(); 9803 for (int i = 0; i < count; i++) { 9804 PackageParser.Package disabledSysChildPkg = 9805 disabledSysParentPs.pkg.childPackages.get(i); 9806 if (isPackageRequestingPermission(disabledSysChildPkg, 9807 perm)) { 9808 allowed = true; 9809 break; 9810 } 9811 } 9812 } 9813 } 9814 } 9815 } 9816 } else { 9817 allowed = isPrivilegedApp(pkg); 9818 } 9819 } 9820 } 9821 if (!allowed) { 9822 if (!allowed && (bp.protectionLevel 9823 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 9824 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 9825 // If this was a previously normal/dangerous permission that got moved 9826 // to a system permission as part of the runtime permission redesign, then 9827 // we still want to blindly grant it to old apps. 9828 allowed = true; 9829 } 9830 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 9831 && pkg.packageName.equals(mRequiredInstallerPackage)) { 9832 // If this permission is to be granted to the system installer and 9833 // this app is an installer, then it gets the permission. 9834 allowed = true; 9835 } 9836 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 9837 && pkg.packageName.equals(mRequiredVerifierPackage)) { 9838 // If this permission is to be granted to the system verifier and 9839 // this app is a verifier, then it gets the permission. 9840 allowed = true; 9841 } 9842 if (!allowed && (bp.protectionLevel 9843 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 9844 && isSystemApp(pkg)) { 9845 // Any pre-installed system app is allowed to get this permission. 9846 allowed = true; 9847 } 9848 if (!allowed && (bp.protectionLevel 9849 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 9850 // For development permissions, a development permission 9851 // is granted only if it was already granted. 9852 allowed = origPermissions.hasInstallPermission(perm); 9853 } 9854 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 9855 && pkg.packageName.equals(mSetupWizardPackage)) { 9856 // If this permission is to be granted to the system setup wizard and 9857 // this app is a setup wizard, then it gets the permission. 9858 allowed = true; 9859 } 9860 } 9861 return allowed; 9862 } 9863 9864 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 9865 final int permCount = pkg.requestedPermissions.size(); 9866 for (int j = 0; j < permCount; j++) { 9867 String requestedPermission = pkg.requestedPermissions.get(j); 9868 if (permission.equals(requestedPermission)) { 9869 return true; 9870 } 9871 } 9872 return false; 9873 } 9874 9875 final class ActivityIntentResolver 9876 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 9877 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9878 boolean defaultOnly, int userId) { 9879 if (!sUserManager.exists(userId)) return null; 9880 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9881 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9882 } 9883 9884 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9885 int userId) { 9886 if (!sUserManager.exists(userId)) return null; 9887 mFlags = flags; 9888 return super.queryIntent(intent, resolvedType, 9889 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9890 } 9891 9892 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9893 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 9894 if (!sUserManager.exists(userId)) return null; 9895 if (packageActivities == null) { 9896 return null; 9897 } 9898 mFlags = flags; 9899 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9900 final int N = packageActivities.size(); 9901 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 9902 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 9903 9904 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 9905 for (int i = 0; i < N; ++i) { 9906 intentFilters = packageActivities.get(i).intents; 9907 if (intentFilters != null && intentFilters.size() > 0) { 9908 PackageParser.ActivityIntentInfo[] array = 9909 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 9910 intentFilters.toArray(array); 9911 listCut.add(array); 9912 } 9913 } 9914 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9915 } 9916 9917 /** 9918 * Finds a privileged activity that matches the specified activity names. 9919 */ 9920 private PackageParser.Activity findMatchingActivity( 9921 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 9922 for (PackageParser.Activity sysActivity : activityList) { 9923 if (sysActivity.info.name.equals(activityInfo.name)) { 9924 return sysActivity; 9925 } 9926 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 9927 return sysActivity; 9928 } 9929 if (sysActivity.info.targetActivity != null) { 9930 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 9931 return sysActivity; 9932 } 9933 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 9934 return sysActivity; 9935 } 9936 } 9937 } 9938 return null; 9939 } 9940 9941 public class IterGenerator<E> { 9942 public Iterator<E> generate(ActivityIntentInfo info) { 9943 return null; 9944 } 9945 } 9946 9947 public class ActionIterGenerator extends IterGenerator<String> { 9948 @Override 9949 public Iterator<String> generate(ActivityIntentInfo info) { 9950 return info.actionsIterator(); 9951 } 9952 } 9953 9954 public class CategoriesIterGenerator extends IterGenerator<String> { 9955 @Override 9956 public Iterator<String> generate(ActivityIntentInfo info) { 9957 return info.categoriesIterator(); 9958 } 9959 } 9960 9961 public class SchemesIterGenerator extends IterGenerator<String> { 9962 @Override 9963 public Iterator<String> generate(ActivityIntentInfo info) { 9964 return info.schemesIterator(); 9965 } 9966 } 9967 9968 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 9969 @Override 9970 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 9971 return info.authoritiesIterator(); 9972 } 9973 } 9974 9975 /** 9976 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 9977 * MODIFIED. Do not pass in a list that should not be changed. 9978 */ 9979 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 9980 IterGenerator<T> generator, Iterator<T> searchIterator) { 9981 // loop through the set of actions; every one must be found in the intent filter 9982 while (searchIterator.hasNext()) { 9983 // we must have at least one filter in the list to consider a match 9984 if (intentList.size() == 0) { 9985 break; 9986 } 9987 9988 final T searchAction = searchIterator.next(); 9989 9990 // loop through the set of intent filters 9991 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 9992 while (intentIter.hasNext()) { 9993 final ActivityIntentInfo intentInfo = intentIter.next(); 9994 boolean selectionFound = false; 9995 9996 // loop through the intent filter's selection criteria; at least one 9997 // of them must match the searched criteria 9998 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 9999 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 10000 final T intentSelection = intentSelectionIter.next(); 10001 if (intentSelection != null && intentSelection.equals(searchAction)) { 10002 selectionFound = true; 10003 break; 10004 } 10005 } 10006 10007 // the selection criteria wasn't found in this filter's set; this filter 10008 // is not a potential match 10009 if (!selectionFound) { 10010 intentIter.remove(); 10011 } 10012 } 10013 } 10014 } 10015 10016 private boolean isProtectedAction(ActivityIntentInfo filter) { 10017 final Iterator<String> actionsIter = filter.actionsIterator(); 10018 while (actionsIter != null && actionsIter.hasNext()) { 10019 final String filterAction = actionsIter.next(); 10020 if (PROTECTED_ACTIONS.contains(filterAction)) { 10021 return true; 10022 } 10023 } 10024 return false; 10025 } 10026 10027 /** 10028 * Adjusts the priority of the given intent filter according to policy. 10029 * <p> 10030 * <ul> 10031 * <li>The priority for non privileged applications is capped to '0'</li> 10032 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 10033 * <li>The priority for unbundled updates to privileged applications is capped to the 10034 * priority defined on the system partition</li> 10035 * </ul> 10036 * <p> 10037 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 10038 * allowed to obtain any priority on any action. 10039 */ 10040 private void adjustPriority( 10041 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 10042 // nothing to do; priority is fine as-is 10043 if (intent.getPriority() <= 0) { 10044 return; 10045 } 10046 10047 final ActivityInfo activityInfo = intent.activity.info; 10048 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 10049 10050 final boolean privilegedApp = 10051 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 10052 if (!privilegedApp) { 10053 // non-privileged applications can never define a priority >0 10054 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 10055 + " package: " + applicationInfo.packageName 10056 + " activity: " + intent.activity.className 10057 + " origPrio: " + intent.getPriority()); 10058 intent.setPriority(0); 10059 return; 10060 } 10061 10062 if (systemActivities == null) { 10063 // the system package is not disabled; we're parsing the system partition 10064 if (isProtectedAction(intent)) { 10065 if (mDeferProtectedFilters) { 10066 // We can't deal with these just yet. No component should ever obtain a 10067 // >0 priority for a protected actions, with ONE exception -- the setup 10068 // wizard. The setup wizard, however, cannot be known until we're able to 10069 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 10070 // until all intent filters have been processed. Chicken, meet egg. 10071 // Let the filter temporarily have a high priority and rectify the 10072 // priorities after all system packages have been scanned. 10073 mProtectedFilters.add(intent); 10074 if (DEBUG_FILTERS) { 10075 Slog.i(TAG, "Protected action; save for later;" 10076 + " package: " + applicationInfo.packageName 10077 + " activity: " + intent.activity.className 10078 + " origPrio: " + intent.getPriority()); 10079 } 10080 return; 10081 } else { 10082 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 10083 Slog.i(TAG, "No setup wizard;" 10084 + " All protected intents capped to priority 0"); 10085 } 10086 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 10087 if (DEBUG_FILTERS) { 10088 Slog.i(TAG, "Found setup wizard;" 10089 + " allow priority " + intent.getPriority() + ";" 10090 + " package: " + intent.activity.info.packageName 10091 + " activity: " + intent.activity.className 10092 + " priority: " + intent.getPriority()); 10093 } 10094 // setup wizard gets whatever it wants 10095 return; 10096 } 10097 Slog.w(TAG, "Protected action; cap priority to 0;" 10098 + " package: " + intent.activity.info.packageName 10099 + " activity: " + intent.activity.className 10100 + " origPrio: " + intent.getPriority()); 10101 intent.setPriority(0); 10102 return; 10103 } 10104 } 10105 // privileged apps on the system image get whatever priority they request 10106 return; 10107 } 10108 10109 // privileged app unbundled update ... try to find the same activity 10110 final PackageParser.Activity foundActivity = 10111 findMatchingActivity(systemActivities, activityInfo); 10112 if (foundActivity == null) { 10113 // this is a new activity; it cannot obtain >0 priority 10114 if (DEBUG_FILTERS) { 10115 Slog.i(TAG, "New activity; cap priority to 0;" 10116 + " package: " + applicationInfo.packageName 10117 + " activity: " + intent.activity.className 10118 + " origPrio: " + intent.getPriority()); 10119 } 10120 intent.setPriority(0); 10121 return; 10122 } 10123 10124 // found activity, now check for filter equivalence 10125 10126 // a shallow copy is enough; we modify the list, not its contents 10127 final List<ActivityIntentInfo> intentListCopy = 10128 new ArrayList<>(foundActivity.intents); 10129 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 10130 10131 // find matching action subsets 10132 final Iterator<String> actionsIterator = intent.actionsIterator(); 10133 if (actionsIterator != null) { 10134 getIntentListSubset( 10135 intentListCopy, new ActionIterGenerator(), actionsIterator); 10136 if (intentListCopy.size() == 0) { 10137 // no more intents to match; we're not equivalent 10138 if (DEBUG_FILTERS) { 10139 Slog.i(TAG, "Mismatched action; cap priority to 0;" 10140 + " package: " + applicationInfo.packageName 10141 + " activity: " + intent.activity.className 10142 + " origPrio: " + intent.getPriority()); 10143 } 10144 intent.setPriority(0); 10145 return; 10146 } 10147 } 10148 10149 // find matching category subsets 10150 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 10151 if (categoriesIterator != null) { 10152 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 10153 categoriesIterator); 10154 if (intentListCopy.size() == 0) { 10155 // no more intents to match; we're not equivalent 10156 if (DEBUG_FILTERS) { 10157 Slog.i(TAG, "Mismatched category; cap priority to 0;" 10158 + " package: " + applicationInfo.packageName 10159 + " activity: " + intent.activity.className 10160 + " origPrio: " + intent.getPriority()); 10161 } 10162 intent.setPriority(0); 10163 return; 10164 } 10165 } 10166 10167 // find matching schemes subsets 10168 final Iterator<String> schemesIterator = intent.schemesIterator(); 10169 if (schemesIterator != null) { 10170 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 10171 schemesIterator); 10172 if (intentListCopy.size() == 0) { 10173 // no more intents to match; we're not equivalent 10174 if (DEBUG_FILTERS) { 10175 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 10176 + " package: " + applicationInfo.packageName 10177 + " activity: " + intent.activity.className 10178 + " origPrio: " + intent.getPriority()); 10179 } 10180 intent.setPriority(0); 10181 return; 10182 } 10183 } 10184 10185 // find matching authorities subsets 10186 final Iterator<IntentFilter.AuthorityEntry> 10187 authoritiesIterator = intent.authoritiesIterator(); 10188 if (authoritiesIterator != null) { 10189 getIntentListSubset(intentListCopy, 10190 new AuthoritiesIterGenerator(), 10191 authoritiesIterator); 10192 if (intentListCopy.size() == 0) { 10193 // no more intents to match; we're not equivalent 10194 if (DEBUG_FILTERS) { 10195 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 10196 + " package: " + applicationInfo.packageName 10197 + " activity: " + intent.activity.className 10198 + " origPrio: " + intent.getPriority()); 10199 } 10200 intent.setPriority(0); 10201 return; 10202 } 10203 } 10204 10205 // we found matching filter(s); app gets the max priority of all intents 10206 int cappedPriority = 0; 10207 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 10208 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 10209 } 10210 if (intent.getPriority() > cappedPriority) { 10211 if (DEBUG_FILTERS) { 10212 Slog.i(TAG, "Found matching filter(s);" 10213 + " cap priority to " + cappedPriority + ";" 10214 + " package: " + applicationInfo.packageName 10215 + " activity: " + intent.activity.className 10216 + " origPrio: " + intent.getPriority()); 10217 } 10218 intent.setPriority(cappedPriority); 10219 return; 10220 } 10221 // all this for nothing; the requested priority was <= what was on the system 10222 } 10223 10224 public final void addActivity(PackageParser.Activity a, String type) { 10225 mActivities.put(a.getComponentName(), a); 10226 if (DEBUG_SHOW_INFO) 10227 Log.v( 10228 TAG, " " + type + " " + 10229 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 10230 if (DEBUG_SHOW_INFO) 10231 Log.v(TAG, " Class=" + a.info.name); 10232 final int NI = a.intents.size(); 10233 for (int j=0; j<NI; j++) { 10234 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10235 if ("activity".equals(type)) { 10236 final PackageSetting ps = 10237 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 10238 final List<PackageParser.Activity> systemActivities = 10239 ps != null && ps.pkg != null ? ps.pkg.activities : null; 10240 adjustPriority(systemActivities, intent); 10241 } 10242 if (DEBUG_SHOW_INFO) { 10243 Log.v(TAG, " IntentFilter:"); 10244 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10245 } 10246 if (!intent.debugCheck()) { 10247 Log.w(TAG, "==> For Activity " + a.info.name); 10248 } 10249 addFilter(intent); 10250 } 10251 } 10252 10253 public final void removeActivity(PackageParser.Activity a, String type) { 10254 mActivities.remove(a.getComponentName()); 10255 if (DEBUG_SHOW_INFO) { 10256 Log.v(TAG, " " + type + " " 10257 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 10258 : a.info.name) + ":"); 10259 Log.v(TAG, " Class=" + a.info.name); 10260 } 10261 final int NI = a.intents.size(); 10262 for (int j=0; j<NI; j++) { 10263 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10264 if (DEBUG_SHOW_INFO) { 10265 Log.v(TAG, " IntentFilter:"); 10266 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10267 } 10268 removeFilter(intent); 10269 } 10270 } 10271 10272 @Override 10273 protected boolean allowFilterResult( 10274 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 10275 ActivityInfo filterAi = filter.activity.info; 10276 for (int i=dest.size()-1; i>=0; i--) { 10277 ActivityInfo destAi = dest.get(i).activityInfo; 10278 if (destAi.name == filterAi.name 10279 && destAi.packageName == filterAi.packageName) { 10280 return false; 10281 } 10282 } 10283 return true; 10284 } 10285 10286 @Override 10287 protected ActivityIntentInfo[] newArray(int size) { 10288 return new ActivityIntentInfo[size]; 10289 } 10290 10291 @Override 10292 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 10293 if (!sUserManager.exists(userId)) return true; 10294 PackageParser.Package p = filter.activity.owner; 10295 if (p != null) { 10296 PackageSetting ps = (PackageSetting)p.mExtras; 10297 if (ps != null) { 10298 // System apps are never considered stopped for purposes of 10299 // filtering, because there may be no way for the user to 10300 // actually re-launch them. 10301 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 10302 && ps.getStopped(userId); 10303 } 10304 } 10305 return false; 10306 } 10307 10308 @Override 10309 protected boolean isPackageForFilter(String packageName, 10310 PackageParser.ActivityIntentInfo info) { 10311 return packageName.equals(info.activity.owner.packageName); 10312 } 10313 10314 @Override 10315 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 10316 int match, int userId) { 10317 if (!sUserManager.exists(userId)) return null; 10318 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 10319 return null; 10320 } 10321 final PackageParser.Activity activity = info.activity; 10322 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 10323 if (ps == null) { 10324 return null; 10325 } 10326 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 10327 ps.readUserState(userId), userId); 10328 if (ai == null) { 10329 return null; 10330 } 10331 final ResolveInfo res = new ResolveInfo(); 10332 res.activityInfo = ai; 10333 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10334 res.filter = info; 10335 } 10336 if (info != null) { 10337 res.handleAllWebDataURI = info.handleAllWebDataURI(); 10338 } 10339 res.priority = info.getPriority(); 10340 res.preferredOrder = activity.owner.mPreferredOrder; 10341 //System.out.println("Result: " + res.activityInfo.className + 10342 // " = " + res.priority); 10343 res.match = match; 10344 res.isDefault = info.hasDefault; 10345 res.labelRes = info.labelRes; 10346 res.nonLocalizedLabel = info.nonLocalizedLabel; 10347 if (userNeedsBadging(userId)) { 10348 res.noResourceId = true; 10349 } else { 10350 res.icon = info.icon; 10351 } 10352 res.iconResourceId = info.icon; 10353 res.system = res.activityInfo.applicationInfo.isSystemApp(); 10354 return res; 10355 } 10356 10357 @Override 10358 protected void sortResults(List<ResolveInfo> results) { 10359 Collections.sort(results, mResolvePrioritySorter); 10360 } 10361 10362 @Override 10363 protected void dumpFilter(PrintWriter out, String prefix, 10364 PackageParser.ActivityIntentInfo filter) { 10365 out.print(prefix); out.print( 10366 Integer.toHexString(System.identityHashCode(filter.activity))); 10367 out.print(' '); 10368 filter.activity.printComponentShortName(out); 10369 out.print(" filter "); 10370 out.println(Integer.toHexString(System.identityHashCode(filter))); 10371 } 10372 10373 @Override 10374 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 10375 return filter.activity; 10376 } 10377 10378 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10379 PackageParser.Activity activity = (PackageParser.Activity)label; 10380 out.print(prefix); out.print( 10381 Integer.toHexString(System.identityHashCode(activity))); 10382 out.print(' '); 10383 activity.printComponentShortName(out); 10384 if (count > 1) { 10385 out.print(" ("); out.print(count); out.print(" filters)"); 10386 } 10387 out.println(); 10388 } 10389 10390 // Keys are String (activity class name), values are Activity. 10391 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 10392 = new ArrayMap<ComponentName, PackageParser.Activity>(); 10393 private int mFlags; 10394 } 10395 10396 private final class ServiceIntentResolver 10397 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 10398 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10399 boolean defaultOnly, int userId) { 10400 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10401 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10402 } 10403 10404 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10405 int userId) { 10406 if (!sUserManager.exists(userId)) return null; 10407 mFlags = flags; 10408 return super.queryIntent(intent, resolvedType, 10409 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10410 } 10411 10412 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10413 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 10414 if (!sUserManager.exists(userId)) return null; 10415 if (packageServices == null) { 10416 return null; 10417 } 10418 mFlags = flags; 10419 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10420 final int N = packageServices.size(); 10421 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 10422 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 10423 10424 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 10425 for (int i = 0; i < N; ++i) { 10426 intentFilters = packageServices.get(i).intents; 10427 if (intentFilters != null && intentFilters.size() > 0) { 10428 PackageParser.ServiceIntentInfo[] array = 10429 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 10430 intentFilters.toArray(array); 10431 listCut.add(array); 10432 } 10433 } 10434 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10435 } 10436 10437 public final void addService(PackageParser.Service s) { 10438 mServices.put(s.getComponentName(), s); 10439 if (DEBUG_SHOW_INFO) { 10440 Log.v(TAG, " " 10441 + (s.info.nonLocalizedLabel != null 10442 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10443 Log.v(TAG, " Class=" + s.info.name); 10444 } 10445 final int NI = s.intents.size(); 10446 int j; 10447 for (j=0; j<NI; j++) { 10448 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10449 if (DEBUG_SHOW_INFO) { 10450 Log.v(TAG, " IntentFilter:"); 10451 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10452 } 10453 if (!intent.debugCheck()) { 10454 Log.w(TAG, "==> For Service " + s.info.name); 10455 } 10456 addFilter(intent); 10457 } 10458 } 10459 10460 public final void removeService(PackageParser.Service s) { 10461 mServices.remove(s.getComponentName()); 10462 if (DEBUG_SHOW_INFO) { 10463 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 10464 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10465 Log.v(TAG, " Class=" + s.info.name); 10466 } 10467 final int NI = s.intents.size(); 10468 int j; 10469 for (j=0; j<NI; j++) { 10470 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10471 if (DEBUG_SHOW_INFO) { 10472 Log.v(TAG, " IntentFilter:"); 10473 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10474 } 10475 removeFilter(intent); 10476 } 10477 } 10478 10479 @Override 10480 protected boolean allowFilterResult( 10481 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 10482 ServiceInfo filterSi = filter.service.info; 10483 for (int i=dest.size()-1; i>=0; i--) { 10484 ServiceInfo destAi = dest.get(i).serviceInfo; 10485 if (destAi.name == filterSi.name 10486 && destAi.packageName == filterSi.packageName) { 10487 return false; 10488 } 10489 } 10490 return true; 10491 } 10492 10493 @Override 10494 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 10495 return new PackageParser.ServiceIntentInfo[size]; 10496 } 10497 10498 @Override 10499 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 10500 if (!sUserManager.exists(userId)) return true; 10501 PackageParser.Package p = filter.service.owner; 10502 if (p != null) { 10503 PackageSetting ps = (PackageSetting)p.mExtras; 10504 if (ps != null) { 10505 // System apps are never considered stopped for purposes of 10506 // filtering, because there may be no way for the user to 10507 // actually re-launch them. 10508 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10509 && ps.getStopped(userId); 10510 } 10511 } 10512 return false; 10513 } 10514 10515 @Override 10516 protected boolean isPackageForFilter(String packageName, 10517 PackageParser.ServiceIntentInfo info) { 10518 return packageName.equals(info.service.owner.packageName); 10519 } 10520 10521 @Override 10522 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 10523 int match, int userId) { 10524 if (!sUserManager.exists(userId)) return null; 10525 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 10526 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 10527 return null; 10528 } 10529 final PackageParser.Service service = info.service; 10530 PackageSetting ps = (PackageSetting) service.owner.mExtras; 10531 if (ps == null) { 10532 return null; 10533 } 10534 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 10535 ps.readUserState(userId), userId); 10536 if (si == null) { 10537 return null; 10538 } 10539 final ResolveInfo res = new ResolveInfo(); 10540 res.serviceInfo = si; 10541 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10542 res.filter = filter; 10543 } 10544 res.priority = info.getPriority(); 10545 res.preferredOrder = service.owner.mPreferredOrder; 10546 res.match = match; 10547 res.isDefault = info.hasDefault; 10548 res.labelRes = info.labelRes; 10549 res.nonLocalizedLabel = info.nonLocalizedLabel; 10550 res.icon = info.icon; 10551 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 10552 return res; 10553 } 10554 10555 @Override 10556 protected void sortResults(List<ResolveInfo> results) { 10557 Collections.sort(results, mResolvePrioritySorter); 10558 } 10559 10560 @Override 10561 protected void dumpFilter(PrintWriter out, String prefix, 10562 PackageParser.ServiceIntentInfo filter) { 10563 out.print(prefix); out.print( 10564 Integer.toHexString(System.identityHashCode(filter.service))); 10565 out.print(' '); 10566 filter.service.printComponentShortName(out); 10567 out.print(" filter "); 10568 out.println(Integer.toHexString(System.identityHashCode(filter))); 10569 } 10570 10571 @Override 10572 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 10573 return filter.service; 10574 } 10575 10576 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10577 PackageParser.Service service = (PackageParser.Service)label; 10578 out.print(prefix); out.print( 10579 Integer.toHexString(System.identityHashCode(service))); 10580 out.print(' '); 10581 service.printComponentShortName(out); 10582 if (count > 1) { 10583 out.print(" ("); out.print(count); out.print(" filters)"); 10584 } 10585 out.println(); 10586 } 10587 10588// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 10589// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 10590// final List<ResolveInfo> retList = Lists.newArrayList(); 10591// while (i.hasNext()) { 10592// final ResolveInfo resolveInfo = (ResolveInfo) i; 10593// if (isEnabledLP(resolveInfo.serviceInfo)) { 10594// retList.add(resolveInfo); 10595// } 10596// } 10597// return retList; 10598// } 10599 10600 // Keys are String (activity class name), values are Activity. 10601 private final ArrayMap<ComponentName, PackageParser.Service> mServices 10602 = new ArrayMap<ComponentName, PackageParser.Service>(); 10603 private int mFlags; 10604 }; 10605 10606 private final class ProviderIntentResolver 10607 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 10608 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10609 boolean defaultOnly, int userId) { 10610 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10611 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10612 } 10613 10614 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10615 int userId) { 10616 if (!sUserManager.exists(userId)) 10617 return null; 10618 mFlags = flags; 10619 return super.queryIntent(intent, resolvedType, 10620 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10621 } 10622 10623 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10624 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 10625 if (!sUserManager.exists(userId)) 10626 return null; 10627 if (packageProviders == null) { 10628 return null; 10629 } 10630 mFlags = flags; 10631 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 10632 final int N = packageProviders.size(); 10633 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 10634 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 10635 10636 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 10637 for (int i = 0; i < N; ++i) { 10638 intentFilters = packageProviders.get(i).intents; 10639 if (intentFilters != null && intentFilters.size() > 0) { 10640 PackageParser.ProviderIntentInfo[] array = 10641 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 10642 intentFilters.toArray(array); 10643 listCut.add(array); 10644 } 10645 } 10646 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10647 } 10648 10649 public final void addProvider(PackageParser.Provider p) { 10650 if (mProviders.containsKey(p.getComponentName())) { 10651 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 10652 return; 10653 } 10654 10655 mProviders.put(p.getComponentName(), p); 10656 if (DEBUG_SHOW_INFO) { 10657 Log.v(TAG, " " 10658 + (p.info.nonLocalizedLabel != null 10659 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10660 Log.v(TAG, " Class=" + p.info.name); 10661 } 10662 final int NI = p.intents.size(); 10663 int j; 10664 for (j = 0; j < NI; j++) { 10665 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10666 if (DEBUG_SHOW_INFO) { 10667 Log.v(TAG, " IntentFilter:"); 10668 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10669 } 10670 if (!intent.debugCheck()) { 10671 Log.w(TAG, "==> For Provider " + p.info.name); 10672 } 10673 addFilter(intent); 10674 } 10675 } 10676 10677 public final void removeProvider(PackageParser.Provider p) { 10678 mProviders.remove(p.getComponentName()); 10679 if (DEBUG_SHOW_INFO) { 10680 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 10681 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10682 Log.v(TAG, " Class=" + p.info.name); 10683 } 10684 final int NI = p.intents.size(); 10685 int j; 10686 for (j = 0; j < NI; j++) { 10687 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10688 if (DEBUG_SHOW_INFO) { 10689 Log.v(TAG, " IntentFilter:"); 10690 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10691 } 10692 removeFilter(intent); 10693 } 10694 } 10695 10696 @Override 10697 protected boolean allowFilterResult( 10698 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 10699 ProviderInfo filterPi = filter.provider.info; 10700 for (int i = dest.size() - 1; i >= 0; i--) { 10701 ProviderInfo destPi = dest.get(i).providerInfo; 10702 if (destPi.name == filterPi.name 10703 && destPi.packageName == filterPi.packageName) { 10704 return false; 10705 } 10706 } 10707 return true; 10708 } 10709 10710 @Override 10711 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 10712 return new PackageParser.ProviderIntentInfo[size]; 10713 } 10714 10715 @Override 10716 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 10717 if (!sUserManager.exists(userId)) 10718 return true; 10719 PackageParser.Package p = filter.provider.owner; 10720 if (p != null) { 10721 PackageSetting ps = (PackageSetting) p.mExtras; 10722 if (ps != null) { 10723 // System apps are never considered stopped for purposes of 10724 // filtering, because there may be no way for the user to 10725 // actually re-launch them. 10726 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10727 && ps.getStopped(userId); 10728 } 10729 } 10730 return false; 10731 } 10732 10733 @Override 10734 protected boolean isPackageForFilter(String packageName, 10735 PackageParser.ProviderIntentInfo info) { 10736 return packageName.equals(info.provider.owner.packageName); 10737 } 10738 10739 @Override 10740 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 10741 int match, int userId) { 10742 if (!sUserManager.exists(userId)) 10743 return null; 10744 final PackageParser.ProviderIntentInfo info = filter; 10745 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 10746 return null; 10747 } 10748 final PackageParser.Provider provider = info.provider; 10749 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 10750 if (ps == null) { 10751 return null; 10752 } 10753 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 10754 ps.readUserState(userId), userId); 10755 if (pi == null) { 10756 return null; 10757 } 10758 final ResolveInfo res = new ResolveInfo(); 10759 res.providerInfo = pi; 10760 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 10761 res.filter = filter; 10762 } 10763 res.priority = info.getPriority(); 10764 res.preferredOrder = provider.owner.mPreferredOrder; 10765 res.match = match; 10766 res.isDefault = info.hasDefault; 10767 res.labelRes = info.labelRes; 10768 res.nonLocalizedLabel = info.nonLocalizedLabel; 10769 res.icon = info.icon; 10770 res.system = res.providerInfo.applicationInfo.isSystemApp(); 10771 return res; 10772 } 10773 10774 @Override 10775 protected void sortResults(List<ResolveInfo> results) { 10776 Collections.sort(results, mResolvePrioritySorter); 10777 } 10778 10779 @Override 10780 protected void dumpFilter(PrintWriter out, String prefix, 10781 PackageParser.ProviderIntentInfo filter) { 10782 out.print(prefix); 10783 out.print( 10784 Integer.toHexString(System.identityHashCode(filter.provider))); 10785 out.print(' '); 10786 filter.provider.printComponentShortName(out); 10787 out.print(" filter "); 10788 out.println(Integer.toHexString(System.identityHashCode(filter))); 10789 } 10790 10791 @Override 10792 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 10793 return filter.provider; 10794 } 10795 10796 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10797 PackageParser.Provider provider = (PackageParser.Provider)label; 10798 out.print(prefix); out.print( 10799 Integer.toHexString(System.identityHashCode(provider))); 10800 out.print(' '); 10801 provider.printComponentShortName(out); 10802 if (count > 1) { 10803 out.print(" ("); out.print(count); out.print(" filters)"); 10804 } 10805 out.println(); 10806 } 10807 10808 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 10809 = new ArrayMap<ComponentName, PackageParser.Provider>(); 10810 private int mFlags; 10811 } 10812 10813 private static final class EphemeralIntentResolver 10814 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 10815 @Override 10816 protected EphemeralResolveIntentInfo[] newArray(int size) { 10817 return new EphemeralResolveIntentInfo[size]; 10818 } 10819 10820 @Override 10821 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 10822 return true; 10823 } 10824 10825 @Override 10826 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 10827 int userId) { 10828 if (!sUserManager.exists(userId)) { 10829 return null; 10830 } 10831 return info.getEphemeralResolveInfo(); 10832 } 10833 } 10834 10835 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 10836 new Comparator<ResolveInfo>() { 10837 public int compare(ResolveInfo r1, ResolveInfo r2) { 10838 int v1 = r1.priority; 10839 int v2 = r2.priority; 10840 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 10841 if (v1 != v2) { 10842 return (v1 > v2) ? -1 : 1; 10843 } 10844 v1 = r1.preferredOrder; 10845 v2 = r2.preferredOrder; 10846 if (v1 != v2) { 10847 return (v1 > v2) ? -1 : 1; 10848 } 10849 if (r1.isDefault != r2.isDefault) { 10850 return r1.isDefault ? -1 : 1; 10851 } 10852 v1 = r1.match; 10853 v2 = r2.match; 10854 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 10855 if (v1 != v2) { 10856 return (v1 > v2) ? -1 : 1; 10857 } 10858 if (r1.system != r2.system) { 10859 return r1.system ? -1 : 1; 10860 } 10861 if (r1.activityInfo != null) { 10862 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 10863 } 10864 if (r1.serviceInfo != null) { 10865 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 10866 } 10867 if (r1.providerInfo != null) { 10868 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 10869 } 10870 return 0; 10871 } 10872 }; 10873 10874 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 10875 new Comparator<ProviderInfo>() { 10876 public int compare(ProviderInfo p1, ProviderInfo p2) { 10877 final int v1 = p1.initOrder; 10878 final int v2 = p2.initOrder; 10879 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 10880 } 10881 }; 10882 10883 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 10884 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 10885 final int[] userIds) { 10886 mHandler.post(new Runnable() { 10887 @Override 10888 public void run() { 10889 try { 10890 final IActivityManager am = ActivityManagerNative.getDefault(); 10891 if (am == null) return; 10892 final int[] resolvedUserIds; 10893 if (userIds == null) { 10894 resolvedUserIds = am.getRunningUserIds(); 10895 } else { 10896 resolvedUserIds = userIds; 10897 } 10898 for (int id : resolvedUserIds) { 10899 final Intent intent = new Intent(action, 10900 pkg != null ? Uri.fromParts("package", pkg, null) : null); 10901 if (extras != null) { 10902 intent.putExtras(extras); 10903 } 10904 if (targetPkg != null) { 10905 intent.setPackage(targetPkg); 10906 } 10907 // Modify the UID when posting to other users 10908 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 10909 if (uid > 0 && UserHandle.getUserId(uid) != id) { 10910 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 10911 intent.putExtra(Intent.EXTRA_UID, uid); 10912 } 10913 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 10914 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 10915 if (DEBUG_BROADCASTS) { 10916 RuntimeException here = new RuntimeException("here"); 10917 here.fillInStackTrace(); 10918 Slog.d(TAG, "Sending to user " + id + ": " 10919 + intent.toShortString(false, true, false, false) 10920 + " " + intent.getExtras(), here); 10921 } 10922 am.broadcastIntent(null, intent, null, finishedReceiver, 10923 0, null, null, null, android.app.AppOpsManager.OP_NONE, 10924 null, finishedReceiver != null, false, id); 10925 } 10926 } catch (RemoteException ex) { 10927 } 10928 } 10929 }); 10930 } 10931 10932 /** 10933 * Check if the external storage media is available. This is true if there 10934 * is a mounted external storage medium or if the external storage is 10935 * emulated. 10936 */ 10937 private boolean isExternalMediaAvailable() { 10938 return mMediaMounted || Environment.isExternalStorageEmulated(); 10939 } 10940 10941 @Override 10942 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 10943 // writer 10944 synchronized (mPackages) { 10945 if (!isExternalMediaAvailable()) { 10946 // If the external storage is no longer mounted at this point, 10947 // the caller may not have been able to delete all of this 10948 // packages files and can not delete any more. Bail. 10949 return null; 10950 } 10951 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 10952 if (lastPackage != null) { 10953 pkgs.remove(lastPackage); 10954 } 10955 if (pkgs.size() > 0) { 10956 return pkgs.get(0); 10957 } 10958 } 10959 return null; 10960 } 10961 10962 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 10963 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 10964 userId, andCode ? 1 : 0, packageName); 10965 if (mSystemReady) { 10966 msg.sendToTarget(); 10967 } else { 10968 if (mPostSystemReadyMessages == null) { 10969 mPostSystemReadyMessages = new ArrayList<>(); 10970 } 10971 mPostSystemReadyMessages.add(msg); 10972 } 10973 } 10974 10975 void startCleaningPackages() { 10976 // reader 10977 if (!isExternalMediaAvailable()) { 10978 return; 10979 } 10980 synchronized (mPackages) { 10981 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 10982 return; 10983 } 10984 } 10985 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 10986 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 10987 IActivityManager am = ActivityManagerNative.getDefault(); 10988 if (am != null) { 10989 try { 10990 am.startService(null, intent, null, mContext.getOpPackageName(), 10991 UserHandle.USER_SYSTEM); 10992 } catch (RemoteException e) { 10993 } 10994 } 10995 } 10996 10997 @Override 10998 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 10999 int installFlags, String installerPackageName, int userId) { 11000 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 11001 11002 final int callingUid = Binder.getCallingUid(); 11003 enforceCrossUserPermission(callingUid, userId, 11004 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 11005 11006 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11007 try { 11008 if (observer != null) { 11009 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 11010 } 11011 } catch (RemoteException re) { 11012 } 11013 return; 11014 } 11015 11016 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 11017 installFlags |= PackageManager.INSTALL_FROM_ADB; 11018 11019 } else { 11020 // Caller holds INSTALL_PACKAGES permission, so we're less strict 11021 // about installerPackageName. 11022 11023 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 11024 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 11025 } 11026 11027 UserHandle user; 11028 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 11029 user = UserHandle.ALL; 11030 } else { 11031 user = new UserHandle(userId); 11032 } 11033 11034 // Only system components can circumvent runtime permissions when installing. 11035 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 11036 && mContext.checkCallingOrSelfPermission(Manifest.permission 11037 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 11038 throw new SecurityException("You need the " 11039 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 11040 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 11041 } 11042 11043 final File originFile = new File(originPath); 11044 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 11045 11046 final Message msg = mHandler.obtainMessage(INIT_COPY); 11047 final VerificationInfo verificationInfo = new VerificationInfo( 11048 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 11049 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 11050 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 11051 null /*packageAbiOverride*/, null /*grantedPermissions*/, 11052 null /*certificates*/); 11053 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 11054 msg.obj = params; 11055 11056 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 11057 System.identityHashCode(msg.obj)); 11058 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11059 System.identityHashCode(msg.obj)); 11060 11061 mHandler.sendMessage(msg); 11062 } 11063 11064 void installStage(String packageName, File stagedDir, String stagedCid, 11065 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 11066 String installerPackageName, int installerUid, UserHandle user, 11067 Certificate[][] certificates) { 11068 if (DEBUG_EPHEMERAL) { 11069 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11070 Slog.d(TAG, "Ephemeral install of " + packageName); 11071 } 11072 } 11073 final VerificationInfo verificationInfo = new VerificationInfo( 11074 sessionParams.originatingUri, sessionParams.referrerUri, 11075 sessionParams.originatingUid, installerUid); 11076 11077 final OriginInfo origin; 11078 if (stagedDir != null) { 11079 origin = OriginInfo.fromStagedFile(stagedDir); 11080 } else { 11081 origin = OriginInfo.fromStagedContainer(stagedCid); 11082 } 11083 11084 final Message msg = mHandler.obtainMessage(INIT_COPY); 11085 final InstallParams params = new InstallParams(origin, null, observer, 11086 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 11087 verificationInfo, user, sessionParams.abiOverride, 11088 sessionParams.grantedRuntimePermissions, certificates); 11089 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 11090 msg.obj = params; 11091 11092 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 11093 System.identityHashCode(msg.obj)); 11094 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11095 System.identityHashCode(msg.obj)); 11096 11097 mHandler.sendMessage(msg); 11098 } 11099 11100 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 11101 int userId) { 11102 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 11103 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId); 11104 } 11105 11106 private void sendPackageAddedForUser(String packageName, boolean isSystem, 11107 int appId, int userId) { 11108 Bundle extras = new Bundle(1); 11109 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId)); 11110 11111 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 11112 packageName, extras, 0, null, null, new int[] {userId}); 11113 try { 11114 IActivityManager am = ActivityManagerNative.getDefault(); 11115 if (isSystem && am.isUserRunning(userId, 0)) { 11116 // The just-installed/enabled app is bundled on the system, so presumed 11117 // to be able to run automatically without needing an explicit launch. 11118 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 11119 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 11120 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 11121 .setPackage(packageName); 11122 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 11123 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 11124 } 11125 } catch (RemoteException e) { 11126 // shouldn't happen 11127 Slog.w(TAG, "Unable to bootstrap installed package", e); 11128 } 11129 } 11130 11131 @Override 11132 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 11133 int userId) { 11134 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11135 PackageSetting pkgSetting; 11136 final int uid = Binder.getCallingUid(); 11137 enforceCrossUserPermission(uid, userId, 11138 true /* requireFullPermission */, true /* checkShell */, 11139 "setApplicationHiddenSetting for user " + userId); 11140 11141 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 11142 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 11143 return false; 11144 } 11145 11146 long callingId = Binder.clearCallingIdentity(); 11147 try { 11148 boolean sendAdded = false; 11149 boolean sendRemoved = false; 11150 // writer 11151 synchronized (mPackages) { 11152 pkgSetting = mSettings.mPackages.get(packageName); 11153 if (pkgSetting == null) { 11154 return false; 11155 } 11156 if (pkgSetting.getHidden(userId) != hidden) { 11157 pkgSetting.setHidden(hidden, userId); 11158 mSettings.writePackageRestrictionsLPr(userId); 11159 if (hidden) { 11160 sendRemoved = true; 11161 } else { 11162 sendAdded = true; 11163 } 11164 } 11165 } 11166 if (sendAdded) { 11167 sendPackageAddedForUser(packageName, pkgSetting, userId); 11168 return true; 11169 } 11170 if (sendRemoved) { 11171 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 11172 "hiding pkg"); 11173 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 11174 return true; 11175 } 11176 } finally { 11177 Binder.restoreCallingIdentity(callingId); 11178 } 11179 return false; 11180 } 11181 11182 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 11183 int userId) { 11184 final PackageRemovedInfo info = new PackageRemovedInfo(); 11185 info.removedPackage = packageName; 11186 info.removedUsers = new int[] {userId}; 11187 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 11188 info.sendPackageRemovedBroadcasts(true /*killApp*/); 11189 } 11190 11191 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 11192 if (pkgList.length > 0) { 11193 Bundle extras = new Bundle(1); 11194 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 11195 11196 sendPackageBroadcast( 11197 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 11198 : Intent.ACTION_PACKAGES_UNSUSPENDED, 11199 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 11200 new int[] {userId}); 11201 } 11202 } 11203 11204 /** 11205 * Returns true if application is not found or there was an error. Otherwise it returns 11206 * the hidden state of the package for the given user. 11207 */ 11208 @Override 11209 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 11210 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11211 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11212 true /* requireFullPermission */, false /* checkShell */, 11213 "getApplicationHidden for user " + userId); 11214 PackageSetting pkgSetting; 11215 long callingId = Binder.clearCallingIdentity(); 11216 try { 11217 // writer 11218 synchronized (mPackages) { 11219 pkgSetting = mSettings.mPackages.get(packageName); 11220 if (pkgSetting == null) { 11221 return true; 11222 } 11223 return pkgSetting.getHidden(userId); 11224 } 11225 } finally { 11226 Binder.restoreCallingIdentity(callingId); 11227 } 11228 } 11229 11230 /** 11231 * @hide 11232 */ 11233 @Override 11234 public int installExistingPackageAsUser(String packageName, int userId) { 11235 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 11236 null); 11237 PackageSetting pkgSetting; 11238 final int uid = Binder.getCallingUid(); 11239 enforceCrossUserPermission(uid, userId, 11240 true /* requireFullPermission */, true /* checkShell */, 11241 "installExistingPackage for user " + userId); 11242 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11243 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 11244 } 11245 11246 long callingId = Binder.clearCallingIdentity(); 11247 try { 11248 boolean installed = false; 11249 11250 // writer 11251 synchronized (mPackages) { 11252 pkgSetting = mSettings.mPackages.get(packageName); 11253 if (pkgSetting == null) { 11254 return PackageManager.INSTALL_FAILED_INVALID_URI; 11255 } 11256 if (!pkgSetting.getInstalled(userId)) { 11257 pkgSetting.setInstalled(true, userId); 11258 pkgSetting.setHidden(false, userId); 11259 mSettings.writePackageRestrictionsLPr(userId); 11260 installed = true; 11261 } 11262 } 11263 11264 if (installed) { 11265 if (pkgSetting.pkg != null) { 11266 synchronized (mInstallLock) { 11267 // We don't need to freeze for a brand new install 11268 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 11269 } 11270 } 11271 sendPackageAddedForUser(packageName, pkgSetting, userId); 11272 } 11273 } finally { 11274 Binder.restoreCallingIdentity(callingId); 11275 } 11276 11277 return PackageManager.INSTALL_SUCCEEDED; 11278 } 11279 11280 boolean isUserRestricted(int userId, String restrictionKey) { 11281 Bundle restrictions = sUserManager.getUserRestrictions(userId); 11282 if (restrictions.getBoolean(restrictionKey, false)) { 11283 Log.w(TAG, "User is restricted: " + restrictionKey); 11284 return true; 11285 } 11286 return false; 11287 } 11288 11289 @Override 11290 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 11291 int userId) { 11292 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11293 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11294 true /* requireFullPermission */, true /* checkShell */, 11295 "setPackagesSuspended for user " + userId); 11296 11297 if (ArrayUtils.isEmpty(packageNames)) { 11298 return packageNames; 11299 } 11300 11301 // List of package names for whom the suspended state has changed. 11302 List<String> changedPackages = new ArrayList<>(packageNames.length); 11303 // List of package names for whom the suspended state is not set as requested in this 11304 // method. 11305 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 11306 for (int i = 0; i < packageNames.length; i++) { 11307 String packageName = packageNames[i]; 11308 long callingId = Binder.clearCallingIdentity(); 11309 try { 11310 boolean changed = false; 11311 final int appId; 11312 synchronized (mPackages) { 11313 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11314 if (pkgSetting == null) { 11315 Slog.w(TAG, "Could not find package setting for package \"" + packageName 11316 + "\". Skipping suspending/un-suspending."); 11317 unactionedPackages.add(packageName); 11318 continue; 11319 } 11320 appId = pkgSetting.appId; 11321 if (pkgSetting.getSuspended(userId) != suspended) { 11322 if (!canSuspendPackageForUserLocked(packageName, userId)) { 11323 unactionedPackages.add(packageName); 11324 continue; 11325 } 11326 pkgSetting.setSuspended(suspended, userId); 11327 mSettings.writePackageRestrictionsLPr(userId); 11328 changed = true; 11329 changedPackages.add(packageName); 11330 } 11331 } 11332 11333 if (changed && suspended) { 11334 killApplication(packageName, UserHandle.getUid(userId, appId), 11335 "suspending package"); 11336 } 11337 } finally { 11338 Binder.restoreCallingIdentity(callingId); 11339 } 11340 } 11341 11342 if (!changedPackages.isEmpty()) { 11343 sendPackagesSuspendedForUser(changedPackages.toArray( 11344 new String[changedPackages.size()]), userId, suspended); 11345 } 11346 11347 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 11348 } 11349 11350 @Override 11351 public boolean isPackageSuspendedForUser(String packageName, int userId) { 11352 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11353 true /* requireFullPermission */, false /* checkShell */, 11354 "isPackageSuspendedForUser for user " + userId); 11355 synchronized (mPackages) { 11356 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11357 if (pkgSetting == null) { 11358 throw new IllegalArgumentException("Unknown target package: " + packageName); 11359 } 11360 return pkgSetting.getSuspended(userId); 11361 } 11362 } 11363 11364 /** 11365 * TODO: cache and disallow blocking the active dialer. 11366 * 11367 * @see also DefaultPermissionGrantPolicy#grantDefaultSystemHandlerPermissions 11368 */ 11369 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 11370 if (isPackageDeviceAdmin(packageName, userId)) { 11371 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11372 + "\": has an active device admin"); 11373 return false; 11374 } 11375 11376 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 11377 if (packageName.equals(activeLauncherPackageName)) { 11378 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11379 + "\": contains the active launcher"); 11380 return false; 11381 } 11382 11383 if (packageName.equals(mRequiredInstallerPackage)) { 11384 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11385 + "\": required for package installation"); 11386 return false; 11387 } 11388 11389 if (packageName.equals(mRequiredVerifierPackage)) { 11390 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11391 + "\": required for package verification"); 11392 return false; 11393 } 11394 11395 final PackageParser.Package pkg = mPackages.get(packageName); 11396 if (pkg != null && isPrivilegedApp(pkg)) { 11397 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11398 + "\": is a privileged app"); 11399 return false; 11400 } 11401 11402 return true; 11403 } 11404 11405 private String getActiveLauncherPackageName(int userId) { 11406 Intent intent = new Intent(Intent.ACTION_MAIN); 11407 intent.addCategory(Intent.CATEGORY_HOME); 11408 ResolveInfo resolveInfo = resolveIntent( 11409 intent, 11410 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 11411 PackageManager.MATCH_DEFAULT_ONLY, 11412 userId); 11413 11414 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 11415 } 11416 11417 @Override 11418 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 11419 mContext.enforceCallingOrSelfPermission( 11420 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11421 "Only package verification agents can verify applications"); 11422 11423 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11424 final PackageVerificationResponse response = new PackageVerificationResponse( 11425 verificationCode, Binder.getCallingUid()); 11426 msg.arg1 = id; 11427 msg.obj = response; 11428 mHandler.sendMessage(msg); 11429 } 11430 11431 @Override 11432 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 11433 long millisecondsToDelay) { 11434 mContext.enforceCallingOrSelfPermission( 11435 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11436 "Only package verification agents can extend verification timeouts"); 11437 11438 final PackageVerificationState state = mPendingVerification.get(id); 11439 final PackageVerificationResponse response = new PackageVerificationResponse( 11440 verificationCodeAtTimeout, Binder.getCallingUid()); 11441 11442 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 11443 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 11444 } 11445 if (millisecondsToDelay < 0) { 11446 millisecondsToDelay = 0; 11447 } 11448 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 11449 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 11450 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 11451 } 11452 11453 if ((state != null) && !state.timeoutExtended()) { 11454 state.extendTimeout(); 11455 11456 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11457 msg.arg1 = id; 11458 msg.obj = response; 11459 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 11460 } 11461 } 11462 11463 private void broadcastPackageVerified(int verificationId, Uri packageUri, 11464 int verificationCode, UserHandle user) { 11465 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 11466 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 11467 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11468 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11469 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 11470 11471 mContext.sendBroadcastAsUser(intent, user, 11472 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 11473 } 11474 11475 private ComponentName matchComponentForVerifier(String packageName, 11476 List<ResolveInfo> receivers) { 11477 ActivityInfo targetReceiver = null; 11478 11479 final int NR = receivers.size(); 11480 for (int i = 0; i < NR; i++) { 11481 final ResolveInfo info = receivers.get(i); 11482 if (info.activityInfo == null) { 11483 continue; 11484 } 11485 11486 if (packageName.equals(info.activityInfo.packageName)) { 11487 targetReceiver = info.activityInfo; 11488 break; 11489 } 11490 } 11491 11492 if (targetReceiver == null) { 11493 return null; 11494 } 11495 11496 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 11497 } 11498 11499 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 11500 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 11501 if (pkgInfo.verifiers.length == 0) { 11502 return null; 11503 } 11504 11505 final int N = pkgInfo.verifiers.length; 11506 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 11507 for (int i = 0; i < N; i++) { 11508 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 11509 11510 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 11511 receivers); 11512 if (comp == null) { 11513 continue; 11514 } 11515 11516 final int verifierUid = getUidForVerifier(verifierInfo); 11517 if (verifierUid == -1) { 11518 continue; 11519 } 11520 11521 if (DEBUG_VERIFY) { 11522 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 11523 + " with the correct signature"); 11524 } 11525 sufficientVerifiers.add(comp); 11526 verificationState.addSufficientVerifier(verifierUid); 11527 } 11528 11529 return sufficientVerifiers; 11530 } 11531 11532 private int getUidForVerifier(VerifierInfo verifierInfo) { 11533 synchronized (mPackages) { 11534 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 11535 if (pkg == null) { 11536 return -1; 11537 } else if (pkg.mSignatures.length != 1) { 11538 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11539 + " has more than one signature; ignoring"); 11540 return -1; 11541 } 11542 11543 /* 11544 * If the public key of the package's signature does not match 11545 * our expected public key, then this is a different package and 11546 * we should skip. 11547 */ 11548 11549 final byte[] expectedPublicKey; 11550 try { 11551 final Signature verifierSig = pkg.mSignatures[0]; 11552 final PublicKey publicKey = verifierSig.getPublicKey(); 11553 expectedPublicKey = publicKey.getEncoded(); 11554 } catch (CertificateException e) { 11555 return -1; 11556 } 11557 11558 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 11559 11560 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 11561 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11562 + " does not have the expected public key; ignoring"); 11563 return -1; 11564 } 11565 11566 return pkg.applicationInfo.uid; 11567 } 11568 } 11569 11570 @Override 11571 public void finishPackageInstall(int token) { 11572 enforceSystemOrRoot("Only the system is allowed to finish installs"); 11573 11574 if (DEBUG_INSTALL) { 11575 Slog.v(TAG, "BM finishing package install for " + token); 11576 } 11577 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 11578 11579 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 11580 mHandler.sendMessage(msg); 11581 } 11582 11583 /** 11584 * Get the verification agent timeout. 11585 * 11586 * @return verification timeout in milliseconds 11587 */ 11588 private long getVerificationTimeout() { 11589 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 11590 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 11591 DEFAULT_VERIFICATION_TIMEOUT); 11592 } 11593 11594 /** 11595 * Get the default verification agent response code. 11596 * 11597 * @return default verification response code 11598 */ 11599 private int getDefaultVerificationResponse() { 11600 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11601 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 11602 DEFAULT_VERIFICATION_RESPONSE); 11603 } 11604 11605 /** 11606 * Check whether or not package verification has been enabled. 11607 * 11608 * @return true if verification should be performed 11609 */ 11610 private boolean isVerificationEnabled(int userId, int installFlags) { 11611 if (!DEFAULT_VERIFY_ENABLE) { 11612 return false; 11613 } 11614 // Ephemeral apps don't get the full verification treatment 11615 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11616 if (DEBUG_EPHEMERAL) { 11617 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 11618 } 11619 return false; 11620 } 11621 11622 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 11623 11624 // Check if installing from ADB 11625 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 11626 // Do not run verification in a test harness environment 11627 if (ActivityManager.isRunningInTestHarness()) { 11628 return false; 11629 } 11630 if (ensureVerifyAppsEnabled) { 11631 return true; 11632 } 11633 // Check if the developer does not want package verification for ADB installs 11634 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11635 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 11636 return false; 11637 } 11638 } 11639 11640 if (ensureVerifyAppsEnabled) { 11641 return true; 11642 } 11643 11644 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11645 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 11646 } 11647 11648 @Override 11649 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 11650 throws RemoteException { 11651 mContext.enforceCallingOrSelfPermission( 11652 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 11653 "Only intentfilter verification agents can verify applications"); 11654 11655 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 11656 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 11657 Binder.getCallingUid(), verificationCode, failedDomains); 11658 msg.arg1 = id; 11659 msg.obj = response; 11660 mHandler.sendMessage(msg); 11661 } 11662 11663 @Override 11664 public int getIntentVerificationStatus(String packageName, int userId) { 11665 synchronized (mPackages) { 11666 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 11667 } 11668 } 11669 11670 @Override 11671 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 11672 mContext.enforceCallingOrSelfPermission( 11673 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11674 11675 boolean result = false; 11676 synchronized (mPackages) { 11677 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 11678 } 11679 if (result) { 11680 scheduleWritePackageRestrictionsLocked(userId); 11681 } 11682 return result; 11683 } 11684 11685 @Override 11686 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 11687 String packageName) { 11688 synchronized (mPackages) { 11689 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 11690 } 11691 } 11692 11693 @Override 11694 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 11695 if (TextUtils.isEmpty(packageName)) { 11696 return ParceledListSlice.emptyList(); 11697 } 11698 synchronized (mPackages) { 11699 PackageParser.Package pkg = mPackages.get(packageName); 11700 if (pkg == null || pkg.activities == null) { 11701 return ParceledListSlice.emptyList(); 11702 } 11703 final int count = pkg.activities.size(); 11704 ArrayList<IntentFilter> result = new ArrayList<>(); 11705 for (int n=0; n<count; n++) { 11706 PackageParser.Activity activity = pkg.activities.get(n); 11707 if (activity.intents != null && activity.intents.size() > 0) { 11708 result.addAll(activity.intents); 11709 } 11710 } 11711 return new ParceledListSlice<>(result); 11712 } 11713 } 11714 11715 @Override 11716 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 11717 mContext.enforceCallingOrSelfPermission( 11718 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11719 11720 synchronized (mPackages) { 11721 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 11722 if (packageName != null) { 11723 result |= updateIntentVerificationStatus(packageName, 11724 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 11725 userId); 11726 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 11727 packageName, userId); 11728 } 11729 return result; 11730 } 11731 } 11732 11733 @Override 11734 public String getDefaultBrowserPackageName(int userId) { 11735 synchronized (mPackages) { 11736 return mSettings.getDefaultBrowserPackageNameLPw(userId); 11737 } 11738 } 11739 11740 /** 11741 * Get the "allow unknown sources" setting. 11742 * 11743 * @return the current "allow unknown sources" setting 11744 */ 11745 private int getUnknownSourcesSettings() { 11746 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 11747 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 11748 -1); 11749 } 11750 11751 @Override 11752 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 11753 final int uid = Binder.getCallingUid(); 11754 // writer 11755 synchronized (mPackages) { 11756 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 11757 if (targetPackageSetting == null) { 11758 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 11759 } 11760 11761 PackageSetting installerPackageSetting; 11762 if (installerPackageName != null) { 11763 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 11764 if (installerPackageSetting == null) { 11765 throw new IllegalArgumentException("Unknown installer package: " 11766 + installerPackageName); 11767 } 11768 } else { 11769 installerPackageSetting = null; 11770 } 11771 11772 Signature[] callerSignature; 11773 Object obj = mSettings.getUserIdLPr(uid); 11774 if (obj != null) { 11775 if (obj instanceof SharedUserSetting) { 11776 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 11777 } else if (obj instanceof PackageSetting) { 11778 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 11779 } else { 11780 throw new SecurityException("Bad object " + obj + " for uid " + uid); 11781 } 11782 } else { 11783 throw new SecurityException("Unknown calling UID: " + uid); 11784 } 11785 11786 // Verify: can't set installerPackageName to a package that is 11787 // not signed with the same cert as the caller. 11788 if (installerPackageSetting != null) { 11789 if (compareSignatures(callerSignature, 11790 installerPackageSetting.signatures.mSignatures) 11791 != PackageManager.SIGNATURE_MATCH) { 11792 throw new SecurityException( 11793 "Caller does not have same cert as new installer package " 11794 + installerPackageName); 11795 } 11796 } 11797 11798 // Verify: if target already has an installer package, it must 11799 // be signed with the same cert as the caller. 11800 if (targetPackageSetting.installerPackageName != null) { 11801 PackageSetting setting = mSettings.mPackages.get( 11802 targetPackageSetting.installerPackageName); 11803 // If the currently set package isn't valid, then it's always 11804 // okay to change it. 11805 if (setting != null) { 11806 if (compareSignatures(callerSignature, 11807 setting.signatures.mSignatures) 11808 != PackageManager.SIGNATURE_MATCH) { 11809 throw new SecurityException( 11810 "Caller does not have same cert as old installer package " 11811 + targetPackageSetting.installerPackageName); 11812 } 11813 } 11814 } 11815 11816 // Okay! 11817 targetPackageSetting.installerPackageName = installerPackageName; 11818 if (installerPackageName != null) { 11819 mSettings.mInstallerPackages.add(installerPackageName); 11820 } 11821 scheduleWriteSettingsLocked(); 11822 } 11823 } 11824 11825 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 11826 // Queue up an async operation since the package installation may take a little while. 11827 mHandler.post(new Runnable() { 11828 public void run() { 11829 mHandler.removeCallbacks(this); 11830 // Result object to be returned 11831 PackageInstalledInfo res = new PackageInstalledInfo(); 11832 res.setReturnCode(currentStatus); 11833 res.uid = -1; 11834 res.pkg = null; 11835 res.removedInfo = null; 11836 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11837 args.doPreInstall(res.returnCode); 11838 synchronized (mInstallLock) { 11839 installPackageTracedLI(args, res); 11840 } 11841 args.doPostInstall(res.returnCode, res.uid); 11842 } 11843 11844 // A restore should be performed at this point if (a) the install 11845 // succeeded, (b) the operation is not an update, and (c) the new 11846 // package has not opted out of backup participation. 11847 final boolean update = res.removedInfo != null 11848 && res.removedInfo.removedPackage != null; 11849 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 11850 boolean doRestore = !update 11851 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 11852 11853 // Set up the post-install work request bookkeeping. This will be used 11854 // and cleaned up by the post-install event handling regardless of whether 11855 // there's a restore pass performed. Token values are >= 1. 11856 int token; 11857 if (mNextInstallToken < 0) mNextInstallToken = 1; 11858 token = mNextInstallToken++; 11859 11860 PostInstallData data = new PostInstallData(args, res); 11861 mRunningInstalls.put(token, data); 11862 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 11863 11864 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 11865 // Pass responsibility to the Backup Manager. It will perform a 11866 // restore if appropriate, then pass responsibility back to the 11867 // Package Manager to run the post-install observer callbacks 11868 // and broadcasts. 11869 IBackupManager bm = IBackupManager.Stub.asInterface( 11870 ServiceManager.getService(Context.BACKUP_SERVICE)); 11871 if (bm != null) { 11872 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 11873 + " to BM for possible restore"); 11874 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 11875 try { 11876 // TODO: http://b/22388012 11877 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 11878 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 11879 } else { 11880 doRestore = false; 11881 } 11882 } catch (RemoteException e) { 11883 // can't happen; the backup manager is local 11884 } catch (Exception e) { 11885 Slog.e(TAG, "Exception trying to enqueue restore", e); 11886 doRestore = false; 11887 } 11888 } else { 11889 Slog.e(TAG, "Backup Manager not found!"); 11890 doRestore = false; 11891 } 11892 } 11893 11894 if (!doRestore) { 11895 // No restore possible, or the Backup Manager was mysteriously not 11896 // available -- just fire the post-install work request directly. 11897 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 11898 11899 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 11900 11901 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 11902 mHandler.sendMessage(msg); 11903 } 11904 } 11905 }); 11906 } 11907 11908 private abstract class HandlerParams { 11909 private static final int MAX_RETRIES = 4; 11910 11911 /** 11912 * Number of times startCopy() has been attempted and had a non-fatal 11913 * error. 11914 */ 11915 private int mRetries = 0; 11916 11917 /** User handle for the user requesting the information or installation. */ 11918 private final UserHandle mUser; 11919 String traceMethod; 11920 int traceCookie; 11921 11922 HandlerParams(UserHandle user) { 11923 mUser = user; 11924 } 11925 11926 UserHandle getUser() { 11927 return mUser; 11928 } 11929 11930 HandlerParams setTraceMethod(String traceMethod) { 11931 this.traceMethod = traceMethod; 11932 return this; 11933 } 11934 11935 HandlerParams setTraceCookie(int traceCookie) { 11936 this.traceCookie = traceCookie; 11937 return this; 11938 } 11939 11940 final boolean startCopy() { 11941 boolean res; 11942 try { 11943 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 11944 11945 if (++mRetries > MAX_RETRIES) { 11946 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 11947 mHandler.sendEmptyMessage(MCS_GIVE_UP); 11948 handleServiceError(); 11949 return false; 11950 } else { 11951 handleStartCopy(); 11952 res = true; 11953 } 11954 } catch (RemoteException e) { 11955 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 11956 mHandler.sendEmptyMessage(MCS_RECONNECT); 11957 res = false; 11958 } 11959 handleReturnCode(); 11960 return res; 11961 } 11962 11963 final void serviceError() { 11964 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 11965 handleServiceError(); 11966 handleReturnCode(); 11967 } 11968 11969 abstract void handleStartCopy() throws RemoteException; 11970 abstract void handleServiceError(); 11971 abstract void handleReturnCode(); 11972 } 11973 11974 class MeasureParams extends HandlerParams { 11975 private final PackageStats mStats; 11976 private boolean mSuccess; 11977 11978 private final IPackageStatsObserver mObserver; 11979 11980 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 11981 super(new UserHandle(stats.userHandle)); 11982 mObserver = observer; 11983 mStats = stats; 11984 } 11985 11986 @Override 11987 public String toString() { 11988 return "MeasureParams{" 11989 + Integer.toHexString(System.identityHashCode(this)) 11990 + " " + mStats.packageName + "}"; 11991 } 11992 11993 @Override 11994 void handleStartCopy() throws RemoteException { 11995 synchronized (mInstallLock) { 11996 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 11997 } 11998 11999 if (mSuccess) { 12000 final boolean mounted; 12001 if (Environment.isExternalStorageEmulated()) { 12002 mounted = true; 12003 } else { 12004 final String status = Environment.getExternalStorageState(); 12005 mounted = (Environment.MEDIA_MOUNTED.equals(status) 12006 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 12007 } 12008 12009 if (mounted) { 12010 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 12011 12012 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 12013 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 12014 12015 mStats.externalDataSize = calculateDirectorySize(mContainerService, 12016 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 12017 12018 // Always subtract cache size, since it's a subdirectory 12019 mStats.externalDataSize -= mStats.externalCacheSize; 12020 12021 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 12022 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 12023 12024 mStats.externalObbSize = calculateDirectorySize(mContainerService, 12025 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 12026 } 12027 } 12028 } 12029 12030 @Override 12031 void handleReturnCode() { 12032 if (mObserver != null) { 12033 try { 12034 mObserver.onGetStatsCompleted(mStats, mSuccess); 12035 } catch (RemoteException e) { 12036 Slog.i(TAG, "Observer no longer exists."); 12037 } 12038 } 12039 } 12040 12041 @Override 12042 void handleServiceError() { 12043 Slog.e(TAG, "Could not measure application " + mStats.packageName 12044 + " external storage"); 12045 } 12046 } 12047 12048 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 12049 throws RemoteException { 12050 long result = 0; 12051 for (File path : paths) { 12052 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 12053 } 12054 return result; 12055 } 12056 12057 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 12058 for (File path : paths) { 12059 try { 12060 mcs.clearDirectory(path.getAbsolutePath()); 12061 } catch (RemoteException e) { 12062 } 12063 } 12064 } 12065 12066 static class OriginInfo { 12067 /** 12068 * Location where install is coming from, before it has been 12069 * copied/renamed into place. This could be a single monolithic APK 12070 * file, or a cluster directory. This location may be untrusted. 12071 */ 12072 final File file; 12073 final String cid; 12074 12075 /** 12076 * Flag indicating that {@link #file} or {@link #cid} has already been 12077 * staged, meaning downstream users don't need to defensively copy the 12078 * contents. 12079 */ 12080 final boolean staged; 12081 12082 /** 12083 * Flag indicating that {@link #file} or {@link #cid} is an already 12084 * installed app that is being moved. 12085 */ 12086 final boolean existing; 12087 12088 final String resolvedPath; 12089 final File resolvedFile; 12090 12091 static OriginInfo fromNothing() { 12092 return new OriginInfo(null, null, false, false); 12093 } 12094 12095 static OriginInfo fromUntrustedFile(File file) { 12096 return new OriginInfo(file, null, false, false); 12097 } 12098 12099 static OriginInfo fromExistingFile(File file) { 12100 return new OriginInfo(file, null, false, true); 12101 } 12102 12103 static OriginInfo fromStagedFile(File file) { 12104 return new OriginInfo(file, null, true, false); 12105 } 12106 12107 static OriginInfo fromStagedContainer(String cid) { 12108 return new OriginInfo(null, cid, true, false); 12109 } 12110 12111 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 12112 this.file = file; 12113 this.cid = cid; 12114 this.staged = staged; 12115 this.existing = existing; 12116 12117 if (cid != null) { 12118 resolvedPath = PackageHelper.getSdDir(cid); 12119 resolvedFile = new File(resolvedPath); 12120 } else if (file != null) { 12121 resolvedPath = file.getAbsolutePath(); 12122 resolvedFile = file; 12123 } else { 12124 resolvedPath = null; 12125 resolvedFile = null; 12126 } 12127 } 12128 } 12129 12130 static class MoveInfo { 12131 final int moveId; 12132 final String fromUuid; 12133 final String toUuid; 12134 final String packageName; 12135 final String dataAppName; 12136 final int appId; 12137 final String seinfo; 12138 final int targetSdkVersion; 12139 12140 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 12141 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 12142 this.moveId = moveId; 12143 this.fromUuid = fromUuid; 12144 this.toUuid = toUuid; 12145 this.packageName = packageName; 12146 this.dataAppName = dataAppName; 12147 this.appId = appId; 12148 this.seinfo = seinfo; 12149 this.targetSdkVersion = targetSdkVersion; 12150 } 12151 } 12152 12153 static class VerificationInfo { 12154 /** A constant used to indicate that a uid value is not present. */ 12155 public static final int NO_UID = -1; 12156 12157 /** URI referencing where the package was downloaded from. */ 12158 final Uri originatingUri; 12159 12160 /** HTTP referrer URI associated with the originatingURI. */ 12161 final Uri referrer; 12162 12163 /** UID of the application that the install request originated from. */ 12164 final int originatingUid; 12165 12166 /** UID of application requesting the install */ 12167 final int installerUid; 12168 12169 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 12170 this.originatingUri = originatingUri; 12171 this.referrer = referrer; 12172 this.originatingUid = originatingUid; 12173 this.installerUid = installerUid; 12174 } 12175 } 12176 12177 class InstallParams extends HandlerParams { 12178 final OriginInfo origin; 12179 final MoveInfo move; 12180 final IPackageInstallObserver2 observer; 12181 int installFlags; 12182 final String installerPackageName; 12183 final String volumeUuid; 12184 private InstallArgs mArgs; 12185 private int mRet; 12186 final String packageAbiOverride; 12187 final String[] grantedRuntimePermissions; 12188 final VerificationInfo verificationInfo; 12189 final Certificate[][] certificates; 12190 12191 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12192 int installFlags, String installerPackageName, String volumeUuid, 12193 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 12194 String[] grantedPermissions, Certificate[][] certificates) { 12195 super(user); 12196 this.origin = origin; 12197 this.move = move; 12198 this.observer = observer; 12199 this.installFlags = installFlags; 12200 this.installerPackageName = installerPackageName; 12201 this.volumeUuid = volumeUuid; 12202 this.verificationInfo = verificationInfo; 12203 this.packageAbiOverride = packageAbiOverride; 12204 this.grantedRuntimePermissions = grantedPermissions; 12205 this.certificates = certificates; 12206 } 12207 12208 @Override 12209 public String toString() { 12210 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 12211 + " file=" + origin.file + " cid=" + origin.cid + "}"; 12212 } 12213 12214 private int installLocationPolicy(PackageInfoLite pkgLite) { 12215 String packageName = pkgLite.packageName; 12216 int installLocation = pkgLite.installLocation; 12217 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12218 // reader 12219 synchronized (mPackages) { 12220 // Currently installed package which the new package is attempting to replace or 12221 // null if no such package is installed. 12222 PackageParser.Package installedPkg = mPackages.get(packageName); 12223 // Package which currently owns the data which the new package will own if installed. 12224 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 12225 // will be null whereas dataOwnerPkg will contain information about the package 12226 // which was uninstalled while keeping its data. 12227 PackageParser.Package dataOwnerPkg = installedPkg; 12228 if (dataOwnerPkg == null) { 12229 PackageSetting ps = mSettings.mPackages.get(packageName); 12230 if (ps != null) { 12231 dataOwnerPkg = ps.pkg; 12232 } 12233 } 12234 12235 if (dataOwnerPkg != null) { 12236 // If installed, the package will get access to data left on the device by its 12237 // predecessor. As a security measure, this is permited only if this is not a 12238 // version downgrade or if the predecessor package is marked as debuggable and 12239 // a downgrade is explicitly requested. 12240 // 12241 // On debuggable platform builds, downgrades are permitted even for 12242 // non-debuggable packages to make testing easier. Debuggable platform builds do 12243 // not offer security guarantees and thus it's OK to disable some security 12244 // mechanisms to make debugging/testing easier on those builds. However, even on 12245 // debuggable builds downgrades of packages are permitted only if requested via 12246 // installFlags. This is because we aim to keep the behavior of debuggable 12247 // platform builds as close as possible to the behavior of non-debuggable 12248 // platform builds. 12249 final boolean downgradeRequested = 12250 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 12251 final boolean packageDebuggable = 12252 (dataOwnerPkg.applicationInfo.flags 12253 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 12254 final boolean downgradePermitted = 12255 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 12256 if (!downgradePermitted) { 12257 try { 12258 checkDowngrade(dataOwnerPkg, pkgLite); 12259 } catch (PackageManagerException e) { 12260 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 12261 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 12262 } 12263 } 12264 } 12265 12266 if (installedPkg != null) { 12267 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12268 // Check for updated system application. 12269 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 12270 if (onSd) { 12271 Slog.w(TAG, "Cannot install update to system app on sdcard"); 12272 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 12273 } 12274 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12275 } else { 12276 if (onSd) { 12277 // Install flag overrides everything. 12278 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12279 } 12280 // If current upgrade specifies particular preference 12281 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 12282 // Application explicitly specified internal. 12283 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12284 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 12285 // App explictly prefers external. Let policy decide 12286 } else { 12287 // Prefer previous location 12288 if (isExternal(installedPkg)) { 12289 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12290 } 12291 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12292 } 12293 } 12294 } else { 12295 // Invalid install. Return error code 12296 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 12297 } 12298 } 12299 } 12300 // All the special cases have been taken care of. 12301 // Return result based on recommended install location. 12302 if (onSd) { 12303 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12304 } 12305 return pkgLite.recommendedInstallLocation; 12306 } 12307 12308 /* 12309 * Invoke remote method to get package information and install 12310 * location values. Override install location based on default 12311 * policy if needed and then create install arguments based 12312 * on the install location. 12313 */ 12314 public void handleStartCopy() throws RemoteException { 12315 int ret = PackageManager.INSTALL_SUCCEEDED; 12316 12317 // If we're already staged, we've firmly committed to an install location 12318 if (origin.staged) { 12319 if (origin.file != null) { 12320 installFlags |= PackageManager.INSTALL_INTERNAL; 12321 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12322 } else if (origin.cid != null) { 12323 installFlags |= PackageManager.INSTALL_EXTERNAL; 12324 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12325 } else { 12326 throw new IllegalStateException("Invalid stage location"); 12327 } 12328 } 12329 12330 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12331 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 12332 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12333 PackageInfoLite pkgLite = null; 12334 12335 if (onInt && onSd) { 12336 // Check if both bits are set. 12337 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 12338 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12339 } else if (onSd && ephemeral) { 12340 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 12341 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12342 } else { 12343 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 12344 packageAbiOverride); 12345 12346 if (DEBUG_EPHEMERAL && ephemeral) { 12347 Slog.v(TAG, "pkgLite for install: " + pkgLite); 12348 } 12349 12350 /* 12351 * If we have too little free space, try to free cache 12352 * before giving up. 12353 */ 12354 if (!origin.staged && pkgLite.recommendedInstallLocation 12355 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12356 // TODO: focus freeing disk space on the target device 12357 final StorageManager storage = StorageManager.from(mContext); 12358 final long lowThreshold = storage.getStorageLowBytes( 12359 Environment.getDataDirectory()); 12360 12361 final long sizeBytes = mContainerService.calculateInstalledSize( 12362 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 12363 12364 try { 12365 mInstaller.freeCache(null, sizeBytes + lowThreshold); 12366 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 12367 installFlags, packageAbiOverride); 12368 } catch (InstallerException e) { 12369 Slog.w(TAG, "Failed to free cache", e); 12370 } 12371 12372 /* 12373 * The cache free must have deleted the file we 12374 * downloaded to install. 12375 * 12376 * TODO: fix the "freeCache" call to not delete 12377 * the file we care about. 12378 */ 12379 if (pkgLite.recommendedInstallLocation 12380 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12381 pkgLite.recommendedInstallLocation 12382 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 12383 } 12384 } 12385 } 12386 12387 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12388 int loc = pkgLite.recommendedInstallLocation; 12389 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 12390 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12391 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 12392 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 12393 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12394 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12395 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 12396 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 12397 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12398 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 12399 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 12400 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 12401 } else { 12402 // Override with defaults if needed. 12403 loc = installLocationPolicy(pkgLite); 12404 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 12405 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 12406 } else if (!onSd && !onInt) { 12407 // Override install location with flags 12408 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 12409 // Set the flag to install on external media. 12410 installFlags |= PackageManager.INSTALL_EXTERNAL; 12411 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12412 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 12413 if (DEBUG_EPHEMERAL) { 12414 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 12415 } 12416 installFlags |= PackageManager.INSTALL_EPHEMERAL; 12417 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 12418 |PackageManager.INSTALL_INTERNAL); 12419 } else { 12420 // Make sure the flag for installing on external 12421 // media is unset 12422 installFlags |= PackageManager.INSTALL_INTERNAL; 12423 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12424 } 12425 } 12426 } 12427 } 12428 12429 final InstallArgs args = createInstallArgs(this); 12430 mArgs = args; 12431 12432 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12433 // TODO: http://b/22976637 12434 // Apps installed for "all" users use the device owner to verify the app 12435 UserHandle verifierUser = getUser(); 12436 if (verifierUser == UserHandle.ALL) { 12437 verifierUser = UserHandle.SYSTEM; 12438 } 12439 12440 /* 12441 * Determine if we have any installed package verifiers. If we 12442 * do, then we'll defer to them to verify the packages. 12443 */ 12444 final int requiredUid = mRequiredVerifierPackage == null ? -1 12445 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 12446 verifierUser.getIdentifier()); 12447 if (!origin.existing && requiredUid != -1 12448 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 12449 final Intent verification = new Intent( 12450 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 12451 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 12452 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 12453 PACKAGE_MIME_TYPE); 12454 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 12455 12456 // Query all live verifiers based on current user state 12457 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 12458 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 12459 12460 if (DEBUG_VERIFY) { 12461 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 12462 + verification.toString() + " with " + pkgLite.verifiers.length 12463 + " optional verifiers"); 12464 } 12465 12466 final int verificationId = mPendingVerificationToken++; 12467 12468 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 12469 12470 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 12471 installerPackageName); 12472 12473 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 12474 installFlags); 12475 12476 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 12477 pkgLite.packageName); 12478 12479 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 12480 pkgLite.versionCode); 12481 12482 if (verificationInfo != null) { 12483 if (verificationInfo.originatingUri != null) { 12484 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 12485 verificationInfo.originatingUri); 12486 } 12487 if (verificationInfo.referrer != null) { 12488 verification.putExtra(Intent.EXTRA_REFERRER, 12489 verificationInfo.referrer); 12490 } 12491 if (verificationInfo.originatingUid >= 0) { 12492 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 12493 verificationInfo.originatingUid); 12494 } 12495 if (verificationInfo.installerUid >= 0) { 12496 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 12497 verificationInfo.installerUid); 12498 } 12499 } 12500 12501 final PackageVerificationState verificationState = new PackageVerificationState( 12502 requiredUid, args); 12503 12504 mPendingVerification.append(verificationId, verificationState); 12505 12506 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 12507 receivers, verificationState); 12508 12509 /* 12510 * If any sufficient verifiers were listed in the package 12511 * manifest, attempt to ask them. 12512 */ 12513 if (sufficientVerifiers != null) { 12514 final int N = sufficientVerifiers.size(); 12515 if (N == 0) { 12516 Slog.i(TAG, "Additional verifiers required, but none installed."); 12517 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 12518 } else { 12519 for (int i = 0; i < N; i++) { 12520 final ComponentName verifierComponent = sufficientVerifiers.get(i); 12521 12522 final Intent sufficientIntent = new Intent(verification); 12523 sufficientIntent.setComponent(verifierComponent); 12524 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 12525 } 12526 } 12527 } 12528 12529 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 12530 mRequiredVerifierPackage, receivers); 12531 if (ret == PackageManager.INSTALL_SUCCEEDED 12532 && mRequiredVerifierPackage != null) { 12533 Trace.asyncTraceBegin( 12534 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 12535 /* 12536 * Send the intent to the required verification agent, 12537 * but only start the verification timeout after the 12538 * target BroadcastReceivers have run. 12539 */ 12540 verification.setComponent(requiredVerifierComponent); 12541 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 12542 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12543 new BroadcastReceiver() { 12544 @Override 12545 public void onReceive(Context context, Intent intent) { 12546 final Message msg = mHandler 12547 .obtainMessage(CHECK_PENDING_VERIFICATION); 12548 msg.arg1 = verificationId; 12549 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 12550 } 12551 }, null, 0, null, null); 12552 12553 /* 12554 * We don't want the copy to proceed until verification 12555 * succeeds, so null out this field. 12556 */ 12557 mArgs = null; 12558 } 12559 } else { 12560 /* 12561 * No package verification is enabled, so immediately start 12562 * the remote call to initiate copy using temporary file. 12563 */ 12564 ret = args.copyApk(mContainerService, true); 12565 } 12566 } 12567 12568 mRet = ret; 12569 } 12570 12571 @Override 12572 void handleReturnCode() { 12573 // If mArgs is null, then MCS couldn't be reached. When it 12574 // reconnects, it will try again to install. At that point, this 12575 // will succeed. 12576 if (mArgs != null) { 12577 processPendingInstall(mArgs, mRet); 12578 } 12579 } 12580 12581 @Override 12582 void handleServiceError() { 12583 mArgs = createInstallArgs(this); 12584 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12585 } 12586 12587 public boolean isForwardLocked() { 12588 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12589 } 12590 } 12591 12592 /** 12593 * Used during creation of InstallArgs 12594 * 12595 * @param installFlags package installation flags 12596 * @return true if should be installed on external storage 12597 */ 12598 private static boolean installOnExternalAsec(int installFlags) { 12599 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 12600 return false; 12601 } 12602 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 12603 return true; 12604 } 12605 return false; 12606 } 12607 12608 /** 12609 * Used during creation of InstallArgs 12610 * 12611 * @param installFlags package installation flags 12612 * @return true if should be installed as forward locked 12613 */ 12614 private static boolean installForwardLocked(int installFlags) { 12615 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12616 } 12617 12618 private InstallArgs createInstallArgs(InstallParams params) { 12619 if (params.move != null) { 12620 return new MoveInstallArgs(params); 12621 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 12622 return new AsecInstallArgs(params); 12623 } else { 12624 return new FileInstallArgs(params); 12625 } 12626 } 12627 12628 /** 12629 * Create args that describe an existing installed package. Typically used 12630 * when cleaning up old installs, or used as a move source. 12631 */ 12632 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 12633 String resourcePath, String[] instructionSets) { 12634 final boolean isInAsec; 12635 if (installOnExternalAsec(installFlags)) { 12636 /* Apps on SD card are always in ASEC containers. */ 12637 isInAsec = true; 12638 } else if (installForwardLocked(installFlags) 12639 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 12640 /* 12641 * Forward-locked apps are only in ASEC containers if they're the 12642 * new style 12643 */ 12644 isInAsec = true; 12645 } else { 12646 isInAsec = false; 12647 } 12648 12649 if (isInAsec) { 12650 return new AsecInstallArgs(codePath, instructionSets, 12651 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 12652 } else { 12653 return new FileInstallArgs(codePath, resourcePath, instructionSets); 12654 } 12655 } 12656 12657 static abstract class InstallArgs { 12658 /** @see InstallParams#origin */ 12659 final OriginInfo origin; 12660 /** @see InstallParams#move */ 12661 final MoveInfo move; 12662 12663 final IPackageInstallObserver2 observer; 12664 // Always refers to PackageManager flags only 12665 final int installFlags; 12666 final String installerPackageName; 12667 final String volumeUuid; 12668 final UserHandle user; 12669 final String abiOverride; 12670 final String[] installGrantPermissions; 12671 /** If non-null, drop an async trace when the install completes */ 12672 final String traceMethod; 12673 final int traceCookie; 12674 final Certificate[][] certificates; 12675 12676 // The list of instruction sets supported by this app. This is currently 12677 // only used during the rmdex() phase to clean up resources. We can get rid of this 12678 // if we move dex files under the common app path. 12679 /* nullable */ String[] instructionSets; 12680 12681 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12682 int installFlags, String installerPackageName, String volumeUuid, 12683 UserHandle user, String[] instructionSets, 12684 String abiOverride, String[] installGrantPermissions, 12685 String traceMethod, int traceCookie, Certificate[][] certificates) { 12686 this.origin = origin; 12687 this.move = move; 12688 this.installFlags = installFlags; 12689 this.observer = observer; 12690 this.installerPackageName = installerPackageName; 12691 this.volumeUuid = volumeUuid; 12692 this.user = user; 12693 this.instructionSets = instructionSets; 12694 this.abiOverride = abiOverride; 12695 this.installGrantPermissions = installGrantPermissions; 12696 this.traceMethod = traceMethod; 12697 this.traceCookie = traceCookie; 12698 this.certificates = certificates; 12699 } 12700 12701 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 12702 abstract int doPreInstall(int status); 12703 12704 /** 12705 * Rename package into final resting place. All paths on the given 12706 * scanned package should be updated to reflect the rename. 12707 */ 12708 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 12709 abstract int doPostInstall(int status, int uid); 12710 12711 /** @see PackageSettingBase#codePathString */ 12712 abstract String getCodePath(); 12713 /** @see PackageSettingBase#resourcePathString */ 12714 abstract String getResourcePath(); 12715 12716 // Need installer lock especially for dex file removal. 12717 abstract void cleanUpResourcesLI(); 12718 abstract boolean doPostDeleteLI(boolean delete); 12719 12720 /** 12721 * Called before the source arguments are copied. This is used mostly 12722 * for MoveParams when it needs to read the source file to put it in the 12723 * destination. 12724 */ 12725 int doPreCopy() { 12726 return PackageManager.INSTALL_SUCCEEDED; 12727 } 12728 12729 /** 12730 * Called after the source arguments are copied. This is used mostly for 12731 * MoveParams when it needs to read the source file to put it in the 12732 * destination. 12733 */ 12734 int doPostCopy(int uid) { 12735 return PackageManager.INSTALL_SUCCEEDED; 12736 } 12737 12738 protected boolean isFwdLocked() { 12739 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12740 } 12741 12742 protected boolean isExternalAsec() { 12743 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12744 } 12745 12746 protected boolean isEphemeral() { 12747 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12748 } 12749 12750 UserHandle getUser() { 12751 return user; 12752 } 12753 } 12754 12755 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 12756 if (!allCodePaths.isEmpty()) { 12757 if (instructionSets == null) { 12758 throw new IllegalStateException("instructionSet == null"); 12759 } 12760 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 12761 for (String codePath : allCodePaths) { 12762 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 12763 try { 12764 mInstaller.rmdex(codePath, dexCodeInstructionSet); 12765 } catch (InstallerException ignored) { 12766 } 12767 } 12768 } 12769 } 12770 } 12771 12772 /** 12773 * Logic to handle installation of non-ASEC applications, including copying 12774 * and renaming logic. 12775 */ 12776 class FileInstallArgs extends InstallArgs { 12777 private File codeFile; 12778 private File resourceFile; 12779 12780 // Example topology: 12781 // /data/app/com.example/base.apk 12782 // /data/app/com.example/split_foo.apk 12783 // /data/app/com.example/lib/arm/libfoo.so 12784 // /data/app/com.example/lib/arm64/libfoo.so 12785 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 12786 12787 /** New install */ 12788 FileInstallArgs(InstallParams params) { 12789 super(params.origin, params.move, params.observer, params.installFlags, 12790 params.installerPackageName, params.volumeUuid, 12791 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 12792 params.grantedRuntimePermissions, 12793 params.traceMethod, params.traceCookie, params.certificates); 12794 if (isFwdLocked()) { 12795 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 12796 } 12797 } 12798 12799 /** Existing install */ 12800 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 12801 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 12802 null, null, null, 0, null /*certificates*/); 12803 this.codeFile = (codePath != null) ? new File(codePath) : null; 12804 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 12805 } 12806 12807 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12808 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 12809 try { 12810 return doCopyApk(imcs, temp); 12811 } finally { 12812 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12813 } 12814 } 12815 12816 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12817 if (origin.staged) { 12818 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 12819 codeFile = origin.file; 12820 resourceFile = origin.file; 12821 return PackageManager.INSTALL_SUCCEEDED; 12822 } 12823 12824 try { 12825 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12826 final File tempDir = 12827 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 12828 codeFile = tempDir; 12829 resourceFile = tempDir; 12830 } catch (IOException e) { 12831 Slog.w(TAG, "Failed to create copy file: " + e); 12832 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12833 } 12834 12835 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 12836 @Override 12837 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 12838 if (!FileUtils.isValidExtFilename(name)) { 12839 throw new IllegalArgumentException("Invalid filename: " + name); 12840 } 12841 try { 12842 final File file = new File(codeFile, name); 12843 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 12844 O_RDWR | O_CREAT, 0644); 12845 Os.chmod(file.getAbsolutePath(), 0644); 12846 return new ParcelFileDescriptor(fd); 12847 } catch (ErrnoException e) { 12848 throw new RemoteException("Failed to open: " + e.getMessage()); 12849 } 12850 } 12851 }; 12852 12853 int ret = PackageManager.INSTALL_SUCCEEDED; 12854 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 12855 if (ret != PackageManager.INSTALL_SUCCEEDED) { 12856 Slog.e(TAG, "Failed to copy package"); 12857 return ret; 12858 } 12859 12860 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 12861 NativeLibraryHelper.Handle handle = null; 12862 try { 12863 handle = NativeLibraryHelper.Handle.create(codeFile); 12864 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 12865 abiOverride); 12866 } catch (IOException e) { 12867 Slog.e(TAG, "Copying native libraries failed", e); 12868 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12869 } finally { 12870 IoUtils.closeQuietly(handle); 12871 } 12872 12873 return ret; 12874 } 12875 12876 int doPreInstall(int status) { 12877 if (status != PackageManager.INSTALL_SUCCEEDED) { 12878 cleanUp(); 12879 } 12880 return status; 12881 } 12882 12883 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 12884 if (status != PackageManager.INSTALL_SUCCEEDED) { 12885 cleanUp(); 12886 return false; 12887 } 12888 12889 final File targetDir = codeFile.getParentFile(); 12890 final File beforeCodeFile = codeFile; 12891 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 12892 12893 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 12894 try { 12895 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 12896 } catch (ErrnoException e) { 12897 Slog.w(TAG, "Failed to rename", e); 12898 return false; 12899 } 12900 12901 if (!SELinux.restoreconRecursive(afterCodeFile)) { 12902 Slog.w(TAG, "Failed to restorecon"); 12903 return false; 12904 } 12905 12906 // Reflect the rename internally 12907 codeFile = afterCodeFile; 12908 resourceFile = afterCodeFile; 12909 12910 // Reflect the rename in scanned details 12911 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 12912 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 12913 afterCodeFile, pkg.baseCodePath)); 12914 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 12915 afterCodeFile, pkg.splitCodePaths)); 12916 12917 // Reflect the rename in app info 12918 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 12919 pkg.setApplicationInfoCodePath(pkg.codePath); 12920 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 12921 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 12922 pkg.setApplicationInfoResourcePath(pkg.codePath); 12923 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 12924 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 12925 12926 return true; 12927 } 12928 12929 int doPostInstall(int status, int uid) { 12930 if (status != PackageManager.INSTALL_SUCCEEDED) { 12931 cleanUp(); 12932 } 12933 return status; 12934 } 12935 12936 @Override 12937 String getCodePath() { 12938 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 12939 } 12940 12941 @Override 12942 String getResourcePath() { 12943 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 12944 } 12945 12946 private boolean cleanUp() { 12947 if (codeFile == null || !codeFile.exists()) { 12948 return false; 12949 } 12950 12951 removeCodePathLI(codeFile); 12952 12953 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 12954 resourceFile.delete(); 12955 } 12956 12957 return true; 12958 } 12959 12960 void cleanUpResourcesLI() { 12961 // Try enumerating all code paths before deleting 12962 List<String> allCodePaths = Collections.EMPTY_LIST; 12963 if (codeFile != null && codeFile.exists()) { 12964 try { 12965 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 12966 allCodePaths = pkg.getAllCodePaths(); 12967 } catch (PackageParserException e) { 12968 // Ignored; we tried our best 12969 } 12970 } 12971 12972 cleanUp(); 12973 removeDexFiles(allCodePaths, instructionSets); 12974 } 12975 12976 boolean doPostDeleteLI(boolean delete) { 12977 // XXX err, shouldn't we respect the delete flag? 12978 cleanUpResourcesLI(); 12979 return true; 12980 } 12981 } 12982 12983 private boolean isAsecExternal(String cid) { 12984 final String asecPath = PackageHelper.getSdFilesystem(cid); 12985 return !asecPath.startsWith(mAsecInternalPath); 12986 } 12987 12988 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 12989 PackageManagerException { 12990 if (copyRet < 0) { 12991 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 12992 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 12993 throw new PackageManagerException(copyRet, message); 12994 } 12995 } 12996 } 12997 12998 /** 12999 * Extract the MountService "container ID" from the full code path of an 13000 * .apk. 13001 */ 13002 static String cidFromCodePath(String fullCodePath) { 13003 int eidx = fullCodePath.lastIndexOf("/"); 13004 String subStr1 = fullCodePath.substring(0, eidx); 13005 int sidx = subStr1.lastIndexOf("/"); 13006 return subStr1.substring(sidx+1, eidx); 13007 } 13008 13009 /** 13010 * Logic to handle installation of ASEC applications, including copying and 13011 * renaming logic. 13012 */ 13013 class AsecInstallArgs extends InstallArgs { 13014 static final String RES_FILE_NAME = "pkg.apk"; 13015 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 13016 13017 String cid; 13018 String packagePath; 13019 String resourcePath; 13020 13021 /** New install */ 13022 AsecInstallArgs(InstallParams params) { 13023 super(params.origin, params.move, params.observer, params.installFlags, 13024 params.installerPackageName, params.volumeUuid, 13025 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13026 params.grantedRuntimePermissions, 13027 params.traceMethod, params.traceCookie, params.certificates); 13028 } 13029 13030 /** Existing install */ 13031 AsecInstallArgs(String fullCodePath, String[] instructionSets, 13032 boolean isExternal, boolean isForwardLocked) { 13033 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 13034 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13035 instructionSets, null, null, null, 0, null /*certificates*/); 13036 // Hackily pretend we're still looking at a full code path 13037 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 13038 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 13039 } 13040 13041 // Extract cid from fullCodePath 13042 int eidx = fullCodePath.lastIndexOf("/"); 13043 String subStr1 = fullCodePath.substring(0, eidx); 13044 int sidx = subStr1.lastIndexOf("/"); 13045 cid = subStr1.substring(sidx+1, eidx); 13046 setMountPath(subStr1); 13047 } 13048 13049 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 13050 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 13051 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13052 instructionSets, null, null, null, 0, null /*certificates*/); 13053 this.cid = cid; 13054 setMountPath(PackageHelper.getSdDir(cid)); 13055 } 13056 13057 void createCopyFile() { 13058 cid = mInstallerService.allocateExternalStageCidLegacy(); 13059 } 13060 13061 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13062 if (origin.staged && origin.cid != null) { 13063 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 13064 cid = origin.cid; 13065 setMountPath(PackageHelper.getSdDir(cid)); 13066 return PackageManager.INSTALL_SUCCEEDED; 13067 } 13068 13069 if (temp) { 13070 createCopyFile(); 13071 } else { 13072 /* 13073 * Pre-emptively destroy the container since it's destroyed if 13074 * copying fails due to it existing anyway. 13075 */ 13076 PackageHelper.destroySdDir(cid); 13077 } 13078 13079 final String newMountPath = imcs.copyPackageToContainer( 13080 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 13081 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 13082 13083 if (newMountPath != null) { 13084 setMountPath(newMountPath); 13085 return PackageManager.INSTALL_SUCCEEDED; 13086 } else { 13087 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13088 } 13089 } 13090 13091 @Override 13092 String getCodePath() { 13093 return packagePath; 13094 } 13095 13096 @Override 13097 String getResourcePath() { 13098 return resourcePath; 13099 } 13100 13101 int doPreInstall(int status) { 13102 if (status != PackageManager.INSTALL_SUCCEEDED) { 13103 // Destroy container 13104 PackageHelper.destroySdDir(cid); 13105 } else { 13106 boolean mounted = PackageHelper.isContainerMounted(cid); 13107 if (!mounted) { 13108 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 13109 Process.SYSTEM_UID); 13110 if (newMountPath != null) { 13111 setMountPath(newMountPath); 13112 } else { 13113 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13114 } 13115 } 13116 } 13117 return status; 13118 } 13119 13120 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13121 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 13122 String newMountPath = null; 13123 if (PackageHelper.isContainerMounted(cid)) { 13124 // Unmount the container 13125 if (!PackageHelper.unMountSdDir(cid)) { 13126 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 13127 return false; 13128 } 13129 } 13130 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13131 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 13132 " which might be stale. Will try to clean up."); 13133 // Clean up the stale container and proceed to recreate. 13134 if (!PackageHelper.destroySdDir(newCacheId)) { 13135 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 13136 return false; 13137 } 13138 // Successfully cleaned up stale container. Try to rename again. 13139 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13140 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 13141 + " inspite of cleaning it up."); 13142 return false; 13143 } 13144 } 13145 if (!PackageHelper.isContainerMounted(newCacheId)) { 13146 Slog.w(TAG, "Mounting container " + newCacheId); 13147 newMountPath = PackageHelper.mountSdDir(newCacheId, 13148 getEncryptKey(), Process.SYSTEM_UID); 13149 } else { 13150 newMountPath = PackageHelper.getSdDir(newCacheId); 13151 } 13152 if (newMountPath == null) { 13153 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 13154 return false; 13155 } 13156 Log.i(TAG, "Succesfully renamed " + cid + 13157 " to " + newCacheId + 13158 " at new path: " + newMountPath); 13159 cid = newCacheId; 13160 13161 final File beforeCodeFile = new File(packagePath); 13162 setMountPath(newMountPath); 13163 final File afterCodeFile = new File(packagePath); 13164 13165 // Reflect the rename in scanned details 13166 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13167 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13168 afterCodeFile, pkg.baseCodePath)); 13169 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13170 afterCodeFile, pkg.splitCodePaths)); 13171 13172 // Reflect the rename in app info 13173 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13174 pkg.setApplicationInfoCodePath(pkg.codePath); 13175 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13176 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13177 pkg.setApplicationInfoResourcePath(pkg.codePath); 13178 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13179 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13180 13181 return true; 13182 } 13183 13184 private void setMountPath(String mountPath) { 13185 final File mountFile = new File(mountPath); 13186 13187 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 13188 if (monolithicFile.exists()) { 13189 packagePath = monolithicFile.getAbsolutePath(); 13190 if (isFwdLocked()) { 13191 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 13192 } else { 13193 resourcePath = packagePath; 13194 } 13195 } else { 13196 packagePath = mountFile.getAbsolutePath(); 13197 resourcePath = packagePath; 13198 } 13199 } 13200 13201 int doPostInstall(int status, int uid) { 13202 if (status != PackageManager.INSTALL_SUCCEEDED) { 13203 cleanUp(); 13204 } else { 13205 final int groupOwner; 13206 final String protectedFile; 13207 if (isFwdLocked()) { 13208 groupOwner = UserHandle.getSharedAppGid(uid); 13209 protectedFile = RES_FILE_NAME; 13210 } else { 13211 groupOwner = -1; 13212 protectedFile = null; 13213 } 13214 13215 if (uid < Process.FIRST_APPLICATION_UID 13216 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 13217 Slog.e(TAG, "Failed to finalize " + cid); 13218 PackageHelper.destroySdDir(cid); 13219 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13220 } 13221 13222 boolean mounted = PackageHelper.isContainerMounted(cid); 13223 if (!mounted) { 13224 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 13225 } 13226 } 13227 return status; 13228 } 13229 13230 private void cleanUp() { 13231 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 13232 13233 // Destroy secure container 13234 PackageHelper.destroySdDir(cid); 13235 } 13236 13237 private List<String> getAllCodePaths() { 13238 final File codeFile = new File(getCodePath()); 13239 if (codeFile != null && codeFile.exists()) { 13240 try { 13241 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13242 return pkg.getAllCodePaths(); 13243 } catch (PackageParserException e) { 13244 // Ignored; we tried our best 13245 } 13246 } 13247 return Collections.EMPTY_LIST; 13248 } 13249 13250 void cleanUpResourcesLI() { 13251 // Enumerate all code paths before deleting 13252 cleanUpResourcesLI(getAllCodePaths()); 13253 } 13254 13255 private void cleanUpResourcesLI(List<String> allCodePaths) { 13256 cleanUp(); 13257 removeDexFiles(allCodePaths, instructionSets); 13258 } 13259 13260 String getPackageName() { 13261 return getAsecPackageName(cid); 13262 } 13263 13264 boolean doPostDeleteLI(boolean delete) { 13265 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 13266 final List<String> allCodePaths = getAllCodePaths(); 13267 boolean mounted = PackageHelper.isContainerMounted(cid); 13268 if (mounted) { 13269 // Unmount first 13270 if (PackageHelper.unMountSdDir(cid)) { 13271 mounted = false; 13272 } 13273 } 13274 if (!mounted && delete) { 13275 cleanUpResourcesLI(allCodePaths); 13276 } 13277 return !mounted; 13278 } 13279 13280 @Override 13281 int doPreCopy() { 13282 if (isFwdLocked()) { 13283 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 13284 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 13285 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13286 } 13287 } 13288 13289 return PackageManager.INSTALL_SUCCEEDED; 13290 } 13291 13292 @Override 13293 int doPostCopy(int uid) { 13294 if (isFwdLocked()) { 13295 if (uid < Process.FIRST_APPLICATION_UID 13296 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 13297 RES_FILE_NAME)) { 13298 Slog.e(TAG, "Failed to finalize " + cid); 13299 PackageHelper.destroySdDir(cid); 13300 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13301 } 13302 } 13303 13304 return PackageManager.INSTALL_SUCCEEDED; 13305 } 13306 } 13307 13308 /** 13309 * Logic to handle movement of existing installed applications. 13310 */ 13311 class MoveInstallArgs extends InstallArgs { 13312 private File codeFile; 13313 private File resourceFile; 13314 13315 /** New install */ 13316 MoveInstallArgs(InstallParams params) { 13317 super(params.origin, params.move, params.observer, params.installFlags, 13318 params.installerPackageName, params.volumeUuid, 13319 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13320 params.grantedRuntimePermissions, 13321 params.traceMethod, params.traceCookie, params.certificates); 13322 } 13323 13324 int copyApk(IMediaContainerService imcs, boolean temp) { 13325 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 13326 + move.fromUuid + " to " + move.toUuid); 13327 synchronized (mInstaller) { 13328 try { 13329 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 13330 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 13331 } catch (InstallerException e) { 13332 Slog.w(TAG, "Failed to move app", e); 13333 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13334 } 13335 } 13336 13337 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 13338 resourceFile = codeFile; 13339 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 13340 13341 return PackageManager.INSTALL_SUCCEEDED; 13342 } 13343 13344 int doPreInstall(int status) { 13345 if (status != PackageManager.INSTALL_SUCCEEDED) { 13346 cleanUp(move.toUuid); 13347 } 13348 return status; 13349 } 13350 13351 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13352 if (status != PackageManager.INSTALL_SUCCEEDED) { 13353 cleanUp(move.toUuid); 13354 return false; 13355 } 13356 13357 // Reflect the move in app info 13358 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13359 pkg.setApplicationInfoCodePath(pkg.codePath); 13360 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13361 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13362 pkg.setApplicationInfoResourcePath(pkg.codePath); 13363 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13364 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13365 13366 return true; 13367 } 13368 13369 int doPostInstall(int status, int uid) { 13370 if (status == PackageManager.INSTALL_SUCCEEDED) { 13371 cleanUp(move.fromUuid); 13372 } else { 13373 cleanUp(move.toUuid); 13374 } 13375 return status; 13376 } 13377 13378 @Override 13379 String getCodePath() { 13380 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13381 } 13382 13383 @Override 13384 String getResourcePath() { 13385 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13386 } 13387 13388 private boolean cleanUp(String volumeUuid) { 13389 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 13390 move.dataAppName); 13391 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 13392 synchronized (mInstallLock) { 13393 // Clean up both app data and code 13394 // All package moves are frozen until finished 13395 try { 13396 mInstaller.destroyAppData(volumeUuid, move.packageName, UserHandle.USER_ALL, 13397 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 13398 } catch (InstallerException e) { 13399 Slog.w(TAG, String.valueOf(e)); 13400 } 13401 removeCodePathLI(codeFile); 13402 } 13403 return true; 13404 } 13405 13406 void cleanUpResourcesLI() { 13407 throw new UnsupportedOperationException(); 13408 } 13409 13410 boolean doPostDeleteLI(boolean delete) { 13411 throw new UnsupportedOperationException(); 13412 } 13413 } 13414 13415 static String getAsecPackageName(String packageCid) { 13416 int idx = packageCid.lastIndexOf("-"); 13417 if (idx == -1) { 13418 return packageCid; 13419 } 13420 return packageCid.substring(0, idx); 13421 } 13422 13423 // Utility method used to create code paths based on package name and available index. 13424 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 13425 String idxStr = ""; 13426 int idx = 1; 13427 // Fall back to default value of idx=1 if prefix is not 13428 // part of oldCodePath 13429 if (oldCodePath != null) { 13430 String subStr = oldCodePath; 13431 // Drop the suffix right away 13432 if (suffix != null && subStr.endsWith(suffix)) { 13433 subStr = subStr.substring(0, subStr.length() - suffix.length()); 13434 } 13435 // If oldCodePath already contains prefix find out the 13436 // ending index to either increment or decrement. 13437 int sidx = subStr.lastIndexOf(prefix); 13438 if (sidx != -1) { 13439 subStr = subStr.substring(sidx + prefix.length()); 13440 if (subStr != null) { 13441 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 13442 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 13443 } 13444 try { 13445 idx = Integer.parseInt(subStr); 13446 if (idx <= 1) { 13447 idx++; 13448 } else { 13449 idx--; 13450 } 13451 } catch(NumberFormatException e) { 13452 } 13453 } 13454 } 13455 } 13456 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 13457 return prefix + idxStr; 13458 } 13459 13460 private File getNextCodePath(File targetDir, String packageName) { 13461 int suffix = 1; 13462 File result; 13463 do { 13464 result = new File(targetDir, packageName + "-" + suffix); 13465 suffix++; 13466 } while (result.exists()); 13467 return result; 13468 } 13469 13470 // Utility method that returns the relative package path with respect 13471 // to the installation directory. Like say for /data/data/com.test-1.apk 13472 // string com.test-1 is returned. 13473 static String deriveCodePathName(String codePath) { 13474 if (codePath == null) { 13475 return null; 13476 } 13477 final File codeFile = new File(codePath); 13478 final String name = codeFile.getName(); 13479 if (codeFile.isDirectory()) { 13480 return name; 13481 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 13482 final int lastDot = name.lastIndexOf('.'); 13483 return name.substring(0, lastDot); 13484 } else { 13485 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 13486 return null; 13487 } 13488 } 13489 13490 static class PackageInstalledInfo { 13491 String name; 13492 int uid; 13493 // The set of users that originally had this package installed. 13494 int[] origUsers; 13495 // The set of users that now have this package installed. 13496 int[] newUsers; 13497 PackageParser.Package pkg; 13498 int returnCode; 13499 String returnMsg; 13500 PackageRemovedInfo removedInfo; 13501 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 13502 13503 public void setError(int code, String msg) { 13504 setReturnCode(code); 13505 setReturnMessage(msg); 13506 Slog.w(TAG, msg); 13507 } 13508 13509 public void setError(String msg, PackageParserException e) { 13510 setReturnCode(e.error); 13511 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13512 Slog.w(TAG, msg, e); 13513 } 13514 13515 public void setError(String msg, PackageManagerException e) { 13516 returnCode = e.error; 13517 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13518 Slog.w(TAG, msg, e); 13519 } 13520 13521 public void setReturnCode(int returnCode) { 13522 this.returnCode = returnCode; 13523 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13524 for (int i = 0; i < childCount; i++) { 13525 addedChildPackages.valueAt(i).returnCode = returnCode; 13526 } 13527 } 13528 13529 private void setReturnMessage(String returnMsg) { 13530 this.returnMsg = returnMsg; 13531 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13532 for (int i = 0; i < childCount; i++) { 13533 addedChildPackages.valueAt(i).returnMsg = returnMsg; 13534 } 13535 } 13536 13537 // In some error cases we want to convey more info back to the observer 13538 String origPackage; 13539 String origPermission; 13540 } 13541 13542 /* 13543 * Install a non-existing package. 13544 */ 13545 private void installNewPackageLIF(PackageParser.Package pkg, int parseFlags, int scanFlags, 13546 UserHandle user, String installerPackageName, String volumeUuid, 13547 PackageInstalledInfo res) { 13548 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 13549 13550 // Remember this for later, in case we need to rollback this install 13551 String pkgName = pkg.packageName; 13552 13553 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 13554 13555 synchronized(mPackages) { 13556 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 13557 // A package with the same name is already installed, though 13558 // it has been renamed to an older name. The package we 13559 // are trying to install should be installed as an update to 13560 // the existing one, but that has not been requested, so bail. 13561 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13562 + " without first uninstalling package running as " 13563 + mSettings.mRenamedPackages.get(pkgName)); 13564 return; 13565 } 13566 if (mPackages.containsKey(pkgName)) { 13567 // Don't allow installation over an existing package with the same name. 13568 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13569 + " without first uninstalling."); 13570 return; 13571 } 13572 } 13573 13574 try { 13575 PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 13576 System.currentTimeMillis(), user); 13577 13578 updateSettingsLI(newPackage, installerPackageName, null, res, user); 13579 13580 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13581 prepareAppDataAfterInstallLIF(newPackage); 13582 13583 } else { 13584 // Remove package from internal structures, but keep around any 13585 // data that might have already existed 13586 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 13587 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 13588 } 13589 } catch (PackageManagerException e) { 13590 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13591 } 13592 13593 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13594 } 13595 13596 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 13597 // Can't rotate keys during boot or if sharedUser. 13598 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 13599 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 13600 return false; 13601 } 13602 // app is using upgradeKeySets; make sure all are valid 13603 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13604 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 13605 for (int i = 0; i < upgradeKeySets.length; i++) { 13606 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 13607 Slog.wtf(TAG, "Package " 13608 + (oldPs.name != null ? oldPs.name : "<null>") 13609 + " contains upgrade-key-set reference to unknown key-set: " 13610 + upgradeKeySets[i] 13611 + " reverting to signatures check."); 13612 return false; 13613 } 13614 } 13615 return true; 13616 } 13617 13618 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 13619 // Upgrade keysets are being used. Determine if new package has a superset of the 13620 // required keys. 13621 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 13622 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13623 for (int i = 0; i < upgradeKeySets.length; i++) { 13624 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 13625 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 13626 return true; 13627 } 13628 } 13629 return false; 13630 } 13631 13632 private void replacePackageLIF(PackageParser.Package pkg, int parseFlags, int scanFlags, 13633 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 13634 final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 13635 13636 final PackageParser.Package oldPackage; 13637 final String pkgName = pkg.packageName; 13638 final int[] allUsers; 13639 13640 // First find the old package info and check signatures 13641 synchronized(mPackages) { 13642 oldPackage = mPackages.get(pkgName); 13643 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 13644 if (isEphemeral && !oldIsEphemeral) { 13645 // can't downgrade from full to ephemeral 13646 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 13647 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 13648 return; 13649 } 13650 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 13651 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13652 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 13653 if (!checkUpgradeKeySetLP(ps, pkg)) { 13654 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13655 "New package not signed by keys specified by upgrade-keysets: " 13656 + pkgName); 13657 return; 13658 } 13659 } else { 13660 // default to original signature matching 13661 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 13662 != PackageManager.SIGNATURE_MATCH) { 13663 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13664 "New package has a different signature: " + pkgName); 13665 return; 13666 } 13667 } 13668 13669 // Check for shared user id changes 13670 String invalidPackageName = 13671 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 13672 if (invalidPackageName != null) { 13673 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 13674 "Package " + invalidPackageName + " tried to change user " 13675 + oldPackage.mSharedUserId); 13676 return; 13677 } 13678 13679 // In case of rollback, remember per-user/profile install state 13680 allUsers = sUserManager.getUserIds(); 13681 } 13682 13683 // Update what is removed 13684 res.removedInfo = new PackageRemovedInfo(); 13685 res.removedInfo.uid = oldPackage.applicationInfo.uid; 13686 res.removedInfo.removedPackage = oldPackage.packageName; 13687 res.removedInfo.isUpdate = true; 13688 final int childCount = (oldPackage.childPackages != null) 13689 ? oldPackage.childPackages.size() : 0; 13690 for (int i = 0; i < childCount; i++) { 13691 boolean childPackageUpdated = false; 13692 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 13693 if (res.addedChildPackages != null) { 13694 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 13695 if (childRes != null) { 13696 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 13697 childRes.removedInfo.removedPackage = childPkg.packageName; 13698 childRes.removedInfo.isUpdate = true; 13699 childPackageUpdated = true; 13700 } 13701 } 13702 if (!childPackageUpdated) { 13703 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 13704 childRemovedRes.removedPackage = childPkg.packageName; 13705 childRemovedRes.isUpdate = false; 13706 childRemovedRes.dataRemoved = true; 13707 synchronized (mPackages) { 13708 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 13709 if (childPs != null) { 13710 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 13711 } 13712 } 13713 if (res.removedInfo.removedChildPackages == null) { 13714 res.removedInfo.removedChildPackages = new ArrayMap<>(); 13715 } 13716 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 13717 } 13718 } 13719 13720 boolean sysPkg = (isSystemApp(oldPackage)); 13721 if (sysPkg) { 13722 replaceSystemPackageLIF(oldPackage, pkg, parseFlags, scanFlags, 13723 user, allUsers, installerPackageName, res); 13724 } else { 13725 replaceNonSystemPackageLIF(oldPackage, pkg, parseFlags, scanFlags, 13726 user, allUsers, installerPackageName, res); 13727 } 13728 } 13729 13730 public List<String> getPreviousCodePaths(String packageName) { 13731 final PackageSetting ps = mSettings.mPackages.get(packageName); 13732 final List<String> result = new ArrayList<String>(); 13733 if (ps != null && ps.oldCodePaths != null) { 13734 result.addAll(ps.oldCodePaths); 13735 } 13736 return result; 13737 } 13738 13739 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 13740 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 13741 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 13742 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 13743 + deletedPackage); 13744 13745 String pkgName = deletedPackage.packageName; 13746 boolean deletedPkg = true; 13747 boolean addedPkg = false; 13748 boolean updatedSettings = false; 13749 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 13750 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 13751 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 13752 13753 final long origUpdateTime = (pkg.mExtras != null) 13754 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 13755 13756 // First delete the existing package while retaining the data directory 13757 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 13758 res.removedInfo, true, pkg)) { 13759 // If the existing package wasn't successfully deleted 13760 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 13761 deletedPkg = false; 13762 } else { 13763 // Successfully deleted the old package; proceed with replace. 13764 13765 // If deleted package lived in a container, give users a chance to 13766 // relinquish resources before killing. 13767 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 13768 if (DEBUG_INSTALL) { 13769 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 13770 } 13771 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 13772 final ArrayList<String> pkgList = new ArrayList<String>(1); 13773 pkgList.add(deletedPackage.applicationInfo.packageName); 13774 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 13775 } 13776 13777 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 13778 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 13779 clearAppProfilesLIF(pkg); 13780 13781 try { 13782 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, 13783 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 13784 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 13785 13786 // Update the in-memory copy of the previous code paths. 13787 PackageSetting ps = mSettings.mPackages.get(pkgName); 13788 if (!killApp) { 13789 if (ps.oldCodePaths == null) { 13790 ps.oldCodePaths = new ArraySet<>(); 13791 } 13792 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 13793 if (deletedPackage.splitCodePaths != null) { 13794 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 13795 } 13796 } else { 13797 ps.oldCodePaths = null; 13798 } 13799 if (ps.childPackageNames != null) { 13800 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 13801 final String childPkgName = ps.childPackageNames.get(i); 13802 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 13803 childPs.oldCodePaths = ps.oldCodePaths; 13804 } 13805 } 13806 prepareAppDataAfterInstallLIF(newPackage); 13807 addedPkg = true; 13808 } catch (PackageManagerException e) { 13809 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13810 } 13811 } 13812 13813 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 13814 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 13815 13816 // Revert all internal state mutations and added folders for the failed install 13817 if (addedPkg) { 13818 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 13819 res.removedInfo, true, null); 13820 } 13821 13822 // Restore the old package 13823 if (deletedPkg) { 13824 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 13825 File restoreFile = new File(deletedPackage.codePath); 13826 // Parse old package 13827 boolean oldExternal = isExternal(deletedPackage); 13828 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 13829 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 13830 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 13831 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 13832 try { 13833 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 13834 null); 13835 } catch (PackageManagerException e) { 13836 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 13837 + e.getMessage()); 13838 return; 13839 } 13840 13841 synchronized (mPackages) { 13842 // Ensure the installer package name up to date 13843 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 13844 13845 // Update permissions for restored package 13846 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 13847 13848 mSettings.writeLPr(); 13849 } 13850 13851 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 13852 } 13853 } else { 13854 synchronized (mPackages) { 13855 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 13856 if (ps != null) { 13857 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 13858 if (res.removedInfo.removedChildPackages != null) { 13859 final int childCount = res.removedInfo.removedChildPackages.size(); 13860 // Iterate in reverse as we may modify the collection 13861 for (int i = childCount - 1; i >= 0; i--) { 13862 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 13863 if (res.addedChildPackages.containsKey(childPackageName)) { 13864 res.removedInfo.removedChildPackages.removeAt(i); 13865 } else { 13866 PackageRemovedInfo childInfo = res.removedInfo 13867 .removedChildPackages.valueAt(i); 13868 childInfo.removedForAllUsers = mPackages.get( 13869 childInfo.removedPackage) == null; 13870 } 13871 } 13872 } 13873 } 13874 } 13875 } 13876 } 13877 13878 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 13879 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 13880 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 13881 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 13882 + ", old=" + deletedPackage); 13883 13884 final boolean disabledSystem; 13885 13886 // Set the system/privileged flags as needed 13887 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 13888 if ((deletedPackage.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 13889 != 0) { 13890 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 13891 } 13892 13893 // Remove existing system package 13894 removePackageLI(deletedPackage, true); 13895 13896 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 13897 if (!disabledSystem) { 13898 // We didn't need to disable the .apk as a current system package, 13899 // which means we are replacing another update that is already 13900 // installed. We need to make sure to delete the older one's .apk. 13901 res.removedInfo.args = createInstallArgsForExisting(0, 13902 deletedPackage.applicationInfo.getCodePath(), 13903 deletedPackage.applicationInfo.getResourcePath(), 13904 getAppDexInstructionSets(deletedPackage.applicationInfo)); 13905 } else { 13906 res.removedInfo.args = null; 13907 } 13908 13909 // Successfully disabled the old package. Now proceed with re-installation 13910 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 13911 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 13912 clearAppProfilesLIF(pkg); 13913 13914 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 13915 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 13916 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 13917 13918 PackageParser.Package newPackage = null; 13919 try { 13920 // Add the package to the internal data structures 13921 newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user); 13922 13923 // Set the update and install times 13924 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 13925 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 13926 System.currentTimeMillis()); 13927 13928 // Update the package dynamic state if succeeded 13929 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13930 // Now that the install succeeded make sure we remove data 13931 // directories for any child package the update removed. 13932 final int deletedChildCount = (deletedPackage.childPackages != null) 13933 ? deletedPackage.childPackages.size() : 0; 13934 final int newChildCount = (newPackage.childPackages != null) 13935 ? newPackage.childPackages.size() : 0; 13936 for (int i = 0; i < deletedChildCount; i++) { 13937 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 13938 boolean childPackageDeleted = true; 13939 for (int j = 0; j < newChildCount; j++) { 13940 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 13941 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 13942 childPackageDeleted = false; 13943 break; 13944 } 13945 } 13946 if (childPackageDeleted) { 13947 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 13948 deletedChildPkg.packageName); 13949 if (ps != null && res.removedInfo.removedChildPackages != null) { 13950 PackageRemovedInfo removedChildRes = res.removedInfo 13951 .removedChildPackages.get(deletedChildPkg.packageName); 13952 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 13953 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 13954 } 13955 } 13956 } 13957 13958 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 13959 prepareAppDataAfterInstallLIF(newPackage); 13960 } 13961 } catch (PackageManagerException e) { 13962 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 13963 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13964 } 13965 13966 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 13967 // Re installation failed. Restore old information 13968 // Remove new pkg information 13969 if (newPackage != null) { 13970 removeInstalledPackageLI(newPackage, true); 13971 } 13972 // Add back the old system package 13973 try { 13974 scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 13975 } catch (PackageManagerException e) { 13976 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 13977 } 13978 13979 synchronized (mPackages) { 13980 if (disabledSystem) { 13981 enableSystemPackageLPw(deletedPackage); 13982 } 13983 13984 // Ensure the installer package name up to date 13985 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 13986 13987 // Update permissions for restored package 13988 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 13989 13990 mSettings.writeLPr(); 13991 } 13992 13993 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 13994 + " after failed upgrade"); 13995 } 13996 } 13997 13998 /** 13999 * Checks whether the parent or any of the child packages have a change shared 14000 * user. For a package to be a valid update the shred users of the parent and 14001 * the children should match. We may later support changing child shared users. 14002 * @param oldPkg The updated package. 14003 * @param newPkg The update package. 14004 * @return The shared user that change between the versions. 14005 */ 14006 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 14007 PackageParser.Package newPkg) { 14008 // Check parent shared user 14009 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 14010 return newPkg.packageName; 14011 } 14012 // Check child shared users 14013 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14014 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 14015 for (int i = 0; i < newChildCount; i++) { 14016 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 14017 // If this child was present, did it have the same shared user? 14018 for (int j = 0; j < oldChildCount; j++) { 14019 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 14020 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 14021 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 14022 return newChildPkg.packageName; 14023 } 14024 } 14025 } 14026 return null; 14027 } 14028 14029 private void removeNativeBinariesLI(PackageSetting ps) { 14030 // Remove the lib path for the parent package 14031 if (ps != null) { 14032 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 14033 // Remove the lib path for the child packages 14034 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 14035 for (int i = 0; i < childCount; i++) { 14036 PackageSetting childPs = null; 14037 synchronized (mPackages) { 14038 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 14039 } 14040 if (childPs != null) { 14041 NativeLibraryHelper.removeNativeBinariesLI(childPs 14042 .legacyNativeLibraryPathString); 14043 } 14044 } 14045 } 14046 } 14047 14048 private void enableSystemPackageLPw(PackageParser.Package pkg) { 14049 // Enable the parent package 14050 mSettings.enableSystemPackageLPw(pkg.packageName); 14051 // Enable the child packages 14052 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14053 for (int i = 0; i < childCount; i++) { 14054 PackageParser.Package childPkg = pkg.childPackages.get(i); 14055 mSettings.enableSystemPackageLPw(childPkg.packageName); 14056 } 14057 } 14058 14059 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 14060 PackageParser.Package newPkg) { 14061 // Disable the parent package (parent always replaced) 14062 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 14063 // Disable the child packages 14064 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14065 for (int i = 0; i < childCount; i++) { 14066 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 14067 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 14068 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 14069 } 14070 return disabled; 14071 } 14072 14073 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 14074 String installerPackageName) { 14075 // Enable the parent package 14076 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 14077 // Enable the child packages 14078 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14079 for (int i = 0; i < childCount; i++) { 14080 PackageParser.Package childPkg = pkg.childPackages.get(i); 14081 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 14082 } 14083 } 14084 14085 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 14086 // Collect all used permissions in the UID 14087 ArraySet<String> usedPermissions = new ArraySet<>(); 14088 final int packageCount = su.packages.size(); 14089 for (int i = 0; i < packageCount; i++) { 14090 PackageSetting ps = su.packages.valueAt(i); 14091 if (ps.pkg == null) { 14092 continue; 14093 } 14094 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 14095 for (int j = 0; j < requestedPermCount; j++) { 14096 String permission = ps.pkg.requestedPermissions.get(j); 14097 BasePermission bp = mSettings.mPermissions.get(permission); 14098 if (bp != null) { 14099 usedPermissions.add(permission); 14100 } 14101 } 14102 } 14103 14104 PermissionsState permissionsState = su.getPermissionsState(); 14105 // Prune install permissions 14106 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 14107 final int installPermCount = installPermStates.size(); 14108 for (int i = installPermCount - 1; i >= 0; i--) { 14109 PermissionState permissionState = installPermStates.get(i); 14110 if (!usedPermissions.contains(permissionState.getName())) { 14111 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14112 if (bp != null) { 14113 permissionsState.revokeInstallPermission(bp); 14114 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 14115 PackageManager.MASK_PERMISSION_FLAGS, 0); 14116 } 14117 } 14118 } 14119 14120 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 14121 14122 // Prune runtime permissions 14123 for (int userId : allUserIds) { 14124 List<PermissionState> runtimePermStates = permissionsState 14125 .getRuntimePermissionStates(userId); 14126 final int runtimePermCount = runtimePermStates.size(); 14127 for (int i = runtimePermCount - 1; i >= 0; i--) { 14128 PermissionState permissionState = runtimePermStates.get(i); 14129 if (!usedPermissions.contains(permissionState.getName())) { 14130 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14131 if (bp != null) { 14132 permissionsState.revokeRuntimePermission(bp, userId); 14133 permissionsState.updatePermissionFlags(bp, userId, 14134 PackageManager.MASK_PERMISSION_FLAGS, 0); 14135 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 14136 runtimePermissionChangedUserIds, userId); 14137 } 14138 } 14139 } 14140 } 14141 14142 return runtimePermissionChangedUserIds; 14143 } 14144 14145 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 14146 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 14147 // Update the parent package setting 14148 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 14149 res, user); 14150 // Update the child packages setting 14151 final int childCount = (newPackage.childPackages != null) 14152 ? newPackage.childPackages.size() : 0; 14153 for (int i = 0; i < childCount; i++) { 14154 PackageParser.Package childPackage = newPackage.childPackages.get(i); 14155 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 14156 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 14157 childRes.origUsers, childRes, user); 14158 } 14159 } 14160 14161 private void updateSettingsInternalLI(PackageParser.Package newPackage, 14162 String installerPackageName, int[] allUsers, int[] installedForUsers, 14163 PackageInstalledInfo res, UserHandle user) { 14164 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 14165 14166 String pkgName = newPackage.packageName; 14167 synchronized (mPackages) { 14168 //write settings. the installStatus will be incomplete at this stage. 14169 //note that the new package setting would have already been 14170 //added to mPackages. It hasn't been persisted yet. 14171 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 14172 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14173 mSettings.writeLPr(); 14174 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14175 } 14176 14177 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 14178 synchronized (mPackages) { 14179 updatePermissionsLPw(newPackage.packageName, newPackage, 14180 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 14181 ? UPDATE_PERMISSIONS_ALL : 0)); 14182 // For system-bundled packages, we assume that installing an upgraded version 14183 // of the package implies that the user actually wants to run that new code, 14184 // so we enable the package. 14185 PackageSetting ps = mSettings.mPackages.get(pkgName); 14186 final int userId = user.getIdentifier(); 14187 if (ps != null) { 14188 if (isSystemApp(newPackage)) { 14189 if (DEBUG_INSTALL) { 14190 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 14191 } 14192 // Enable system package for requested users 14193 if (res.origUsers != null) { 14194 for (int origUserId : res.origUsers) { 14195 if (userId == UserHandle.USER_ALL || userId == origUserId) { 14196 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 14197 origUserId, installerPackageName); 14198 } 14199 } 14200 } 14201 // Also convey the prior install/uninstall state 14202 if (allUsers != null && installedForUsers != null) { 14203 for (int currentUserId : allUsers) { 14204 final boolean installed = ArrayUtils.contains( 14205 installedForUsers, currentUserId); 14206 if (DEBUG_INSTALL) { 14207 Slog.d(TAG, " user " + currentUserId + " => " + installed); 14208 } 14209 ps.setInstalled(installed, currentUserId); 14210 } 14211 // these install state changes will be persisted in the 14212 // upcoming call to mSettings.writeLPr(). 14213 } 14214 } 14215 // It's implied that when a user requests installation, they want the app to be 14216 // installed and enabled. 14217 if (userId != UserHandle.USER_ALL) { 14218 ps.setInstalled(true, userId); 14219 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 14220 } 14221 } 14222 res.name = pkgName; 14223 res.uid = newPackage.applicationInfo.uid; 14224 res.pkg = newPackage; 14225 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 14226 mSettings.setInstallerPackageName(pkgName, installerPackageName); 14227 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14228 //to update install status 14229 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14230 mSettings.writeLPr(); 14231 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14232 } 14233 14234 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14235 } 14236 14237 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 14238 try { 14239 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 14240 installPackageLI(args, res); 14241 } finally { 14242 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14243 } 14244 } 14245 14246 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 14247 final int installFlags = args.installFlags; 14248 final String installerPackageName = args.installerPackageName; 14249 final String volumeUuid = args.volumeUuid; 14250 final File tmpPackageFile = new File(args.getCodePath()); 14251 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 14252 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 14253 || (args.volumeUuid != null)); 14254 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 14255 boolean replace = false; 14256 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 14257 if (args.move != null) { 14258 // moving a complete application; perform an initial scan on the new install location 14259 scanFlags |= SCAN_INITIAL; 14260 } 14261 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 14262 scanFlags |= SCAN_DONT_KILL_APP; 14263 } 14264 14265 // Result object to be returned 14266 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14267 14268 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 14269 14270 // Sanity check 14271 if (ephemeral && (forwardLocked || onExternal)) { 14272 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 14273 + " external=" + onExternal); 14274 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14275 return; 14276 } 14277 14278 // Retrieve PackageSettings and parse package 14279 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 14280 | PackageParser.PARSE_ENFORCE_CODE 14281 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 14282 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 14283 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0); 14284 PackageParser pp = new PackageParser(); 14285 pp.setSeparateProcesses(mSeparateProcesses); 14286 pp.setDisplayMetrics(mMetrics); 14287 14288 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 14289 final PackageParser.Package pkg; 14290 try { 14291 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 14292 } catch (PackageParserException e) { 14293 res.setError("Failed parse during installPackageLI", e); 14294 return; 14295 } finally { 14296 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14297 } 14298 14299 // If we are installing a clustered package add results for the children 14300 if (pkg.childPackages != null) { 14301 synchronized (mPackages) { 14302 final int childCount = pkg.childPackages.size(); 14303 for (int i = 0; i < childCount; i++) { 14304 PackageParser.Package childPkg = pkg.childPackages.get(i); 14305 PackageInstalledInfo childRes = new PackageInstalledInfo(); 14306 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14307 childRes.pkg = childPkg; 14308 childRes.name = childPkg.packageName; 14309 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14310 if (childPs != null) { 14311 childRes.origUsers = childPs.queryInstalledUsers( 14312 sUserManager.getUserIds(), true); 14313 } 14314 if ((mPackages.containsKey(childPkg.packageName))) { 14315 childRes.removedInfo = new PackageRemovedInfo(); 14316 childRes.removedInfo.removedPackage = childPkg.packageName; 14317 } 14318 if (res.addedChildPackages == null) { 14319 res.addedChildPackages = new ArrayMap<>(); 14320 } 14321 res.addedChildPackages.put(childPkg.packageName, childRes); 14322 } 14323 } 14324 } 14325 14326 // If package doesn't declare API override, mark that we have an install 14327 // time CPU ABI override. 14328 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 14329 pkg.cpuAbiOverride = args.abiOverride; 14330 } 14331 14332 String pkgName = res.name = pkg.packageName; 14333 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 14334 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 14335 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 14336 return; 14337 } 14338 } 14339 14340 try { 14341 // either use what we've been given or parse directly from the APK 14342 if (args.certificates != null) { 14343 try { 14344 PackageParser.populateCertificates(pkg, args.certificates); 14345 } catch (PackageParserException e) { 14346 // there was something wrong with the certificates we were given; 14347 // try to pull them from the APK 14348 PackageParser.collectCertificates(pkg, parseFlags); 14349 } 14350 } else { 14351 PackageParser.collectCertificates(pkg, parseFlags); 14352 } 14353 } catch (PackageParserException e) { 14354 res.setError("Failed collect during installPackageLI", e); 14355 return; 14356 } 14357 14358 // Get rid of all references to package scan path via parser. 14359 pp = null; 14360 String oldCodePath = null; 14361 boolean systemApp = false; 14362 synchronized (mPackages) { 14363 // Check if installing already existing package 14364 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14365 String oldName = mSettings.mRenamedPackages.get(pkgName); 14366 if (pkg.mOriginalPackages != null 14367 && pkg.mOriginalPackages.contains(oldName) 14368 && mPackages.containsKey(oldName)) { 14369 // This package is derived from an original package, 14370 // and this device has been updating from that original 14371 // name. We must continue using the original name, so 14372 // rename the new package here. 14373 pkg.setPackageName(oldName); 14374 pkgName = pkg.packageName; 14375 replace = true; 14376 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 14377 + oldName + " pkgName=" + pkgName); 14378 } else if (mPackages.containsKey(pkgName)) { 14379 // This package, under its official name, already exists 14380 // on the device; we should replace it. 14381 replace = true; 14382 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 14383 } 14384 14385 // Child packages are installed through the parent package 14386 if (pkg.parentPackage != null) { 14387 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14388 "Package " + pkg.packageName + " is child of package " 14389 + pkg.parentPackage.parentPackage + ". Child packages " 14390 + "can be updated only through the parent package."); 14391 return; 14392 } 14393 14394 if (replace) { 14395 // Prevent apps opting out from runtime permissions 14396 PackageParser.Package oldPackage = mPackages.get(pkgName); 14397 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 14398 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 14399 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 14400 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 14401 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 14402 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 14403 + " doesn't support runtime permissions but the old" 14404 + " target SDK " + oldTargetSdk + " does."); 14405 return; 14406 } 14407 14408 // Prevent installing of child packages 14409 if (oldPackage.parentPackage != null) { 14410 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14411 "Package " + pkg.packageName + " is child of package " 14412 + oldPackage.parentPackage + ". Child packages " 14413 + "can be updated only through the parent package."); 14414 return; 14415 } 14416 } 14417 } 14418 14419 PackageSetting ps = mSettings.mPackages.get(pkgName); 14420 if (ps != null) { 14421 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 14422 14423 // Quick sanity check that we're signed correctly if updating; 14424 // we'll check this again later when scanning, but we want to 14425 // bail early here before tripping over redefined permissions. 14426 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14427 if (!checkUpgradeKeySetLP(ps, pkg)) { 14428 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 14429 + pkg.packageName + " upgrade keys do not match the " 14430 + "previously installed version"); 14431 return; 14432 } 14433 } else { 14434 try { 14435 verifySignaturesLP(ps, pkg); 14436 } catch (PackageManagerException e) { 14437 res.setError(e.error, e.getMessage()); 14438 return; 14439 } 14440 } 14441 14442 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 14443 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 14444 systemApp = (ps.pkg.applicationInfo.flags & 14445 ApplicationInfo.FLAG_SYSTEM) != 0; 14446 } 14447 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14448 } 14449 14450 // Check whether the newly-scanned package wants to define an already-defined perm 14451 int N = pkg.permissions.size(); 14452 for (int i = N-1; i >= 0; i--) { 14453 PackageParser.Permission perm = pkg.permissions.get(i); 14454 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 14455 if (bp != null) { 14456 // If the defining package is signed with our cert, it's okay. This 14457 // also includes the "updating the same package" case, of course. 14458 // "updating same package" could also involve key-rotation. 14459 final boolean sigsOk; 14460 if (bp.sourcePackage.equals(pkg.packageName) 14461 && (bp.packageSetting instanceof PackageSetting) 14462 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 14463 scanFlags))) { 14464 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 14465 } else { 14466 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 14467 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 14468 } 14469 if (!sigsOk) { 14470 // If the owning package is the system itself, we log but allow 14471 // install to proceed; we fail the install on all other permission 14472 // redefinitions. 14473 if (!bp.sourcePackage.equals("android")) { 14474 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 14475 + pkg.packageName + " attempting to redeclare permission " 14476 + perm.info.name + " already owned by " + bp.sourcePackage); 14477 res.origPermission = perm.info.name; 14478 res.origPackage = bp.sourcePackage; 14479 return; 14480 } else { 14481 Slog.w(TAG, "Package " + pkg.packageName 14482 + " attempting to redeclare system permission " 14483 + perm.info.name + "; ignoring new declaration"); 14484 pkg.permissions.remove(i); 14485 } 14486 } 14487 } 14488 } 14489 } 14490 14491 if (systemApp) { 14492 if (onExternal) { 14493 // Abort update; system app can't be replaced with app on sdcard 14494 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 14495 "Cannot install updates to system apps on sdcard"); 14496 return; 14497 } else if (ephemeral) { 14498 // Abort update; system app can't be replaced with an ephemeral app 14499 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 14500 "Cannot update a system app with an ephemeral app"); 14501 return; 14502 } 14503 } 14504 14505 if (args.move != null) { 14506 // We did an in-place move, so dex is ready to roll 14507 scanFlags |= SCAN_NO_DEX; 14508 scanFlags |= SCAN_MOVE; 14509 14510 synchronized (mPackages) { 14511 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14512 if (ps == null) { 14513 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 14514 "Missing settings for moved package " + pkgName); 14515 } 14516 14517 // We moved the entire application as-is, so bring over the 14518 // previously derived ABI information. 14519 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 14520 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 14521 } 14522 14523 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 14524 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 14525 scanFlags |= SCAN_NO_DEX; 14526 14527 try { 14528 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 14529 args.abiOverride : pkg.cpuAbiOverride); 14530 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 14531 true /* extract libs */); 14532 } catch (PackageManagerException pme) { 14533 Slog.e(TAG, "Error deriving application ABI", pme); 14534 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 14535 return; 14536 } 14537 14538 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 14539 // Do not run PackageDexOptimizer through the local performDexOpt 14540 // method because `pkg` is not in `mPackages` yet. 14541 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instructionSets */, 14542 false /* checkProfiles */, getCompilerFilterForReason(REASON_INSTALL)); 14543 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14544 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 14545 String msg = "Extracting package failed for " + pkgName; 14546 res.setError(INSTALL_FAILED_DEXOPT, msg); 14547 return; 14548 } 14549 14550 // Notify BackgroundDexOptService that the package has been changed. 14551 // If this is an update of a package which used to fail to compile, 14552 // BDOS will remove it from its blacklist. 14553 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 14554 } 14555 14556 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 14557 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 14558 return; 14559 } 14560 14561 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 14562 14563 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 14564 "installPackageLI")) { 14565 if (replace) { 14566 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 14567 installerPackageName, res); 14568 } else { 14569 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 14570 args.user, installerPackageName, volumeUuid, res); 14571 } 14572 } 14573 synchronized (mPackages) { 14574 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14575 if (ps != null) { 14576 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14577 } 14578 14579 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14580 for (int i = 0; i < childCount; i++) { 14581 PackageParser.Package childPkg = pkg.childPackages.get(i); 14582 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14583 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14584 if (childPs != null) { 14585 childRes.newUsers = childPs.queryInstalledUsers( 14586 sUserManager.getUserIds(), true); 14587 } 14588 } 14589 } 14590 } 14591 14592 private void startIntentFilterVerifications(int userId, boolean replacing, 14593 PackageParser.Package pkg) { 14594 if (mIntentFilterVerifierComponent == null) { 14595 Slog.w(TAG, "No IntentFilter verification will not be done as " 14596 + "there is no IntentFilterVerifier available!"); 14597 return; 14598 } 14599 14600 final int verifierUid = getPackageUid( 14601 mIntentFilterVerifierComponent.getPackageName(), 14602 MATCH_DEBUG_TRIAGED_MISSING, 14603 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 14604 14605 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14606 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 14607 mHandler.sendMessage(msg); 14608 14609 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14610 for (int i = 0; i < childCount; i++) { 14611 PackageParser.Package childPkg = pkg.childPackages.get(i); 14612 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14613 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 14614 mHandler.sendMessage(msg); 14615 } 14616 } 14617 14618 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 14619 PackageParser.Package pkg) { 14620 int size = pkg.activities.size(); 14621 if (size == 0) { 14622 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14623 "No activity, so no need to verify any IntentFilter!"); 14624 return; 14625 } 14626 14627 final boolean hasDomainURLs = hasDomainURLs(pkg); 14628 if (!hasDomainURLs) { 14629 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14630 "No domain URLs, so no need to verify any IntentFilter!"); 14631 return; 14632 } 14633 14634 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 14635 + " if any IntentFilter from the " + size 14636 + " Activities needs verification ..."); 14637 14638 int count = 0; 14639 final String packageName = pkg.packageName; 14640 14641 synchronized (mPackages) { 14642 // If this is a new install and we see that we've already run verification for this 14643 // package, we have nothing to do: it means the state was restored from backup. 14644 if (!replacing) { 14645 IntentFilterVerificationInfo ivi = 14646 mSettings.getIntentFilterVerificationLPr(packageName); 14647 if (ivi != null) { 14648 if (DEBUG_DOMAIN_VERIFICATION) { 14649 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 14650 + ivi.getStatusString()); 14651 } 14652 return; 14653 } 14654 } 14655 14656 // If any filters need to be verified, then all need to be. 14657 boolean needToVerify = false; 14658 for (PackageParser.Activity a : pkg.activities) { 14659 for (ActivityIntentInfo filter : a.intents) { 14660 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 14661 if (DEBUG_DOMAIN_VERIFICATION) { 14662 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 14663 } 14664 needToVerify = true; 14665 break; 14666 } 14667 } 14668 } 14669 14670 if (needToVerify) { 14671 final int verificationId = mIntentFilterVerificationToken++; 14672 for (PackageParser.Activity a : pkg.activities) { 14673 for (ActivityIntentInfo filter : a.intents) { 14674 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 14675 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14676 "Verification needed for IntentFilter:" + filter.toString()); 14677 mIntentFilterVerifier.addOneIntentFilterVerification( 14678 verifierUid, userId, verificationId, filter, packageName); 14679 count++; 14680 } 14681 } 14682 } 14683 } 14684 } 14685 14686 if (count > 0) { 14687 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 14688 + " IntentFilter verification" + (count > 1 ? "s" : "") 14689 + " for userId:" + userId); 14690 mIntentFilterVerifier.startVerifications(userId); 14691 } else { 14692 if (DEBUG_DOMAIN_VERIFICATION) { 14693 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 14694 } 14695 } 14696 } 14697 14698 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 14699 final ComponentName cn = filter.activity.getComponentName(); 14700 final String packageName = cn.getPackageName(); 14701 14702 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 14703 packageName); 14704 if (ivi == null) { 14705 return true; 14706 } 14707 int status = ivi.getStatus(); 14708 switch (status) { 14709 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 14710 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 14711 return true; 14712 14713 default: 14714 // Nothing to do 14715 return false; 14716 } 14717 } 14718 14719 private static boolean isMultiArch(ApplicationInfo info) { 14720 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 14721 } 14722 14723 private static boolean isExternal(PackageParser.Package pkg) { 14724 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 14725 } 14726 14727 private static boolean isExternal(PackageSetting ps) { 14728 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 14729 } 14730 14731 private static boolean isEphemeral(PackageParser.Package pkg) { 14732 return pkg.applicationInfo.isEphemeralApp(); 14733 } 14734 14735 private static boolean isEphemeral(PackageSetting ps) { 14736 return ps.pkg != null && isEphemeral(ps.pkg); 14737 } 14738 14739 private static boolean isSystemApp(PackageParser.Package pkg) { 14740 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 14741 } 14742 14743 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 14744 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14745 } 14746 14747 private static boolean hasDomainURLs(PackageParser.Package pkg) { 14748 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 14749 } 14750 14751 private static boolean isSystemApp(PackageSetting ps) { 14752 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 14753 } 14754 14755 private static boolean isUpdatedSystemApp(PackageSetting ps) { 14756 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 14757 } 14758 14759 private int packageFlagsToInstallFlags(PackageSetting ps) { 14760 int installFlags = 0; 14761 if (isEphemeral(ps)) { 14762 installFlags |= PackageManager.INSTALL_EPHEMERAL; 14763 } 14764 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 14765 // This existing package was an external ASEC install when we have 14766 // the external flag without a UUID 14767 installFlags |= PackageManager.INSTALL_EXTERNAL; 14768 } 14769 if (ps.isForwardLocked()) { 14770 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 14771 } 14772 return installFlags; 14773 } 14774 14775 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 14776 if (isExternal(pkg)) { 14777 if (TextUtils.isEmpty(pkg.volumeUuid)) { 14778 return StorageManager.UUID_PRIMARY_PHYSICAL; 14779 } else { 14780 return pkg.volumeUuid; 14781 } 14782 } else { 14783 return StorageManager.UUID_PRIVATE_INTERNAL; 14784 } 14785 } 14786 14787 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 14788 if (isExternal(pkg)) { 14789 if (TextUtils.isEmpty(pkg.volumeUuid)) { 14790 return mSettings.getExternalVersion(); 14791 } else { 14792 return mSettings.findOrCreateVersion(pkg.volumeUuid); 14793 } 14794 } else { 14795 return mSettings.getInternalVersion(); 14796 } 14797 } 14798 14799 private void deleteTempPackageFiles() { 14800 final FilenameFilter filter = new FilenameFilter() { 14801 public boolean accept(File dir, String name) { 14802 return name.startsWith("vmdl") && name.endsWith(".tmp"); 14803 } 14804 }; 14805 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 14806 file.delete(); 14807 } 14808 } 14809 14810 @Override 14811 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 14812 int flags) { 14813 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 14814 flags); 14815 } 14816 14817 @Override 14818 public void deletePackage(final String packageName, 14819 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 14820 mContext.enforceCallingOrSelfPermission( 14821 android.Manifest.permission.DELETE_PACKAGES, null); 14822 Preconditions.checkNotNull(packageName); 14823 Preconditions.checkNotNull(observer); 14824 final int uid = Binder.getCallingUid(); 14825 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 14826 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 14827 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 14828 mContext.enforceCallingOrSelfPermission( 14829 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 14830 "deletePackage for user " + userId); 14831 } 14832 14833 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 14834 try { 14835 observer.onPackageDeleted(packageName, 14836 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 14837 } catch (RemoteException re) { 14838 } 14839 return; 14840 } 14841 14842 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 14843 try { 14844 observer.onPackageDeleted(packageName, 14845 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 14846 } catch (RemoteException re) { 14847 } 14848 return; 14849 } 14850 14851 if (DEBUG_REMOVE) { 14852 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 14853 + " deleteAllUsers: " + deleteAllUsers ); 14854 } 14855 // Queue up an async operation since the package deletion may take a little while. 14856 mHandler.post(new Runnable() { 14857 public void run() { 14858 mHandler.removeCallbacks(this); 14859 int returnCode; 14860 if (!deleteAllUsers) { 14861 returnCode = deletePackageX(packageName, userId, deleteFlags); 14862 } else { 14863 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 14864 // If nobody is blocking uninstall, proceed with delete for all users 14865 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 14866 returnCode = deletePackageX(packageName, userId, deleteFlags); 14867 } else { 14868 // Otherwise uninstall individually for users with blockUninstalls=false 14869 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 14870 for (int userId : users) { 14871 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 14872 returnCode = deletePackageX(packageName, userId, userFlags); 14873 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 14874 Slog.w(TAG, "Package delete failed for user " + userId 14875 + ", returnCode " + returnCode); 14876 } 14877 } 14878 } 14879 // The app has only been marked uninstalled for certain users. 14880 // We still need to report that delete was blocked 14881 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 14882 } 14883 } 14884 try { 14885 observer.onPackageDeleted(packageName, returnCode, null); 14886 } catch (RemoteException e) { 14887 Log.i(TAG, "Observer no longer exists."); 14888 } //end catch 14889 } //end run 14890 }); 14891 } 14892 14893 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 14894 int[] result = EMPTY_INT_ARRAY; 14895 for (int userId : userIds) { 14896 if (getBlockUninstallForUser(packageName, userId)) { 14897 result = ArrayUtils.appendInt(result, userId); 14898 } 14899 } 14900 return result; 14901 } 14902 14903 @Override 14904 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 14905 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 14906 } 14907 14908 private boolean isPackageDeviceAdmin(String packageName, int userId) { 14909 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 14910 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 14911 try { 14912 if (dpm != null) { 14913 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 14914 /* callingUserOnly =*/ false); 14915 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 14916 : deviceOwnerComponentName.getPackageName(); 14917 // Does the package contains the device owner? 14918 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 14919 // this check is probably not needed, since DO should be registered as a device 14920 // admin on some user too. (Original bug for this: b/17657954) 14921 if (packageName.equals(deviceOwnerPackageName)) { 14922 return true; 14923 } 14924 // Does it contain a device admin for any user? 14925 int[] users; 14926 if (userId == UserHandle.USER_ALL) { 14927 users = sUserManager.getUserIds(); 14928 } else { 14929 users = new int[]{userId}; 14930 } 14931 for (int i = 0; i < users.length; ++i) { 14932 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 14933 return true; 14934 } 14935 } 14936 } 14937 } catch (RemoteException e) { 14938 } 14939 return false; 14940 } 14941 14942 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 14943 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 14944 } 14945 14946 /** 14947 * This method is an internal method that could be get invoked either 14948 * to delete an installed package or to clean up a failed installation. 14949 * After deleting an installed package, a broadcast is sent to notify any 14950 * listeners that the package has been removed. For cleaning up a failed 14951 * installation, the broadcast is not necessary since the package's 14952 * installation wouldn't have sent the initial broadcast either 14953 * The key steps in deleting a package are 14954 * deleting the package information in internal structures like mPackages, 14955 * deleting the packages base directories through installd 14956 * updating mSettings to reflect current status 14957 * persisting settings for later use 14958 * sending a broadcast if necessary 14959 */ 14960 private int deletePackageX(String packageName, int userId, int deleteFlags) { 14961 final PackageRemovedInfo info = new PackageRemovedInfo(); 14962 final boolean res; 14963 14964 final UserHandle removeForUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 14965 ? UserHandle.ALL : new UserHandle(userId); 14966 14967 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 14968 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 14969 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 14970 } 14971 14972 PackageSetting uninstalledPs = null; 14973 14974 // for the uninstall-updates case and restricted profiles, remember the per- 14975 // user handle installed state 14976 int[] allUsers; 14977 synchronized (mPackages) { 14978 uninstalledPs = mSettings.mPackages.get(packageName); 14979 if (uninstalledPs == null) { 14980 Slog.w(TAG, "Not removing non-existent package " + packageName); 14981 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 14982 } 14983 allUsers = sUserManager.getUserIds(); 14984 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 14985 } 14986 14987 synchronized (mInstallLock) { 14988 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 14989 try (PackageFreezer freezer = freezePackageForDelete(packageName, deleteFlags, 14990 "deletePackageX")) { 14991 res = deletePackageLIF(packageName, removeForUser, true, allUsers, 14992 deleteFlags | REMOVE_CHATTY, info, true, null); 14993 } 14994 synchronized (mPackages) { 14995 if (res) { 14996 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 14997 } 14998 } 14999 } 15000 15001 if (res) { 15002 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 15003 info.sendPackageRemovedBroadcasts(killApp); 15004 info.sendSystemPackageUpdatedBroadcasts(); 15005 info.sendSystemPackageAppearedBroadcasts(); 15006 } 15007 // Force a gc here. 15008 Runtime.getRuntime().gc(); 15009 // Delete the resources here after sending the broadcast to let 15010 // other processes clean up before deleting resources. 15011 if (info.args != null) { 15012 synchronized (mInstallLock) { 15013 info.args.doPostDeleteLI(true); 15014 } 15015 } 15016 15017 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15018 } 15019 15020 class PackageRemovedInfo { 15021 String removedPackage; 15022 int uid = -1; 15023 int removedAppId = -1; 15024 int[] origUsers; 15025 int[] removedUsers = null; 15026 boolean isRemovedPackageSystemUpdate = false; 15027 boolean isUpdate; 15028 boolean dataRemoved; 15029 boolean removedForAllUsers; 15030 // Clean up resources deleted packages. 15031 InstallArgs args = null; 15032 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 15033 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 15034 15035 void sendPackageRemovedBroadcasts(boolean killApp) { 15036 sendPackageRemovedBroadcastInternal(killApp); 15037 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 15038 for (int i = 0; i < childCount; i++) { 15039 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15040 childInfo.sendPackageRemovedBroadcastInternal(killApp); 15041 } 15042 } 15043 15044 void sendSystemPackageUpdatedBroadcasts() { 15045 if (isRemovedPackageSystemUpdate) { 15046 sendSystemPackageUpdatedBroadcastsInternal(); 15047 final int childCount = (removedChildPackages != null) 15048 ? removedChildPackages.size() : 0; 15049 for (int i = 0; i < childCount; i++) { 15050 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15051 if (childInfo.isRemovedPackageSystemUpdate) { 15052 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 15053 } 15054 } 15055 } 15056 } 15057 15058 void sendSystemPackageAppearedBroadcasts() { 15059 final int packageCount = (appearedChildPackages != null) 15060 ? appearedChildPackages.size() : 0; 15061 for (int i = 0; i < packageCount; i++) { 15062 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 15063 for (int userId : installedInfo.newUsers) { 15064 sendPackageAddedForUser(installedInfo.name, true, 15065 UserHandle.getAppId(installedInfo.uid), userId); 15066 } 15067 } 15068 } 15069 15070 private void sendSystemPackageUpdatedBroadcastsInternal() { 15071 Bundle extras = new Bundle(2); 15072 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15073 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15074 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 15075 extras, 0, null, null, null); 15076 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 15077 extras, 0, null, null, null); 15078 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 15079 null, 0, removedPackage, null, null); 15080 } 15081 15082 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 15083 Bundle extras = new Bundle(2); 15084 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15085 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 15086 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 15087 if (isUpdate || isRemovedPackageSystemUpdate) { 15088 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15089 } 15090 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 15091 if (removedPackage != null) { 15092 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 15093 extras, 0, null, null, removedUsers); 15094 if (dataRemoved && !isRemovedPackageSystemUpdate) { 15095 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 15096 removedPackage, extras, 0, null, null, removedUsers); 15097 } 15098 } 15099 if (removedAppId >= 0) { 15100 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 15101 removedUsers); 15102 } 15103 } 15104 } 15105 15106 /* 15107 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 15108 * flag is not set, the data directory is removed as well. 15109 * make sure this flag is set for partially installed apps. If not its meaningless to 15110 * delete a partially installed application. 15111 */ 15112 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 15113 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 15114 String packageName = ps.name; 15115 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 15116 // Retrieve object to delete permissions for shared user later on 15117 final PackageParser.Package deletedPkg; 15118 final PackageSetting deletedPs; 15119 // reader 15120 synchronized (mPackages) { 15121 deletedPkg = mPackages.get(packageName); 15122 deletedPs = mSettings.mPackages.get(packageName); 15123 if (outInfo != null) { 15124 outInfo.removedPackage = packageName; 15125 outInfo.removedUsers = deletedPs != null 15126 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 15127 : null; 15128 } 15129 } 15130 15131 removePackageLI(ps, (flags & REMOVE_CHATTY) != 0); 15132 15133 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 15134 destroyAppDataLIF(deletedPkg, UserHandle.USER_ALL, 15135 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15136 destroyAppProfilesLIF(deletedPkg); 15137 if (outInfo != null) { 15138 outInfo.dataRemoved = true; 15139 } 15140 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 15141 } 15142 15143 // writer 15144 synchronized (mPackages) { 15145 if (deletedPs != null) { 15146 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 15147 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 15148 clearDefaultBrowserIfNeeded(packageName); 15149 if (outInfo != null) { 15150 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 15151 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 15152 } 15153 updatePermissionsLPw(deletedPs.name, null, 0); 15154 if (deletedPs.sharedUser != null) { 15155 // Remove permissions associated with package. Since runtime 15156 // permissions are per user we have to kill the removed package 15157 // or packages running under the shared user of the removed 15158 // package if revoking the permissions requested only by the removed 15159 // package is successful and this causes a change in gids. 15160 for (int userId : UserManagerService.getInstance().getUserIds()) { 15161 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 15162 userId); 15163 if (userIdToKill == UserHandle.USER_ALL 15164 || userIdToKill >= UserHandle.USER_SYSTEM) { 15165 // If gids changed for this user, kill all affected packages. 15166 mHandler.post(new Runnable() { 15167 @Override 15168 public void run() { 15169 // This has to happen with no lock held. 15170 killApplication(deletedPs.name, deletedPs.appId, 15171 KILL_APP_REASON_GIDS_CHANGED); 15172 } 15173 }); 15174 break; 15175 } 15176 } 15177 } 15178 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 15179 } 15180 // make sure to preserve per-user disabled state if this removal was just 15181 // a downgrade of a system app to the factory package 15182 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 15183 if (DEBUG_REMOVE) { 15184 Slog.d(TAG, "Propagating install state across downgrade"); 15185 } 15186 for (int userId : allUserHandles) { 15187 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15188 if (DEBUG_REMOVE) { 15189 Slog.d(TAG, " user " + userId + " => " + installed); 15190 } 15191 ps.setInstalled(installed, userId); 15192 } 15193 } 15194 } 15195 // can downgrade to reader 15196 if (writeSettings) { 15197 // Save settings now 15198 mSettings.writeLPr(); 15199 } 15200 } 15201 if (outInfo != null) { 15202 // A user ID was deleted here. Go through all users and remove it 15203 // from KeyStore. 15204 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 15205 } 15206 } 15207 15208 static boolean locationIsPrivileged(File path) { 15209 try { 15210 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 15211 .getCanonicalPath(); 15212 return path.getCanonicalPath().startsWith(privilegedAppDir); 15213 } catch (IOException e) { 15214 Slog.e(TAG, "Unable to access code path " + path); 15215 } 15216 return false; 15217 } 15218 15219 /* 15220 * Tries to delete system package. 15221 */ 15222 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 15223 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 15224 boolean writeSettings) { 15225 if (deletedPs.parentPackageName != null) { 15226 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 15227 return false; 15228 } 15229 15230 final boolean applyUserRestrictions 15231 = (allUserHandles != null) && (outInfo.origUsers != null); 15232 final PackageSetting disabledPs; 15233 // Confirm if the system package has been updated 15234 // An updated system app can be deleted. This will also have to restore 15235 // the system pkg from system partition 15236 // reader 15237 synchronized (mPackages) { 15238 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 15239 } 15240 15241 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 15242 + " disabledPs=" + disabledPs); 15243 15244 if (disabledPs == null) { 15245 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 15246 return false; 15247 } else if (DEBUG_REMOVE) { 15248 Slog.d(TAG, "Deleting system pkg from data partition"); 15249 } 15250 15251 if (DEBUG_REMOVE) { 15252 if (applyUserRestrictions) { 15253 Slog.d(TAG, "Remembering install states:"); 15254 for (int userId : allUserHandles) { 15255 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 15256 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 15257 } 15258 } 15259 } 15260 15261 // Delete the updated package 15262 outInfo.isRemovedPackageSystemUpdate = true; 15263 if (outInfo.removedChildPackages != null) { 15264 final int childCount = (deletedPs.childPackageNames != null) 15265 ? deletedPs.childPackageNames.size() : 0; 15266 for (int i = 0; i < childCount; i++) { 15267 String childPackageName = deletedPs.childPackageNames.get(i); 15268 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 15269 .contains(childPackageName)) { 15270 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15271 childPackageName); 15272 if (childInfo != null) { 15273 childInfo.isRemovedPackageSystemUpdate = true; 15274 } 15275 } 15276 } 15277 } 15278 15279 if (disabledPs.versionCode < deletedPs.versionCode) { 15280 // Delete data for downgrades 15281 flags &= ~PackageManager.DELETE_KEEP_DATA; 15282 } else { 15283 // Preserve data by setting flag 15284 flags |= PackageManager.DELETE_KEEP_DATA; 15285 } 15286 15287 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 15288 outInfo, writeSettings, disabledPs.pkg); 15289 if (!ret) { 15290 return false; 15291 } 15292 15293 // writer 15294 synchronized (mPackages) { 15295 // Reinstate the old system package 15296 enableSystemPackageLPw(disabledPs.pkg); 15297 // Remove any native libraries from the upgraded package. 15298 removeNativeBinariesLI(deletedPs); 15299 } 15300 15301 // Install the system package 15302 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 15303 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 15304 if (locationIsPrivileged(disabledPs.codePath)) { 15305 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 15306 } 15307 15308 final PackageParser.Package newPkg; 15309 try { 15310 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 15311 } catch (PackageManagerException e) { 15312 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 15313 + e.getMessage()); 15314 return false; 15315 } 15316 15317 prepareAppDataAfterInstallLIF(newPkg); 15318 15319 // writer 15320 synchronized (mPackages) { 15321 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 15322 15323 // Propagate the permissions state as we do not want to drop on the floor 15324 // runtime permissions. The update permissions method below will take 15325 // care of removing obsolete permissions and grant install permissions. 15326 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 15327 updatePermissionsLPw(newPkg.packageName, newPkg, 15328 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 15329 15330 if (applyUserRestrictions) { 15331 if (DEBUG_REMOVE) { 15332 Slog.d(TAG, "Propagating install state across reinstall"); 15333 } 15334 for (int userId : allUserHandles) { 15335 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15336 if (DEBUG_REMOVE) { 15337 Slog.d(TAG, " user " + userId + " => " + installed); 15338 } 15339 ps.setInstalled(installed, userId); 15340 15341 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 15342 } 15343 // Regardless of writeSettings we need to ensure that this restriction 15344 // state propagation is persisted 15345 mSettings.writeAllUsersPackageRestrictionsLPr(); 15346 } 15347 // can downgrade to reader here 15348 if (writeSettings) { 15349 mSettings.writeLPr(); 15350 } 15351 } 15352 return true; 15353 } 15354 15355 private boolean deleteInstalledPackageLIF(PackageSetting ps, 15356 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 15357 PackageRemovedInfo outInfo, boolean writeSettings, 15358 PackageParser.Package replacingPackage) { 15359 synchronized (mPackages) { 15360 if (outInfo != null) { 15361 outInfo.uid = ps.appId; 15362 } 15363 15364 if (outInfo != null && outInfo.removedChildPackages != null) { 15365 final int childCount = (ps.childPackageNames != null) 15366 ? ps.childPackageNames.size() : 0; 15367 for (int i = 0; i < childCount; i++) { 15368 String childPackageName = ps.childPackageNames.get(i); 15369 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 15370 if (childPs == null) { 15371 return false; 15372 } 15373 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15374 childPackageName); 15375 if (childInfo != null) { 15376 childInfo.uid = childPs.appId; 15377 } 15378 } 15379 } 15380 } 15381 15382 // Delete package data from internal structures and also remove data if flag is set 15383 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 15384 15385 // Delete the child packages data 15386 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 15387 for (int i = 0; i < childCount; i++) { 15388 PackageSetting childPs; 15389 synchronized (mPackages) { 15390 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 15391 } 15392 if (childPs != null) { 15393 PackageRemovedInfo childOutInfo = (outInfo != null 15394 && outInfo.removedChildPackages != null) 15395 ? outInfo.removedChildPackages.get(childPs.name) : null; 15396 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 15397 && (replacingPackage != null 15398 && !replacingPackage.hasChildPackage(childPs.name)) 15399 ? flags & ~DELETE_KEEP_DATA : flags; 15400 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 15401 deleteFlags, writeSettings); 15402 } 15403 } 15404 15405 // Delete application code and resources only for parent packages 15406 if (ps.parentPackageName == null) { 15407 if (deleteCodeAndResources && (outInfo != null)) { 15408 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 15409 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 15410 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 15411 } 15412 } 15413 15414 return true; 15415 } 15416 15417 @Override 15418 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 15419 int userId) { 15420 mContext.enforceCallingOrSelfPermission( 15421 android.Manifest.permission.DELETE_PACKAGES, null); 15422 synchronized (mPackages) { 15423 PackageSetting ps = mSettings.mPackages.get(packageName); 15424 if (ps == null) { 15425 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 15426 return false; 15427 } 15428 if (!ps.getInstalled(userId)) { 15429 // Can't block uninstall for an app that is not installed or enabled. 15430 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 15431 return false; 15432 } 15433 ps.setBlockUninstall(blockUninstall, userId); 15434 mSettings.writePackageRestrictionsLPr(userId); 15435 } 15436 return true; 15437 } 15438 15439 @Override 15440 public boolean getBlockUninstallForUser(String packageName, int userId) { 15441 synchronized (mPackages) { 15442 PackageSetting ps = mSettings.mPackages.get(packageName); 15443 if (ps == null) { 15444 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 15445 return false; 15446 } 15447 return ps.getBlockUninstall(userId); 15448 } 15449 } 15450 15451 @Override 15452 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 15453 int callingUid = Binder.getCallingUid(); 15454 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 15455 throw new SecurityException( 15456 "setRequiredForSystemUser can only be run by the system or root"); 15457 } 15458 synchronized (mPackages) { 15459 PackageSetting ps = mSettings.mPackages.get(packageName); 15460 if (ps == null) { 15461 Log.w(TAG, "Package doesn't exist: " + packageName); 15462 return false; 15463 } 15464 if (systemUserApp) { 15465 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15466 } else { 15467 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15468 } 15469 mSettings.writeLPr(); 15470 } 15471 return true; 15472 } 15473 15474 /* 15475 * This method handles package deletion in general 15476 */ 15477 private boolean deletePackageLIF(String packageName, UserHandle user, 15478 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 15479 PackageRemovedInfo outInfo, boolean writeSettings, 15480 PackageParser.Package replacingPackage) { 15481 if (packageName == null) { 15482 Slog.w(TAG, "Attempt to delete null packageName."); 15483 return false; 15484 } 15485 15486 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 15487 15488 PackageSetting ps; 15489 15490 synchronized (mPackages) { 15491 ps = mSettings.mPackages.get(packageName); 15492 if (ps == null) { 15493 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 15494 return false; 15495 } 15496 15497 if (ps.parentPackageName != null && (!isSystemApp(ps) 15498 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 15499 if (DEBUG_REMOVE) { 15500 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 15501 + ((user == null) ? UserHandle.USER_ALL : user)); 15502 } 15503 final int removedUserId = (user != null) ? user.getIdentifier() 15504 : UserHandle.USER_ALL; 15505 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 15506 return false; 15507 } 15508 markPackageUninstalledForUserLPw(ps, user); 15509 scheduleWritePackageRestrictionsLocked(user); 15510 return true; 15511 } 15512 } 15513 15514 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 15515 && user.getIdentifier() != UserHandle.USER_ALL)) { 15516 // The caller is asking that the package only be deleted for a single 15517 // user. To do this, we just mark its uninstalled state and delete 15518 // its data. If this is a system app, we only allow this to happen if 15519 // they have set the special DELETE_SYSTEM_APP which requests different 15520 // semantics than normal for uninstalling system apps. 15521 markPackageUninstalledForUserLPw(ps, user); 15522 15523 if (!isSystemApp(ps)) { 15524 // Do not uninstall the APK if an app should be cached 15525 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 15526 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 15527 // Other user still have this package installed, so all 15528 // we need to do is clear this user's data and save that 15529 // it is uninstalled. 15530 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 15531 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 15532 return false; 15533 } 15534 scheduleWritePackageRestrictionsLocked(user); 15535 return true; 15536 } else { 15537 // We need to set it back to 'installed' so the uninstall 15538 // broadcasts will be sent correctly. 15539 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 15540 ps.setInstalled(true, user.getIdentifier()); 15541 } 15542 } else { 15543 // This is a system app, so we assume that the 15544 // other users still have this package installed, so all 15545 // we need to do is clear this user's data and save that 15546 // it is uninstalled. 15547 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 15548 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 15549 return false; 15550 } 15551 scheduleWritePackageRestrictionsLocked(user); 15552 return true; 15553 } 15554 } 15555 15556 // If we are deleting a composite package for all users, keep track 15557 // of result for each child. 15558 if (ps.childPackageNames != null && outInfo != null) { 15559 synchronized (mPackages) { 15560 final int childCount = ps.childPackageNames.size(); 15561 outInfo.removedChildPackages = new ArrayMap<>(childCount); 15562 for (int i = 0; i < childCount; i++) { 15563 String childPackageName = ps.childPackageNames.get(i); 15564 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 15565 childInfo.removedPackage = childPackageName; 15566 outInfo.removedChildPackages.put(childPackageName, childInfo); 15567 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 15568 if (childPs != null) { 15569 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 15570 } 15571 } 15572 } 15573 } 15574 15575 boolean ret = false; 15576 if (isSystemApp(ps)) { 15577 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 15578 // When an updated system application is deleted we delete the existing resources 15579 // as well and fall back to existing code in system partition 15580 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 15581 } else { 15582 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 15583 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 15584 outInfo, writeSettings, replacingPackage); 15585 } 15586 15587 // Take a note whether we deleted the package for all users 15588 if (outInfo != null) { 15589 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 15590 if (outInfo.removedChildPackages != null) { 15591 synchronized (mPackages) { 15592 final int childCount = outInfo.removedChildPackages.size(); 15593 for (int i = 0; i < childCount; i++) { 15594 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 15595 if (childInfo != null) { 15596 childInfo.removedForAllUsers = mPackages.get( 15597 childInfo.removedPackage) == null; 15598 } 15599 } 15600 } 15601 } 15602 // If we uninstalled an update to a system app there may be some 15603 // child packages that appeared as they are declared in the system 15604 // app but were not declared in the update. 15605 if (isSystemApp(ps)) { 15606 synchronized (mPackages) { 15607 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 15608 final int childCount = (updatedPs.childPackageNames != null) 15609 ? updatedPs.childPackageNames.size() : 0; 15610 for (int i = 0; i < childCount; i++) { 15611 String childPackageName = updatedPs.childPackageNames.get(i); 15612 if (outInfo.removedChildPackages == null 15613 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 15614 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 15615 if (childPs == null) { 15616 continue; 15617 } 15618 PackageInstalledInfo installRes = new PackageInstalledInfo(); 15619 installRes.name = childPackageName; 15620 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 15621 installRes.pkg = mPackages.get(childPackageName); 15622 installRes.uid = childPs.pkg.applicationInfo.uid; 15623 if (outInfo.appearedChildPackages == null) { 15624 outInfo.appearedChildPackages = new ArrayMap<>(); 15625 } 15626 outInfo.appearedChildPackages.put(childPackageName, installRes); 15627 } 15628 } 15629 } 15630 } 15631 } 15632 15633 return ret; 15634 } 15635 15636 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 15637 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 15638 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 15639 for (int nextUserId : userIds) { 15640 if (DEBUG_REMOVE) { 15641 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 15642 } 15643 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 15644 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 15645 false /*hidden*/, false /*suspended*/, null, null, null, 15646 false /*blockUninstall*/, 15647 ps.readUserState(nextUserId).domainVerificationStatus, 0); 15648 } 15649 } 15650 15651 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 15652 PackageRemovedInfo outInfo) { 15653 final PackageParser.Package pkg; 15654 synchronized (mPackages) { 15655 pkg = mPackages.get(ps.name); 15656 } 15657 15658 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 15659 : new int[] {userId}; 15660 for (int nextUserId : userIds) { 15661 if (DEBUG_REMOVE) { 15662 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 15663 + nextUserId); 15664 } 15665 15666 destroyAppDataLIF(pkg, userId, 15667 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15668 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 15669 schedulePackageCleaning(ps.name, nextUserId, false); 15670 synchronized (mPackages) { 15671 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 15672 scheduleWritePackageRestrictionsLocked(nextUserId); 15673 } 15674 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 15675 } 15676 } 15677 15678 if (outInfo != null) { 15679 outInfo.removedPackage = ps.name; 15680 outInfo.removedAppId = ps.appId; 15681 outInfo.removedUsers = userIds; 15682 } 15683 15684 return true; 15685 } 15686 15687 private final class ClearStorageConnection implements ServiceConnection { 15688 IMediaContainerService mContainerService; 15689 15690 @Override 15691 public void onServiceConnected(ComponentName name, IBinder service) { 15692 synchronized (this) { 15693 mContainerService = IMediaContainerService.Stub.asInterface(service); 15694 notifyAll(); 15695 } 15696 } 15697 15698 @Override 15699 public void onServiceDisconnected(ComponentName name) { 15700 } 15701 } 15702 15703 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 15704 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 15705 15706 final boolean mounted; 15707 if (Environment.isExternalStorageEmulated()) { 15708 mounted = true; 15709 } else { 15710 final String status = Environment.getExternalStorageState(); 15711 15712 mounted = status.equals(Environment.MEDIA_MOUNTED) 15713 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 15714 } 15715 15716 if (!mounted) { 15717 return; 15718 } 15719 15720 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 15721 int[] users; 15722 if (userId == UserHandle.USER_ALL) { 15723 users = sUserManager.getUserIds(); 15724 } else { 15725 users = new int[] { userId }; 15726 } 15727 final ClearStorageConnection conn = new ClearStorageConnection(); 15728 if (mContext.bindServiceAsUser( 15729 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 15730 try { 15731 for (int curUser : users) { 15732 long timeout = SystemClock.uptimeMillis() + 5000; 15733 synchronized (conn) { 15734 long now = SystemClock.uptimeMillis(); 15735 while (conn.mContainerService == null && now < timeout) { 15736 try { 15737 conn.wait(timeout - now); 15738 } catch (InterruptedException e) { 15739 } 15740 } 15741 } 15742 if (conn.mContainerService == null) { 15743 return; 15744 } 15745 15746 final UserEnvironment userEnv = new UserEnvironment(curUser); 15747 clearDirectory(conn.mContainerService, 15748 userEnv.buildExternalStorageAppCacheDirs(packageName)); 15749 if (allData) { 15750 clearDirectory(conn.mContainerService, 15751 userEnv.buildExternalStorageAppDataDirs(packageName)); 15752 clearDirectory(conn.mContainerService, 15753 userEnv.buildExternalStorageAppMediaDirs(packageName)); 15754 } 15755 } 15756 } finally { 15757 mContext.unbindService(conn); 15758 } 15759 } 15760 } 15761 15762 @Override 15763 public void clearApplicationProfileData(String packageName) { 15764 enforceSystemOrRoot("Only the system can clear all profile data"); 15765 15766 final PackageParser.Package pkg; 15767 synchronized (mPackages) { 15768 pkg = mPackages.get(packageName); 15769 } 15770 15771 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 15772 synchronized (mInstallLock) { 15773 clearAppProfilesLIF(pkg); 15774 } 15775 } 15776 } 15777 15778 @Override 15779 public void clearApplicationUserData(final String packageName, 15780 final IPackageDataObserver observer, final int userId) { 15781 mContext.enforceCallingOrSelfPermission( 15782 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 15783 15784 enforceCrossUserPermission(Binder.getCallingUid(), userId, 15785 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 15786 15787 final DevicePolicyManagerInternal dpmi = LocalServices 15788 .getService(DevicePolicyManagerInternal.class); 15789 if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) { 15790 throw new SecurityException("Cannot clear data for a device owner or a profile owner"); 15791 } 15792 // Queue up an async operation since the package deletion may take a little while. 15793 mHandler.post(new Runnable() { 15794 public void run() { 15795 mHandler.removeCallbacks(this); 15796 final boolean succeeded; 15797 try (PackageFreezer freezer = freezePackage(packageName, 15798 "clearApplicationUserData")) { 15799 synchronized (mInstallLock) { 15800 succeeded = clearApplicationUserDataLIF(packageName, userId); 15801 } 15802 clearExternalStorageDataSync(packageName, userId, true); 15803 } 15804 if (succeeded) { 15805 // invoke DeviceStorageMonitor's update method to clear any notifications 15806 DeviceStorageMonitorInternal dsm = LocalServices 15807 .getService(DeviceStorageMonitorInternal.class); 15808 if (dsm != null) { 15809 dsm.checkMemory(); 15810 } 15811 } 15812 if(observer != null) { 15813 try { 15814 observer.onRemoveCompleted(packageName, succeeded); 15815 } catch (RemoteException e) { 15816 Log.i(TAG, "Observer no longer exists."); 15817 } 15818 } //end if observer 15819 } //end run 15820 }); 15821 } 15822 15823 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 15824 if (packageName == null) { 15825 Slog.w(TAG, "Attempt to delete null packageName."); 15826 return false; 15827 } 15828 15829 // Try finding details about the requested package 15830 PackageParser.Package pkg; 15831 synchronized (mPackages) { 15832 pkg = mPackages.get(packageName); 15833 if (pkg == null) { 15834 final PackageSetting ps = mSettings.mPackages.get(packageName); 15835 if (ps != null) { 15836 pkg = ps.pkg; 15837 } 15838 } 15839 15840 if (pkg == null) { 15841 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 15842 return false; 15843 } 15844 15845 PackageSetting ps = (PackageSetting) pkg.mExtras; 15846 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 15847 } 15848 15849 clearAppDataLIF(pkg, userId, 15850 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15851 15852 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 15853 removeKeystoreDataIfNeeded(userId, appId); 15854 15855 final UserManager um = mContext.getSystemService(UserManager.class); 15856 final int flags; 15857 if (um.isUserUnlocked(userId)) { 15858 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 15859 } else if (um.isUserRunning(userId)) { 15860 flags = StorageManager.FLAG_STORAGE_DE; 15861 } else { 15862 flags = 0; 15863 } 15864 prepareAppDataContentsLIF(pkg, userId, flags); 15865 15866 return true; 15867 } 15868 15869 /** 15870 * Reverts user permission state changes (permissions and flags) in 15871 * all packages for a given user. 15872 * 15873 * @param userId The device user for which to do a reset. 15874 */ 15875 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 15876 final int packageCount = mPackages.size(); 15877 for (int i = 0; i < packageCount; i++) { 15878 PackageParser.Package pkg = mPackages.valueAt(i); 15879 PackageSetting ps = (PackageSetting) pkg.mExtras; 15880 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 15881 } 15882 } 15883 15884 /** 15885 * Reverts user permission state changes (permissions and flags). 15886 * 15887 * @param ps The package for which to reset. 15888 * @param userId The device user for which to do a reset. 15889 */ 15890 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 15891 final PackageSetting ps, final int userId) { 15892 if (ps.pkg == null) { 15893 return; 15894 } 15895 15896 // These are flags that can change base on user actions. 15897 final int userSettableMask = FLAG_PERMISSION_USER_SET 15898 | FLAG_PERMISSION_USER_FIXED 15899 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 15900 | FLAG_PERMISSION_REVIEW_REQUIRED; 15901 15902 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 15903 | FLAG_PERMISSION_POLICY_FIXED; 15904 15905 boolean writeInstallPermissions = false; 15906 boolean writeRuntimePermissions = false; 15907 15908 final int permissionCount = ps.pkg.requestedPermissions.size(); 15909 for (int i = 0; i < permissionCount; i++) { 15910 String permission = ps.pkg.requestedPermissions.get(i); 15911 15912 BasePermission bp = mSettings.mPermissions.get(permission); 15913 if (bp == null) { 15914 continue; 15915 } 15916 15917 // If shared user we just reset the state to which only this app contributed. 15918 if (ps.sharedUser != null) { 15919 boolean used = false; 15920 final int packageCount = ps.sharedUser.packages.size(); 15921 for (int j = 0; j < packageCount; j++) { 15922 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 15923 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 15924 && pkg.pkg.requestedPermissions.contains(permission)) { 15925 used = true; 15926 break; 15927 } 15928 } 15929 if (used) { 15930 continue; 15931 } 15932 } 15933 15934 PermissionsState permissionsState = ps.getPermissionsState(); 15935 15936 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 15937 15938 // Always clear the user settable flags. 15939 final boolean hasInstallState = permissionsState.getInstallPermissionState( 15940 bp.name) != null; 15941 // If permission review is enabled and this is a legacy app, mark the 15942 // permission as requiring a review as this is the initial state. 15943 int flags = 0; 15944 if (Build.PERMISSIONS_REVIEW_REQUIRED 15945 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 15946 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 15947 } 15948 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 15949 if (hasInstallState) { 15950 writeInstallPermissions = true; 15951 } else { 15952 writeRuntimePermissions = true; 15953 } 15954 } 15955 15956 // Below is only runtime permission handling. 15957 if (!bp.isRuntime()) { 15958 continue; 15959 } 15960 15961 // Never clobber system or policy. 15962 if ((oldFlags & policyOrSystemFlags) != 0) { 15963 continue; 15964 } 15965 15966 // If this permission was granted by default, make sure it is. 15967 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 15968 if (permissionsState.grantRuntimePermission(bp, userId) 15969 != PERMISSION_OPERATION_FAILURE) { 15970 writeRuntimePermissions = true; 15971 } 15972 // If permission review is enabled the permissions for a legacy apps 15973 // are represented as constantly granted runtime ones, so don't revoke. 15974 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 15975 // Otherwise, reset the permission. 15976 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 15977 switch (revokeResult) { 15978 case PERMISSION_OPERATION_SUCCESS: 15979 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 15980 writeRuntimePermissions = true; 15981 final int appId = ps.appId; 15982 mHandler.post(new Runnable() { 15983 @Override 15984 public void run() { 15985 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 15986 } 15987 }); 15988 } break; 15989 } 15990 } 15991 } 15992 15993 // Synchronously write as we are taking permissions away. 15994 if (writeRuntimePermissions) { 15995 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 15996 } 15997 15998 // Synchronously write as we are taking permissions away. 15999 if (writeInstallPermissions) { 16000 mSettings.writeLPr(); 16001 } 16002 } 16003 16004 /** 16005 * Remove entries from the keystore daemon. Will only remove it if the 16006 * {@code appId} is valid. 16007 */ 16008 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 16009 if (appId < 0) { 16010 return; 16011 } 16012 16013 final KeyStore keyStore = KeyStore.getInstance(); 16014 if (keyStore != null) { 16015 if (userId == UserHandle.USER_ALL) { 16016 for (final int individual : sUserManager.getUserIds()) { 16017 keyStore.clearUid(UserHandle.getUid(individual, appId)); 16018 } 16019 } else { 16020 keyStore.clearUid(UserHandle.getUid(userId, appId)); 16021 } 16022 } else { 16023 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 16024 } 16025 } 16026 16027 @Override 16028 public void deleteApplicationCacheFiles(final String packageName, 16029 final IPackageDataObserver observer) { 16030 mContext.enforceCallingOrSelfPermission( 16031 android.Manifest.permission.DELETE_CACHE_FILES, null); 16032 // Queue up an async operation since the package deletion may take a little while. 16033 final int userId = UserHandle.getCallingUserId(); 16034 16035 final PackageParser.Package pkg; 16036 synchronized (mPackages) { 16037 pkg = mPackages.get(packageName); 16038 } 16039 16040 mHandler.post(new Runnable() { 16041 public void run() { 16042 try (PackageFreezer freezer = freezePackage(packageName, 16043 "deleteApplicationCacheFiles")) { 16044 synchronized (mInstallLock) { 16045 final int flags = StorageManager.FLAG_STORAGE_DE 16046 | StorageManager.FLAG_STORAGE_CE; 16047 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 16048 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16049 } 16050 clearExternalStorageDataSync(packageName, userId, false); 16051 } 16052 if (observer != null) { 16053 try { 16054 observer.onRemoveCompleted(packageName, true); 16055 } catch (RemoteException e) { 16056 Log.i(TAG, "Observer no longer exists."); 16057 } 16058 } 16059 } 16060 }); 16061 } 16062 16063 @Override 16064 public void getPackageSizeInfo(final String packageName, int userHandle, 16065 final IPackageStatsObserver observer) { 16066 mContext.enforceCallingOrSelfPermission( 16067 android.Manifest.permission.GET_PACKAGE_SIZE, null); 16068 if (packageName == null) { 16069 throw new IllegalArgumentException("Attempt to get size of null packageName"); 16070 } 16071 16072 PackageStats stats = new PackageStats(packageName, userHandle); 16073 16074 /* 16075 * Queue up an async operation since the package measurement may take a 16076 * little while. 16077 */ 16078 Message msg = mHandler.obtainMessage(INIT_COPY); 16079 msg.obj = new MeasureParams(stats, observer); 16080 mHandler.sendMessage(msg); 16081 } 16082 16083 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 16084 final PackageSetting ps; 16085 synchronized (mPackages) { 16086 ps = mSettings.mPackages.get(packageName); 16087 if (ps == null) { 16088 Slog.w(TAG, "Failed to find settings for " + packageName); 16089 return false; 16090 } 16091 } 16092 try { 16093 mInstaller.getAppSize(ps.volumeUuid, packageName, userId, 16094 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 16095 ps.getCeDataInode(userId), ps.codePathString, stats); 16096 return true; 16097 } catch (InstallerException e) { 16098 Slog.w(TAG, String.valueOf(e)); 16099 return false; 16100 } 16101 } 16102 16103 private int getUidTargetSdkVersionLockedLPr(int uid) { 16104 Object obj = mSettings.getUserIdLPr(uid); 16105 if (obj instanceof SharedUserSetting) { 16106 final SharedUserSetting sus = (SharedUserSetting) obj; 16107 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 16108 final Iterator<PackageSetting> it = sus.packages.iterator(); 16109 while (it.hasNext()) { 16110 final PackageSetting ps = it.next(); 16111 if (ps.pkg != null) { 16112 int v = ps.pkg.applicationInfo.targetSdkVersion; 16113 if (v < vers) vers = v; 16114 } 16115 } 16116 return vers; 16117 } else if (obj instanceof PackageSetting) { 16118 final PackageSetting ps = (PackageSetting) obj; 16119 if (ps.pkg != null) { 16120 return ps.pkg.applicationInfo.targetSdkVersion; 16121 } 16122 } 16123 return Build.VERSION_CODES.CUR_DEVELOPMENT; 16124 } 16125 16126 @Override 16127 public void addPreferredActivity(IntentFilter filter, int match, 16128 ComponentName[] set, ComponentName activity, int userId) { 16129 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16130 "Adding preferred"); 16131 } 16132 16133 private void addPreferredActivityInternal(IntentFilter filter, int match, 16134 ComponentName[] set, ComponentName activity, boolean always, int userId, 16135 String opname) { 16136 // writer 16137 int callingUid = Binder.getCallingUid(); 16138 enforceCrossUserPermission(callingUid, userId, 16139 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 16140 if (filter.countActions() == 0) { 16141 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16142 return; 16143 } 16144 synchronized (mPackages) { 16145 if (mContext.checkCallingOrSelfPermission( 16146 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16147 != PackageManager.PERMISSION_GRANTED) { 16148 if (getUidTargetSdkVersionLockedLPr(callingUid) 16149 < Build.VERSION_CODES.FROYO) { 16150 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 16151 + callingUid); 16152 return; 16153 } 16154 mContext.enforceCallingOrSelfPermission( 16155 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16156 } 16157 16158 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 16159 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 16160 + userId + ":"); 16161 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16162 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 16163 scheduleWritePackageRestrictionsLocked(userId); 16164 } 16165 } 16166 16167 @Override 16168 public void replacePreferredActivity(IntentFilter filter, int match, 16169 ComponentName[] set, ComponentName activity, int userId) { 16170 if (filter.countActions() != 1) { 16171 throw new IllegalArgumentException( 16172 "replacePreferredActivity expects filter to have only 1 action."); 16173 } 16174 if (filter.countDataAuthorities() != 0 16175 || filter.countDataPaths() != 0 16176 || filter.countDataSchemes() > 1 16177 || filter.countDataTypes() != 0) { 16178 throw new IllegalArgumentException( 16179 "replacePreferredActivity expects filter to have no data authorities, " + 16180 "paths, or types; and at most one scheme."); 16181 } 16182 16183 final int callingUid = Binder.getCallingUid(); 16184 enforceCrossUserPermission(callingUid, userId, 16185 true /* requireFullPermission */, false /* checkShell */, 16186 "replace preferred activity"); 16187 synchronized (mPackages) { 16188 if (mContext.checkCallingOrSelfPermission( 16189 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16190 != PackageManager.PERMISSION_GRANTED) { 16191 if (getUidTargetSdkVersionLockedLPr(callingUid) 16192 < Build.VERSION_CODES.FROYO) { 16193 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 16194 + Binder.getCallingUid()); 16195 return; 16196 } 16197 mContext.enforceCallingOrSelfPermission( 16198 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16199 } 16200 16201 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16202 if (pir != null) { 16203 // Get all of the existing entries that exactly match this filter. 16204 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 16205 if (existing != null && existing.size() == 1) { 16206 PreferredActivity cur = existing.get(0); 16207 if (DEBUG_PREFERRED) { 16208 Slog.i(TAG, "Checking replace of preferred:"); 16209 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16210 if (!cur.mPref.mAlways) { 16211 Slog.i(TAG, " -- CUR; not mAlways!"); 16212 } else { 16213 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 16214 Slog.i(TAG, " -- CUR: mSet=" 16215 + Arrays.toString(cur.mPref.mSetComponents)); 16216 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 16217 Slog.i(TAG, " -- NEW: mMatch=" 16218 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 16219 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 16220 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 16221 } 16222 } 16223 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 16224 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 16225 && cur.mPref.sameSet(set)) { 16226 // Setting the preferred activity to what it happens to be already 16227 if (DEBUG_PREFERRED) { 16228 Slog.i(TAG, "Replacing with same preferred activity " 16229 + cur.mPref.mShortComponent + " for user " 16230 + userId + ":"); 16231 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16232 } 16233 return; 16234 } 16235 } 16236 16237 if (existing != null) { 16238 if (DEBUG_PREFERRED) { 16239 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 16240 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16241 } 16242 for (int i = 0; i < existing.size(); i++) { 16243 PreferredActivity pa = existing.get(i); 16244 if (DEBUG_PREFERRED) { 16245 Slog.i(TAG, "Removing existing preferred activity " 16246 + pa.mPref.mComponent + ":"); 16247 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 16248 } 16249 pir.removeFilter(pa); 16250 } 16251 } 16252 } 16253 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16254 "Replacing preferred"); 16255 } 16256 } 16257 16258 @Override 16259 public void clearPackagePreferredActivities(String packageName) { 16260 final int uid = Binder.getCallingUid(); 16261 // writer 16262 synchronized (mPackages) { 16263 PackageParser.Package pkg = mPackages.get(packageName); 16264 if (pkg == null || pkg.applicationInfo.uid != uid) { 16265 if (mContext.checkCallingOrSelfPermission( 16266 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16267 != PackageManager.PERMISSION_GRANTED) { 16268 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 16269 < Build.VERSION_CODES.FROYO) { 16270 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 16271 + Binder.getCallingUid()); 16272 return; 16273 } 16274 mContext.enforceCallingOrSelfPermission( 16275 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16276 } 16277 } 16278 16279 int user = UserHandle.getCallingUserId(); 16280 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 16281 scheduleWritePackageRestrictionsLocked(user); 16282 } 16283 } 16284 } 16285 16286 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16287 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 16288 ArrayList<PreferredActivity> removed = null; 16289 boolean changed = false; 16290 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16291 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 16292 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16293 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 16294 continue; 16295 } 16296 Iterator<PreferredActivity> it = pir.filterIterator(); 16297 while (it.hasNext()) { 16298 PreferredActivity pa = it.next(); 16299 // Mark entry for removal only if it matches the package name 16300 // and the entry is of type "always". 16301 if (packageName == null || 16302 (pa.mPref.mComponent.getPackageName().equals(packageName) 16303 && pa.mPref.mAlways)) { 16304 if (removed == null) { 16305 removed = new ArrayList<PreferredActivity>(); 16306 } 16307 removed.add(pa); 16308 } 16309 } 16310 if (removed != null) { 16311 for (int j=0; j<removed.size(); j++) { 16312 PreferredActivity pa = removed.get(j); 16313 pir.removeFilter(pa); 16314 } 16315 changed = true; 16316 } 16317 } 16318 return changed; 16319 } 16320 16321 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16322 private void clearIntentFilterVerificationsLPw(int userId) { 16323 final int packageCount = mPackages.size(); 16324 for (int i = 0; i < packageCount; i++) { 16325 PackageParser.Package pkg = mPackages.valueAt(i); 16326 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 16327 } 16328 } 16329 16330 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16331 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 16332 if (userId == UserHandle.USER_ALL) { 16333 if (mSettings.removeIntentFilterVerificationLPw(packageName, 16334 sUserManager.getUserIds())) { 16335 for (int oneUserId : sUserManager.getUserIds()) { 16336 scheduleWritePackageRestrictionsLocked(oneUserId); 16337 } 16338 } 16339 } else { 16340 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 16341 scheduleWritePackageRestrictionsLocked(userId); 16342 } 16343 } 16344 } 16345 16346 void clearDefaultBrowserIfNeeded(String packageName) { 16347 for (int oneUserId : sUserManager.getUserIds()) { 16348 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 16349 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 16350 if (packageName.equals(defaultBrowserPackageName)) { 16351 setDefaultBrowserPackageName(null, oneUserId); 16352 } 16353 } 16354 } 16355 16356 @Override 16357 public void resetApplicationPreferences(int userId) { 16358 mContext.enforceCallingOrSelfPermission( 16359 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16360 // writer 16361 synchronized (mPackages) { 16362 final long identity = Binder.clearCallingIdentity(); 16363 try { 16364 clearPackagePreferredActivitiesLPw(null, userId); 16365 mSettings.applyDefaultPreferredAppsLPw(this, userId); 16366 // TODO: We have to reset the default SMS and Phone. This requires 16367 // significant refactoring to keep all default apps in the package 16368 // manager (cleaner but more work) or have the services provide 16369 // callbacks to the package manager to request a default app reset. 16370 applyFactoryDefaultBrowserLPw(userId); 16371 clearIntentFilterVerificationsLPw(userId); 16372 primeDomainVerificationsLPw(userId); 16373 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 16374 scheduleWritePackageRestrictionsLocked(userId); 16375 } finally { 16376 Binder.restoreCallingIdentity(identity); 16377 } 16378 } 16379 } 16380 16381 @Override 16382 public int getPreferredActivities(List<IntentFilter> outFilters, 16383 List<ComponentName> outActivities, String packageName) { 16384 16385 int num = 0; 16386 final int userId = UserHandle.getCallingUserId(); 16387 // reader 16388 synchronized (mPackages) { 16389 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16390 if (pir != null) { 16391 final Iterator<PreferredActivity> it = pir.filterIterator(); 16392 while (it.hasNext()) { 16393 final PreferredActivity pa = it.next(); 16394 if (packageName == null 16395 || (pa.mPref.mComponent.getPackageName().equals(packageName) 16396 && pa.mPref.mAlways)) { 16397 if (outFilters != null) { 16398 outFilters.add(new IntentFilter(pa)); 16399 } 16400 if (outActivities != null) { 16401 outActivities.add(pa.mPref.mComponent); 16402 } 16403 } 16404 } 16405 } 16406 } 16407 16408 return num; 16409 } 16410 16411 @Override 16412 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 16413 int userId) { 16414 int callingUid = Binder.getCallingUid(); 16415 if (callingUid != Process.SYSTEM_UID) { 16416 throw new SecurityException( 16417 "addPersistentPreferredActivity can only be run by the system"); 16418 } 16419 if (filter.countActions() == 0) { 16420 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16421 return; 16422 } 16423 synchronized (mPackages) { 16424 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 16425 ":"); 16426 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16427 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 16428 new PersistentPreferredActivity(filter, activity)); 16429 scheduleWritePackageRestrictionsLocked(userId); 16430 } 16431 } 16432 16433 @Override 16434 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 16435 int callingUid = Binder.getCallingUid(); 16436 if (callingUid != Process.SYSTEM_UID) { 16437 throw new SecurityException( 16438 "clearPackagePersistentPreferredActivities can only be run by the system"); 16439 } 16440 ArrayList<PersistentPreferredActivity> removed = null; 16441 boolean changed = false; 16442 synchronized (mPackages) { 16443 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 16444 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 16445 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 16446 .valueAt(i); 16447 if (userId != thisUserId) { 16448 continue; 16449 } 16450 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 16451 while (it.hasNext()) { 16452 PersistentPreferredActivity ppa = it.next(); 16453 // Mark entry for removal only if it matches the package name. 16454 if (ppa.mComponent.getPackageName().equals(packageName)) { 16455 if (removed == null) { 16456 removed = new ArrayList<PersistentPreferredActivity>(); 16457 } 16458 removed.add(ppa); 16459 } 16460 } 16461 if (removed != null) { 16462 for (int j=0; j<removed.size(); j++) { 16463 PersistentPreferredActivity ppa = removed.get(j); 16464 ppir.removeFilter(ppa); 16465 } 16466 changed = true; 16467 } 16468 } 16469 16470 if (changed) { 16471 scheduleWritePackageRestrictionsLocked(userId); 16472 } 16473 } 16474 } 16475 16476 /** 16477 * Common machinery for picking apart a restored XML blob and passing 16478 * it to a caller-supplied functor to be applied to the running system. 16479 */ 16480 private void restoreFromXml(XmlPullParser parser, int userId, 16481 String expectedStartTag, BlobXmlRestorer functor) 16482 throws IOException, XmlPullParserException { 16483 int type; 16484 while ((type = parser.next()) != XmlPullParser.START_TAG 16485 && type != XmlPullParser.END_DOCUMENT) { 16486 } 16487 if (type != XmlPullParser.START_TAG) { 16488 // oops didn't find a start tag?! 16489 if (DEBUG_BACKUP) { 16490 Slog.e(TAG, "Didn't find start tag during restore"); 16491 } 16492 return; 16493 } 16494Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 16495 // this is supposed to be TAG_PREFERRED_BACKUP 16496 if (!expectedStartTag.equals(parser.getName())) { 16497 if (DEBUG_BACKUP) { 16498 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 16499 } 16500 return; 16501 } 16502 16503 // skip interfering stuff, then we're aligned with the backing implementation 16504 while ((type = parser.next()) == XmlPullParser.TEXT) { } 16505Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 16506 functor.apply(parser, userId); 16507 } 16508 16509 private interface BlobXmlRestorer { 16510 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 16511 } 16512 16513 /** 16514 * Non-Binder method, support for the backup/restore mechanism: write the 16515 * full set of preferred activities in its canonical XML format. Returns the 16516 * XML output as a byte array, or null if there is none. 16517 */ 16518 @Override 16519 public byte[] getPreferredActivityBackup(int userId) { 16520 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16521 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 16522 } 16523 16524 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16525 try { 16526 final XmlSerializer serializer = new FastXmlSerializer(); 16527 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16528 serializer.startDocument(null, true); 16529 serializer.startTag(null, TAG_PREFERRED_BACKUP); 16530 16531 synchronized (mPackages) { 16532 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 16533 } 16534 16535 serializer.endTag(null, TAG_PREFERRED_BACKUP); 16536 serializer.endDocument(); 16537 serializer.flush(); 16538 } catch (Exception e) { 16539 if (DEBUG_BACKUP) { 16540 Slog.e(TAG, "Unable to write preferred activities for backup", e); 16541 } 16542 return null; 16543 } 16544 16545 return dataStream.toByteArray(); 16546 } 16547 16548 @Override 16549 public void restorePreferredActivities(byte[] backup, int userId) { 16550 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16551 throw new SecurityException("Only the system may call restorePreferredActivities()"); 16552 } 16553 16554 try { 16555 final XmlPullParser parser = Xml.newPullParser(); 16556 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16557 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 16558 new BlobXmlRestorer() { 16559 @Override 16560 public void apply(XmlPullParser parser, int userId) 16561 throws XmlPullParserException, IOException { 16562 synchronized (mPackages) { 16563 mSettings.readPreferredActivitiesLPw(parser, userId); 16564 } 16565 } 16566 } ); 16567 } catch (Exception e) { 16568 if (DEBUG_BACKUP) { 16569 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16570 } 16571 } 16572 } 16573 16574 /** 16575 * Non-Binder method, support for the backup/restore mechanism: write the 16576 * default browser (etc) settings in its canonical XML format. Returns the default 16577 * browser XML representation as a byte array, or null if there is none. 16578 */ 16579 @Override 16580 public byte[] getDefaultAppsBackup(int userId) { 16581 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16582 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 16583 } 16584 16585 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16586 try { 16587 final XmlSerializer serializer = new FastXmlSerializer(); 16588 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16589 serializer.startDocument(null, true); 16590 serializer.startTag(null, TAG_DEFAULT_APPS); 16591 16592 synchronized (mPackages) { 16593 mSettings.writeDefaultAppsLPr(serializer, userId); 16594 } 16595 16596 serializer.endTag(null, TAG_DEFAULT_APPS); 16597 serializer.endDocument(); 16598 serializer.flush(); 16599 } catch (Exception e) { 16600 if (DEBUG_BACKUP) { 16601 Slog.e(TAG, "Unable to write default apps for backup", e); 16602 } 16603 return null; 16604 } 16605 16606 return dataStream.toByteArray(); 16607 } 16608 16609 @Override 16610 public void restoreDefaultApps(byte[] backup, int userId) { 16611 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16612 throw new SecurityException("Only the system may call restoreDefaultApps()"); 16613 } 16614 16615 try { 16616 final XmlPullParser parser = Xml.newPullParser(); 16617 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16618 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 16619 new BlobXmlRestorer() { 16620 @Override 16621 public void apply(XmlPullParser parser, int userId) 16622 throws XmlPullParserException, IOException { 16623 synchronized (mPackages) { 16624 mSettings.readDefaultAppsLPw(parser, userId); 16625 } 16626 } 16627 } ); 16628 } catch (Exception e) { 16629 if (DEBUG_BACKUP) { 16630 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 16631 } 16632 } 16633 } 16634 16635 @Override 16636 public byte[] getIntentFilterVerificationBackup(int userId) { 16637 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16638 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 16639 } 16640 16641 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16642 try { 16643 final XmlSerializer serializer = new FastXmlSerializer(); 16644 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16645 serializer.startDocument(null, true); 16646 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 16647 16648 synchronized (mPackages) { 16649 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 16650 } 16651 16652 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 16653 serializer.endDocument(); 16654 serializer.flush(); 16655 } catch (Exception e) { 16656 if (DEBUG_BACKUP) { 16657 Slog.e(TAG, "Unable to write default apps for backup", e); 16658 } 16659 return null; 16660 } 16661 16662 return dataStream.toByteArray(); 16663 } 16664 16665 @Override 16666 public void restoreIntentFilterVerification(byte[] backup, int userId) { 16667 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16668 throw new SecurityException("Only the system may call restorePreferredActivities()"); 16669 } 16670 16671 try { 16672 final XmlPullParser parser = Xml.newPullParser(); 16673 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16674 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 16675 new BlobXmlRestorer() { 16676 @Override 16677 public void apply(XmlPullParser parser, int userId) 16678 throws XmlPullParserException, IOException { 16679 synchronized (mPackages) { 16680 mSettings.readAllDomainVerificationsLPr(parser, userId); 16681 mSettings.writeLPr(); 16682 } 16683 } 16684 } ); 16685 } catch (Exception e) { 16686 if (DEBUG_BACKUP) { 16687 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16688 } 16689 } 16690 } 16691 16692 @Override 16693 public byte[] getPermissionGrantBackup(int userId) { 16694 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16695 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 16696 } 16697 16698 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16699 try { 16700 final XmlSerializer serializer = new FastXmlSerializer(); 16701 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16702 serializer.startDocument(null, true); 16703 serializer.startTag(null, TAG_PERMISSION_BACKUP); 16704 16705 synchronized (mPackages) { 16706 serializeRuntimePermissionGrantsLPr(serializer, userId); 16707 } 16708 16709 serializer.endTag(null, TAG_PERMISSION_BACKUP); 16710 serializer.endDocument(); 16711 serializer.flush(); 16712 } catch (Exception e) { 16713 if (DEBUG_BACKUP) { 16714 Slog.e(TAG, "Unable to write default apps for backup", e); 16715 } 16716 return null; 16717 } 16718 16719 return dataStream.toByteArray(); 16720 } 16721 16722 @Override 16723 public void restorePermissionGrants(byte[] backup, int userId) { 16724 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16725 throw new SecurityException("Only the system may call restorePermissionGrants()"); 16726 } 16727 16728 try { 16729 final XmlPullParser parser = Xml.newPullParser(); 16730 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16731 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 16732 new BlobXmlRestorer() { 16733 @Override 16734 public void apply(XmlPullParser parser, int userId) 16735 throws XmlPullParserException, IOException { 16736 synchronized (mPackages) { 16737 processRestoredPermissionGrantsLPr(parser, userId); 16738 } 16739 } 16740 } ); 16741 } catch (Exception e) { 16742 if (DEBUG_BACKUP) { 16743 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16744 } 16745 } 16746 } 16747 16748 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 16749 throws IOException { 16750 serializer.startTag(null, TAG_ALL_GRANTS); 16751 16752 final int N = mSettings.mPackages.size(); 16753 for (int i = 0; i < N; i++) { 16754 final PackageSetting ps = mSettings.mPackages.valueAt(i); 16755 boolean pkgGrantsKnown = false; 16756 16757 PermissionsState packagePerms = ps.getPermissionsState(); 16758 16759 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 16760 final int grantFlags = state.getFlags(); 16761 // only look at grants that are not system/policy fixed 16762 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 16763 final boolean isGranted = state.isGranted(); 16764 // And only back up the user-twiddled state bits 16765 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 16766 final String packageName = mSettings.mPackages.keyAt(i); 16767 if (!pkgGrantsKnown) { 16768 serializer.startTag(null, TAG_GRANT); 16769 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 16770 pkgGrantsKnown = true; 16771 } 16772 16773 final boolean userSet = 16774 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 16775 final boolean userFixed = 16776 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 16777 final boolean revoke = 16778 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 16779 16780 serializer.startTag(null, TAG_PERMISSION); 16781 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 16782 if (isGranted) { 16783 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 16784 } 16785 if (userSet) { 16786 serializer.attribute(null, ATTR_USER_SET, "true"); 16787 } 16788 if (userFixed) { 16789 serializer.attribute(null, ATTR_USER_FIXED, "true"); 16790 } 16791 if (revoke) { 16792 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 16793 } 16794 serializer.endTag(null, TAG_PERMISSION); 16795 } 16796 } 16797 } 16798 16799 if (pkgGrantsKnown) { 16800 serializer.endTag(null, TAG_GRANT); 16801 } 16802 } 16803 16804 serializer.endTag(null, TAG_ALL_GRANTS); 16805 } 16806 16807 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 16808 throws XmlPullParserException, IOException { 16809 String pkgName = null; 16810 int outerDepth = parser.getDepth(); 16811 int type; 16812 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 16813 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 16814 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 16815 continue; 16816 } 16817 16818 final String tagName = parser.getName(); 16819 if (tagName.equals(TAG_GRANT)) { 16820 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 16821 if (DEBUG_BACKUP) { 16822 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 16823 } 16824 } else if (tagName.equals(TAG_PERMISSION)) { 16825 16826 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 16827 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 16828 16829 int newFlagSet = 0; 16830 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 16831 newFlagSet |= FLAG_PERMISSION_USER_SET; 16832 } 16833 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 16834 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 16835 } 16836 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 16837 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 16838 } 16839 if (DEBUG_BACKUP) { 16840 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 16841 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 16842 } 16843 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16844 if (ps != null) { 16845 // Already installed so we apply the grant immediately 16846 if (DEBUG_BACKUP) { 16847 Slog.v(TAG, " + already installed; applying"); 16848 } 16849 PermissionsState perms = ps.getPermissionsState(); 16850 BasePermission bp = mSettings.mPermissions.get(permName); 16851 if (bp != null) { 16852 if (isGranted) { 16853 perms.grantRuntimePermission(bp, userId); 16854 } 16855 if (newFlagSet != 0) { 16856 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 16857 } 16858 } 16859 } else { 16860 // Need to wait for post-restore install to apply the grant 16861 if (DEBUG_BACKUP) { 16862 Slog.v(TAG, " - not yet installed; saving for later"); 16863 } 16864 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 16865 isGranted, newFlagSet, userId); 16866 } 16867 } else { 16868 PackageManagerService.reportSettingsProblem(Log.WARN, 16869 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 16870 XmlUtils.skipCurrentTag(parser); 16871 } 16872 } 16873 16874 scheduleWriteSettingsLocked(); 16875 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 16876 } 16877 16878 @Override 16879 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 16880 int sourceUserId, int targetUserId, int flags) { 16881 mContext.enforceCallingOrSelfPermission( 16882 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 16883 int callingUid = Binder.getCallingUid(); 16884 enforceOwnerRights(ownerPackage, callingUid); 16885 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 16886 if (intentFilter.countActions() == 0) { 16887 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 16888 return; 16889 } 16890 synchronized (mPackages) { 16891 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 16892 ownerPackage, targetUserId, flags); 16893 CrossProfileIntentResolver resolver = 16894 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 16895 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 16896 // We have all those whose filter is equal. Now checking if the rest is equal as well. 16897 if (existing != null) { 16898 int size = existing.size(); 16899 for (int i = 0; i < size; i++) { 16900 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 16901 return; 16902 } 16903 } 16904 } 16905 resolver.addFilter(newFilter); 16906 scheduleWritePackageRestrictionsLocked(sourceUserId); 16907 } 16908 } 16909 16910 @Override 16911 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 16912 mContext.enforceCallingOrSelfPermission( 16913 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 16914 int callingUid = Binder.getCallingUid(); 16915 enforceOwnerRights(ownerPackage, callingUid); 16916 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 16917 synchronized (mPackages) { 16918 CrossProfileIntentResolver resolver = 16919 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 16920 ArraySet<CrossProfileIntentFilter> set = 16921 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 16922 for (CrossProfileIntentFilter filter : set) { 16923 if (filter.getOwnerPackage().equals(ownerPackage)) { 16924 resolver.removeFilter(filter); 16925 } 16926 } 16927 scheduleWritePackageRestrictionsLocked(sourceUserId); 16928 } 16929 } 16930 16931 // Enforcing that callingUid is owning pkg on userId 16932 private void enforceOwnerRights(String pkg, int callingUid) { 16933 // The system owns everything. 16934 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 16935 return; 16936 } 16937 int callingUserId = UserHandle.getUserId(callingUid); 16938 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 16939 if (pi == null) { 16940 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 16941 + callingUserId); 16942 } 16943 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 16944 throw new SecurityException("Calling uid " + callingUid 16945 + " does not own package " + pkg); 16946 } 16947 } 16948 16949 @Override 16950 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 16951 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 16952 } 16953 16954 private Intent getHomeIntent() { 16955 Intent intent = new Intent(Intent.ACTION_MAIN); 16956 intent.addCategory(Intent.CATEGORY_HOME); 16957 return intent; 16958 } 16959 16960 private IntentFilter getHomeFilter() { 16961 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 16962 filter.addCategory(Intent.CATEGORY_HOME); 16963 filter.addCategory(Intent.CATEGORY_DEFAULT); 16964 return filter; 16965 } 16966 16967 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 16968 int userId) { 16969 Intent intent = getHomeIntent(); 16970 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 16971 PackageManager.GET_META_DATA, userId); 16972 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 16973 true, false, false, userId); 16974 16975 allHomeCandidates.clear(); 16976 if (list != null) { 16977 for (ResolveInfo ri : list) { 16978 allHomeCandidates.add(ri); 16979 } 16980 } 16981 return (preferred == null || preferred.activityInfo == null) 16982 ? null 16983 : new ComponentName(preferred.activityInfo.packageName, 16984 preferred.activityInfo.name); 16985 } 16986 16987 @Override 16988 public void setHomeActivity(ComponentName comp, int userId) { 16989 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 16990 getHomeActivitiesAsUser(homeActivities, userId); 16991 16992 boolean found = false; 16993 16994 final int size = homeActivities.size(); 16995 final ComponentName[] set = new ComponentName[size]; 16996 for (int i = 0; i < size; i++) { 16997 final ResolveInfo candidate = homeActivities.get(i); 16998 final ActivityInfo info = candidate.activityInfo; 16999 final ComponentName activityName = new ComponentName(info.packageName, info.name); 17000 set[i] = activityName; 17001 if (!found && activityName.equals(comp)) { 17002 found = true; 17003 } 17004 } 17005 if (!found) { 17006 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 17007 + userId); 17008 } 17009 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 17010 set, comp, userId); 17011 } 17012 17013 private @Nullable String getSetupWizardPackageName() { 17014 final Intent intent = new Intent(Intent.ACTION_MAIN); 17015 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 17016 17017 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 17018 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 17019 | MATCH_DISABLED_COMPONENTS, 17020 UserHandle.myUserId()); 17021 if (matches.size() == 1) { 17022 return matches.get(0).getComponentInfo().packageName; 17023 } else { 17024 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 17025 + ": matches=" + matches); 17026 return null; 17027 } 17028 } 17029 17030 @Override 17031 public void setApplicationEnabledSetting(String appPackageName, 17032 int newState, int flags, int userId, String callingPackage) { 17033 if (!sUserManager.exists(userId)) return; 17034 if (callingPackage == null) { 17035 callingPackage = Integer.toString(Binder.getCallingUid()); 17036 } 17037 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 17038 } 17039 17040 @Override 17041 public void setComponentEnabledSetting(ComponentName componentName, 17042 int newState, int flags, int userId) { 17043 if (!sUserManager.exists(userId)) return; 17044 setEnabledSetting(componentName.getPackageName(), 17045 componentName.getClassName(), newState, flags, userId, null); 17046 } 17047 17048 private void setEnabledSetting(final String packageName, String className, int newState, 17049 final int flags, int userId, String callingPackage) { 17050 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 17051 || newState == COMPONENT_ENABLED_STATE_ENABLED 17052 || newState == COMPONENT_ENABLED_STATE_DISABLED 17053 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17054 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 17055 throw new IllegalArgumentException("Invalid new component state: " 17056 + newState); 17057 } 17058 PackageSetting pkgSetting; 17059 final int uid = Binder.getCallingUid(); 17060 final int permission = mContext.checkCallingOrSelfPermission( 17061 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17062 enforceCrossUserPermission(uid, userId, 17063 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 17064 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17065 boolean sendNow = false; 17066 boolean isApp = (className == null); 17067 String componentName = isApp ? packageName : className; 17068 int packageUid = -1; 17069 ArrayList<String> components; 17070 17071 // writer 17072 synchronized (mPackages) { 17073 pkgSetting = mSettings.mPackages.get(packageName); 17074 if (pkgSetting == null) { 17075 if (className == null) { 17076 throw new IllegalArgumentException("Unknown package: " + packageName); 17077 } 17078 throw new IllegalArgumentException( 17079 "Unknown component: " + packageName + "/" + className); 17080 } 17081 // Allow root and verify that userId is not being specified by a different user 17082 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 17083 throw new SecurityException( 17084 "Permission Denial: attempt to change component state from pid=" 17085 + Binder.getCallingPid() 17086 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 17087 } 17088 if (className == null) { 17089 // We're dealing with an application/package level state change 17090 if (pkgSetting.getEnabled(userId) == newState) { 17091 // Nothing to do 17092 return; 17093 } 17094 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 17095 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 17096 // Don't care about who enables an app. 17097 callingPackage = null; 17098 } 17099 pkgSetting.setEnabled(newState, userId, callingPackage); 17100 // pkgSetting.pkg.mSetEnabled = newState; 17101 } else { 17102 // We're dealing with a component level state change 17103 // First, verify that this is a valid class name. 17104 PackageParser.Package pkg = pkgSetting.pkg; 17105 if (pkg == null || !pkg.hasComponentClassName(className)) { 17106 if (pkg != null && 17107 pkg.applicationInfo.targetSdkVersion >= 17108 Build.VERSION_CODES.JELLY_BEAN) { 17109 throw new IllegalArgumentException("Component class " + className 17110 + " does not exist in " + packageName); 17111 } else { 17112 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 17113 + className + " does not exist in " + packageName); 17114 } 17115 } 17116 switch (newState) { 17117 case COMPONENT_ENABLED_STATE_ENABLED: 17118 if (!pkgSetting.enableComponentLPw(className, userId)) { 17119 return; 17120 } 17121 break; 17122 case COMPONENT_ENABLED_STATE_DISABLED: 17123 if (!pkgSetting.disableComponentLPw(className, userId)) { 17124 return; 17125 } 17126 break; 17127 case COMPONENT_ENABLED_STATE_DEFAULT: 17128 if (!pkgSetting.restoreComponentLPw(className, userId)) { 17129 return; 17130 } 17131 break; 17132 default: 17133 Slog.e(TAG, "Invalid new component state: " + newState); 17134 return; 17135 } 17136 } 17137 scheduleWritePackageRestrictionsLocked(userId); 17138 components = mPendingBroadcasts.get(userId, packageName); 17139 final boolean newPackage = components == null; 17140 if (newPackage) { 17141 components = new ArrayList<String>(); 17142 } 17143 if (!components.contains(componentName)) { 17144 components.add(componentName); 17145 } 17146 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 17147 sendNow = true; 17148 // Purge entry from pending broadcast list if another one exists already 17149 // since we are sending one right away. 17150 mPendingBroadcasts.remove(userId, packageName); 17151 } else { 17152 if (newPackage) { 17153 mPendingBroadcasts.put(userId, packageName, components); 17154 } 17155 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 17156 // Schedule a message 17157 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 17158 } 17159 } 17160 } 17161 17162 long callingId = Binder.clearCallingIdentity(); 17163 try { 17164 if (sendNow) { 17165 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 17166 sendPackageChangedBroadcast(packageName, 17167 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 17168 } 17169 } finally { 17170 Binder.restoreCallingIdentity(callingId); 17171 } 17172 } 17173 17174 @Override 17175 public void flushPackageRestrictionsAsUser(int userId) { 17176 if (!sUserManager.exists(userId)) { 17177 return; 17178 } 17179 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 17180 false /* checkShell */, "flushPackageRestrictions"); 17181 synchronized (mPackages) { 17182 mSettings.writePackageRestrictionsLPr(userId); 17183 mDirtyUsers.remove(userId); 17184 if (mDirtyUsers.isEmpty()) { 17185 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 17186 } 17187 } 17188 } 17189 17190 private void sendPackageChangedBroadcast(String packageName, 17191 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 17192 if (DEBUG_INSTALL) 17193 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 17194 + componentNames); 17195 Bundle extras = new Bundle(4); 17196 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 17197 String nameList[] = new String[componentNames.size()]; 17198 componentNames.toArray(nameList); 17199 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 17200 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 17201 extras.putInt(Intent.EXTRA_UID, packageUid); 17202 // If this is not reporting a change of the overall package, then only send it 17203 // to registered receivers. We don't want to launch a swath of apps for every 17204 // little component state change. 17205 final int flags = !componentNames.contains(packageName) 17206 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 17207 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 17208 new int[] {UserHandle.getUserId(packageUid)}); 17209 } 17210 17211 @Override 17212 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 17213 if (!sUserManager.exists(userId)) return; 17214 final int uid = Binder.getCallingUid(); 17215 final int permission = mContext.checkCallingOrSelfPermission( 17216 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17217 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17218 enforceCrossUserPermission(uid, userId, 17219 true /* requireFullPermission */, true /* checkShell */, "stop package"); 17220 // writer 17221 synchronized (mPackages) { 17222 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 17223 allowedByPermission, uid, userId)) { 17224 scheduleWritePackageRestrictionsLocked(userId); 17225 } 17226 } 17227 } 17228 17229 @Override 17230 public String getInstallerPackageName(String packageName) { 17231 // reader 17232 synchronized (mPackages) { 17233 return mSettings.getInstallerPackageNameLPr(packageName); 17234 } 17235 } 17236 17237 @Override 17238 public int getApplicationEnabledSetting(String packageName, int userId) { 17239 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17240 int uid = Binder.getCallingUid(); 17241 enforceCrossUserPermission(uid, userId, 17242 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 17243 // reader 17244 synchronized (mPackages) { 17245 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 17246 } 17247 } 17248 17249 @Override 17250 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 17251 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17252 int uid = Binder.getCallingUid(); 17253 enforceCrossUserPermission(uid, userId, 17254 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 17255 // reader 17256 synchronized (mPackages) { 17257 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 17258 } 17259 } 17260 17261 @Override 17262 public void enterSafeMode() { 17263 enforceSystemOrRoot("Only the system can request entering safe mode"); 17264 17265 if (!mSystemReady) { 17266 mSafeMode = true; 17267 } 17268 } 17269 17270 @Override 17271 public void systemReady() { 17272 mSystemReady = true; 17273 17274 // Read the compatibilty setting when the system is ready. 17275 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 17276 mContext.getContentResolver(), 17277 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 17278 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 17279 if (DEBUG_SETTINGS) { 17280 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 17281 } 17282 17283 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 17284 17285 synchronized (mPackages) { 17286 // Verify that all of the preferred activity components actually 17287 // exist. It is possible for applications to be updated and at 17288 // that point remove a previously declared activity component that 17289 // had been set as a preferred activity. We try to clean this up 17290 // the next time we encounter that preferred activity, but it is 17291 // possible for the user flow to never be able to return to that 17292 // situation so here we do a sanity check to make sure we haven't 17293 // left any junk around. 17294 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 17295 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17296 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17297 removed.clear(); 17298 for (PreferredActivity pa : pir.filterSet()) { 17299 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 17300 removed.add(pa); 17301 } 17302 } 17303 if (removed.size() > 0) { 17304 for (int r=0; r<removed.size(); r++) { 17305 PreferredActivity pa = removed.get(r); 17306 Slog.w(TAG, "Removing dangling preferred activity: " 17307 + pa.mPref.mComponent); 17308 pir.removeFilter(pa); 17309 } 17310 mSettings.writePackageRestrictionsLPr( 17311 mSettings.mPreferredActivities.keyAt(i)); 17312 } 17313 } 17314 17315 for (int userId : UserManagerService.getInstance().getUserIds()) { 17316 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 17317 grantPermissionsUserIds = ArrayUtils.appendInt( 17318 grantPermissionsUserIds, userId); 17319 } 17320 } 17321 } 17322 sUserManager.systemReady(); 17323 17324 // If we upgraded grant all default permissions before kicking off. 17325 for (int userId : grantPermissionsUserIds) { 17326 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 17327 } 17328 17329 // Kick off any messages waiting for system ready 17330 if (mPostSystemReadyMessages != null) { 17331 for (Message msg : mPostSystemReadyMessages) { 17332 msg.sendToTarget(); 17333 } 17334 mPostSystemReadyMessages = null; 17335 } 17336 17337 // Watch for external volumes that come and go over time 17338 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17339 storage.registerListener(mStorageListener); 17340 17341 mInstallerService.systemReady(); 17342 mPackageDexOptimizer.systemReady(); 17343 17344 MountServiceInternal mountServiceInternal = LocalServices.getService( 17345 MountServiceInternal.class); 17346 mountServiceInternal.addExternalStoragePolicy( 17347 new MountServiceInternal.ExternalStorageMountPolicy() { 17348 @Override 17349 public int getMountMode(int uid, String packageName) { 17350 if (Process.isIsolated(uid)) { 17351 return Zygote.MOUNT_EXTERNAL_NONE; 17352 } 17353 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 17354 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17355 } 17356 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17357 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17358 } 17359 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17360 return Zygote.MOUNT_EXTERNAL_READ; 17361 } 17362 return Zygote.MOUNT_EXTERNAL_WRITE; 17363 } 17364 17365 @Override 17366 public boolean hasExternalStorage(int uid, String packageName) { 17367 return true; 17368 } 17369 }); 17370 } 17371 17372 @Override 17373 public boolean isSafeMode() { 17374 return mSafeMode; 17375 } 17376 17377 @Override 17378 public boolean hasSystemUidErrors() { 17379 return mHasSystemUidErrors; 17380 } 17381 17382 static String arrayToString(int[] array) { 17383 StringBuffer buf = new StringBuffer(128); 17384 buf.append('['); 17385 if (array != null) { 17386 for (int i=0; i<array.length; i++) { 17387 if (i > 0) buf.append(", "); 17388 buf.append(array[i]); 17389 } 17390 } 17391 buf.append(']'); 17392 return buf.toString(); 17393 } 17394 17395 static class DumpState { 17396 public static final int DUMP_LIBS = 1 << 0; 17397 public static final int DUMP_FEATURES = 1 << 1; 17398 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 17399 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 17400 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 17401 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 17402 public static final int DUMP_PERMISSIONS = 1 << 6; 17403 public static final int DUMP_PACKAGES = 1 << 7; 17404 public static final int DUMP_SHARED_USERS = 1 << 8; 17405 public static final int DUMP_MESSAGES = 1 << 9; 17406 public static final int DUMP_PROVIDERS = 1 << 10; 17407 public static final int DUMP_VERIFIERS = 1 << 11; 17408 public static final int DUMP_PREFERRED = 1 << 12; 17409 public static final int DUMP_PREFERRED_XML = 1 << 13; 17410 public static final int DUMP_KEYSETS = 1 << 14; 17411 public static final int DUMP_VERSION = 1 << 15; 17412 public static final int DUMP_INSTALLS = 1 << 16; 17413 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 17414 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 17415 public static final int DUMP_FROZEN = 1 << 19; 17416 17417 public static final int OPTION_SHOW_FILTERS = 1 << 0; 17418 17419 private int mTypes; 17420 17421 private int mOptions; 17422 17423 private boolean mTitlePrinted; 17424 17425 private SharedUserSetting mSharedUser; 17426 17427 public boolean isDumping(int type) { 17428 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 17429 return true; 17430 } 17431 17432 return (mTypes & type) != 0; 17433 } 17434 17435 public void setDump(int type) { 17436 mTypes |= type; 17437 } 17438 17439 public boolean isOptionEnabled(int option) { 17440 return (mOptions & option) != 0; 17441 } 17442 17443 public void setOptionEnabled(int option) { 17444 mOptions |= option; 17445 } 17446 17447 public boolean onTitlePrinted() { 17448 final boolean printed = mTitlePrinted; 17449 mTitlePrinted = true; 17450 return printed; 17451 } 17452 17453 public boolean getTitlePrinted() { 17454 return mTitlePrinted; 17455 } 17456 17457 public void setTitlePrinted(boolean enabled) { 17458 mTitlePrinted = enabled; 17459 } 17460 17461 public SharedUserSetting getSharedUser() { 17462 return mSharedUser; 17463 } 17464 17465 public void setSharedUser(SharedUserSetting user) { 17466 mSharedUser = user; 17467 } 17468 } 17469 17470 @Override 17471 public void onShellCommand(FileDescriptor in, FileDescriptor out, 17472 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 17473 (new PackageManagerShellCommand(this)).exec( 17474 this, in, out, err, args, resultReceiver); 17475 } 17476 17477 @Override 17478 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 17479 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 17480 != PackageManager.PERMISSION_GRANTED) { 17481 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 17482 + Binder.getCallingPid() 17483 + ", uid=" + Binder.getCallingUid() 17484 + " without permission " 17485 + android.Manifest.permission.DUMP); 17486 return; 17487 } 17488 17489 DumpState dumpState = new DumpState(); 17490 boolean fullPreferred = false; 17491 boolean checkin = false; 17492 17493 String packageName = null; 17494 ArraySet<String> permissionNames = null; 17495 17496 int opti = 0; 17497 while (opti < args.length) { 17498 String opt = args[opti]; 17499 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 17500 break; 17501 } 17502 opti++; 17503 17504 if ("-a".equals(opt)) { 17505 // Right now we only know how to print all. 17506 } else if ("-h".equals(opt)) { 17507 pw.println("Package manager dump options:"); 17508 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 17509 pw.println(" --checkin: dump for a checkin"); 17510 pw.println(" -f: print details of intent filters"); 17511 pw.println(" -h: print this help"); 17512 pw.println(" cmd may be one of:"); 17513 pw.println(" l[ibraries]: list known shared libraries"); 17514 pw.println(" f[eatures]: list device features"); 17515 pw.println(" k[eysets]: print known keysets"); 17516 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 17517 pw.println(" perm[issions]: dump permissions"); 17518 pw.println(" permission [name ...]: dump declaration and use of given permission"); 17519 pw.println(" pref[erred]: print preferred package settings"); 17520 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 17521 pw.println(" prov[iders]: dump content providers"); 17522 pw.println(" p[ackages]: dump installed packages"); 17523 pw.println(" s[hared-users]: dump shared user IDs"); 17524 pw.println(" m[essages]: print collected runtime messages"); 17525 pw.println(" v[erifiers]: print package verifier info"); 17526 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 17527 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 17528 pw.println(" version: print database version info"); 17529 pw.println(" write: write current settings now"); 17530 pw.println(" installs: details about install sessions"); 17531 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 17532 pw.println(" <package.name>: info about given package"); 17533 return; 17534 } else if ("--checkin".equals(opt)) { 17535 checkin = true; 17536 } else if ("-f".equals(opt)) { 17537 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 17538 } else { 17539 pw.println("Unknown argument: " + opt + "; use -h for help"); 17540 } 17541 } 17542 17543 // Is the caller requesting to dump a particular piece of data? 17544 if (opti < args.length) { 17545 String cmd = args[opti]; 17546 opti++; 17547 // Is this a package name? 17548 if ("android".equals(cmd) || cmd.contains(".")) { 17549 packageName = cmd; 17550 // When dumping a single package, we always dump all of its 17551 // filter information since the amount of data will be reasonable. 17552 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 17553 } else if ("check-permission".equals(cmd)) { 17554 if (opti >= args.length) { 17555 pw.println("Error: check-permission missing permission argument"); 17556 return; 17557 } 17558 String perm = args[opti]; 17559 opti++; 17560 if (opti >= args.length) { 17561 pw.println("Error: check-permission missing package argument"); 17562 return; 17563 } 17564 String pkg = args[opti]; 17565 opti++; 17566 int user = UserHandle.getUserId(Binder.getCallingUid()); 17567 if (opti < args.length) { 17568 try { 17569 user = Integer.parseInt(args[opti]); 17570 } catch (NumberFormatException e) { 17571 pw.println("Error: check-permission user argument is not a number: " 17572 + args[opti]); 17573 return; 17574 } 17575 } 17576 pw.println(checkPermission(perm, pkg, user)); 17577 return; 17578 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 17579 dumpState.setDump(DumpState.DUMP_LIBS); 17580 } else if ("f".equals(cmd) || "features".equals(cmd)) { 17581 dumpState.setDump(DumpState.DUMP_FEATURES); 17582 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 17583 if (opti >= args.length) { 17584 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 17585 | DumpState.DUMP_SERVICE_RESOLVERS 17586 | DumpState.DUMP_RECEIVER_RESOLVERS 17587 | DumpState.DUMP_CONTENT_RESOLVERS); 17588 } else { 17589 while (opti < args.length) { 17590 String name = args[opti]; 17591 if ("a".equals(name) || "activity".equals(name)) { 17592 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 17593 } else if ("s".equals(name) || "service".equals(name)) { 17594 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 17595 } else if ("r".equals(name) || "receiver".equals(name)) { 17596 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 17597 } else if ("c".equals(name) || "content".equals(name)) { 17598 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 17599 } else { 17600 pw.println("Error: unknown resolver table type: " + name); 17601 return; 17602 } 17603 opti++; 17604 } 17605 } 17606 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 17607 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 17608 } else if ("permission".equals(cmd)) { 17609 if (opti >= args.length) { 17610 pw.println("Error: permission requires permission name"); 17611 return; 17612 } 17613 permissionNames = new ArraySet<>(); 17614 while (opti < args.length) { 17615 permissionNames.add(args[opti]); 17616 opti++; 17617 } 17618 dumpState.setDump(DumpState.DUMP_PERMISSIONS 17619 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 17620 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 17621 dumpState.setDump(DumpState.DUMP_PREFERRED); 17622 } else if ("preferred-xml".equals(cmd)) { 17623 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 17624 if (opti < args.length && "--full".equals(args[opti])) { 17625 fullPreferred = true; 17626 opti++; 17627 } 17628 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 17629 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 17630 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 17631 dumpState.setDump(DumpState.DUMP_PACKAGES); 17632 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 17633 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 17634 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 17635 dumpState.setDump(DumpState.DUMP_PROVIDERS); 17636 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 17637 dumpState.setDump(DumpState.DUMP_MESSAGES); 17638 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 17639 dumpState.setDump(DumpState.DUMP_VERIFIERS); 17640 } else if ("i".equals(cmd) || "ifv".equals(cmd) 17641 || "intent-filter-verifiers".equals(cmd)) { 17642 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 17643 } else if ("version".equals(cmd)) { 17644 dumpState.setDump(DumpState.DUMP_VERSION); 17645 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 17646 dumpState.setDump(DumpState.DUMP_KEYSETS); 17647 } else if ("installs".equals(cmd)) { 17648 dumpState.setDump(DumpState.DUMP_INSTALLS); 17649 } else if ("frozen".equals(cmd)) { 17650 dumpState.setDump(DumpState.DUMP_FROZEN); 17651 } else if ("write".equals(cmd)) { 17652 synchronized (mPackages) { 17653 mSettings.writeLPr(); 17654 pw.println("Settings written."); 17655 return; 17656 } 17657 } 17658 } 17659 17660 if (checkin) { 17661 pw.println("vers,1"); 17662 } 17663 17664 // reader 17665 synchronized (mPackages) { 17666 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 17667 if (!checkin) { 17668 if (dumpState.onTitlePrinted()) 17669 pw.println(); 17670 pw.println("Database versions:"); 17671 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 17672 } 17673 } 17674 17675 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 17676 if (!checkin) { 17677 if (dumpState.onTitlePrinted()) 17678 pw.println(); 17679 pw.println("Verifiers:"); 17680 pw.print(" Required: "); 17681 pw.print(mRequiredVerifierPackage); 17682 pw.print(" (uid="); 17683 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 17684 UserHandle.USER_SYSTEM)); 17685 pw.println(")"); 17686 } else if (mRequiredVerifierPackage != null) { 17687 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 17688 pw.print(","); 17689 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 17690 UserHandle.USER_SYSTEM)); 17691 } 17692 } 17693 17694 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 17695 packageName == null) { 17696 if (mIntentFilterVerifierComponent != null) { 17697 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 17698 if (!checkin) { 17699 if (dumpState.onTitlePrinted()) 17700 pw.println(); 17701 pw.println("Intent Filter Verifier:"); 17702 pw.print(" Using: "); 17703 pw.print(verifierPackageName); 17704 pw.print(" (uid="); 17705 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 17706 UserHandle.USER_SYSTEM)); 17707 pw.println(")"); 17708 } else if (verifierPackageName != null) { 17709 pw.print("ifv,"); pw.print(verifierPackageName); 17710 pw.print(","); 17711 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 17712 UserHandle.USER_SYSTEM)); 17713 } 17714 } else { 17715 pw.println(); 17716 pw.println("No Intent Filter Verifier available!"); 17717 } 17718 } 17719 17720 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 17721 boolean printedHeader = false; 17722 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 17723 while (it.hasNext()) { 17724 String name = it.next(); 17725 SharedLibraryEntry ent = mSharedLibraries.get(name); 17726 if (!checkin) { 17727 if (!printedHeader) { 17728 if (dumpState.onTitlePrinted()) 17729 pw.println(); 17730 pw.println("Libraries:"); 17731 printedHeader = true; 17732 } 17733 pw.print(" "); 17734 } else { 17735 pw.print("lib,"); 17736 } 17737 pw.print(name); 17738 if (!checkin) { 17739 pw.print(" -> "); 17740 } 17741 if (ent.path != null) { 17742 if (!checkin) { 17743 pw.print("(jar) "); 17744 pw.print(ent.path); 17745 } else { 17746 pw.print(",jar,"); 17747 pw.print(ent.path); 17748 } 17749 } else { 17750 if (!checkin) { 17751 pw.print("(apk) "); 17752 pw.print(ent.apk); 17753 } else { 17754 pw.print(",apk,"); 17755 pw.print(ent.apk); 17756 } 17757 } 17758 pw.println(); 17759 } 17760 } 17761 17762 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 17763 if (dumpState.onTitlePrinted()) 17764 pw.println(); 17765 if (!checkin) { 17766 pw.println("Features:"); 17767 } 17768 17769 for (FeatureInfo feat : mAvailableFeatures.values()) { 17770 if (checkin) { 17771 pw.print("feat,"); 17772 pw.print(feat.name); 17773 pw.print(","); 17774 pw.println(feat.version); 17775 } else { 17776 pw.print(" "); 17777 pw.print(feat.name); 17778 if (feat.version > 0) { 17779 pw.print(" version="); 17780 pw.print(feat.version); 17781 } 17782 pw.println(); 17783 } 17784 } 17785 } 17786 17787 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 17788 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 17789 : "Activity Resolver Table:", " ", packageName, 17790 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17791 dumpState.setTitlePrinted(true); 17792 } 17793 } 17794 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 17795 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 17796 : "Receiver Resolver Table:", " ", packageName, 17797 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17798 dumpState.setTitlePrinted(true); 17799 } 17800 } 17801 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 17802 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 17803 : "Service Resolver Table:", " ", packageName, 17804 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17805 dumpState.setTitlePrinted(true); 17806 } 17807 } 17808 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 17809 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 17810 : "Provider Resolver Table:", " ", packageName, 17811 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17812 dumpState.setTitlePrinted(true); 17813 } 17814 } 17815 17816 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 17817 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17818 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17819 int user = mSettings.mPreferredActivities.keyAt(i); 17820 if (pir.dump(pw, 17821 dumpState.getTitlePrinted() 17822 ? "\nPreferred Activities User " + user + ":" 17823 : "Preferred Activities User " + user + ":", " ", 17824 packageName, true, false)) { 17825 dumpState.setTitlePrinted(true); 17826 } 17827 } 17828 } 17829 17830 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 17831 pw.flush(); 17832 FileOutputStream fout = new FileOutputStream(fd); 17833 BufferedOutputStream str = new BufferedOutputStream(fout); 17834 XmlSerializer serializer = new FastXmlSerializer(); 17835 try { 17836 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 17837 serializer.startDocument(null, true); 17838 serializer.setFeature( 17839 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 17840 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 17841 serializer.endDocument(); 17842 serializer.flush(); 17843 } catch (IllegalArgumentException e) { 17844 pw.println("Failed writing: " + e); 17845 } catch (IllegalStateException e) { 17846 pw.println("Failed writing: " + e); 17847 } catch (IOException e) { 17848 pw.println("Failed writing: " + e); 17849 } 17850 } 17851 17852 if (!checkin 17853 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 17854 && packageName == null) { 17855 pw.println(); 17856 int count = mSettings.mPackages.size(); 17857 if (count == 0) { 17858 pw.println("No applications!"); 17859 pw.println(); 17860 } else { 17861 final String prefix = " "; 17862 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 17863 if (allPackageSettings.size() == 0) { 17864 pw.println("No domain preferred apps!"); 17865 pw.println(); 17866 } else { 17867 pw.println("App verification status:"); 17868 pw.println(); 17869 count = 0; 17870 for (PackageSetting ps : allPackageSettings) { 17871 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 17872 if (ivi == null || ivi.getPackageName() == null) continue; 17873 pw.println(prefix + "Package: " + ivi.getPackageName()); 17874 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 17875 pw.println(prefix + "Status: " + ivi.getStatusString()); 17876 pw.println(); 17877 count++; 17878 } 17879 if (count == 0) { 17880 pw.println(prefix + "No app verification established."); 17881 pw.println(); 17882 } 17883 for (int userId : sUserManager.getUserIds()) { 17884 pw.println("App linkages for user " + userId + ":"); 17885 pw.println(); 17886 count = 0; 17887 for (PackageSetting ps : allPackageSettings) { 17888 final long status = ps.getDomainVerificationStatusForUser(userId); 17889 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 17890 continue; 17891 } 17892 pw.println(prefix + "Package: " + ps.name); 17893 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 17894 String statusStr = IntentFilterVerificationInfo. 17895 getStatusStringFromValue(status); 17896 pw.println(prefix + "Status: " + statusStr); 17897 pw.println(); 17898 count++; 17899 } 17900 if (count == 0) { 17901 pw.println(prefix + "No configured app linkages."); 17902 pw.println(); 17903 } 17904 } 17905 } 17906 } 17907 } 17908 17909 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 17910 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 17911 if (packageName == null && permissionNames == null) { 17912 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 17913 if (iperm == 0) { 17914 if (dumpState.onTitlePrinted()) 17915 pw.println(); 17916 pw.println("AppOp Permissions:"); 17917 } 17918 pw.print(" AppOp Permission "); 17919 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 17920 pw.println(":"); 17921 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 17922 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 17923 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 17924 } 17925 } 17926 } 17927 } 17928 17929 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 17930 boolean printedSomething = false; 17931 for (PackageParser.Provider p : mProviders.mProviders.values()) { 17932 if (packageName != null && !packageName.equals(p.info.packageName)) { 17933 continue; 17934 } 17935 if (!printedSomething) { 17936 if (dumpState.onTitlePrinted()) 17937 pw.println(); 17938 pw.println("Registered ContentProviders:"); 17939 printedSomething = true; 17940 } 17941 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 17942 pw.print(" "); pw.println(p.toString()); 17943 } 17944 printedSomething = false; 17945 for (Map.Entry<String, PackageParser.Provider> entry : 17946 mProvidersByAuthority.entrySet()) { 17947 PackageParser.Provider p = entry.getValue(); 17948 if (packageName != null && !packageName.equals(p.info.packageName)) { 17949 continue; 17950 } 17951 if (!printedSomething) { 17952 if (dumpState.onTitlePrinted()) 17953 pw.println(); 17954 pw.println("ContentProvider Authorities:"); 17955 printedSomething = true; 17956 } 17957 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 17958 pw.print(" "); pw.println(p.toString()); 17959 if (p.info != null && p.info.applicationInfo != null) { 17960 final String appInfo = p.info.applicationInfo.toString(); 17961 pw.print(" applicationInfo="); pw.println(appInfo); 17962 } 17963 } 17964 } 17965 17966 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 17967 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 17968 } 17969 17970 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 17971 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 17972 } 17973 17974 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 17975 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 17976 } 17977 17978 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 17979 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 17980 } 17981 17982 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 17983 // XXX should handle packageName != null by dumping only install data that 17984 // the given package is involved with. 17985 if (dumpState.onTitlePrinted()) pw.println(); 17986 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 17987 } 17988 17989 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 17990 // XXX should handle packageName != null by dumping only install data that 17991 // the given package is involved with. 17992 if (dumpState.onTitlePrinted()) pw.println(); 17993 17994 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 17995 ipw.println(); 17996 ipw.println("Frozen packages:"); 17997 ipw.increaseIndent(); 17998 if (mFrozenPackages.size() == 0) { 17999 ipw.println("(none)"); 18000 } else { 18001 for (int i = 0; i < mFrozenPackages.size(); i++) { 18002 ipw.println(mFrozenPackages.valueAt(i)); 18003 } 18004 } 18005 ipw.decreaseIndent(); 18006 } 18007 18008 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 18009 if (dumpState.onTitlePrinted()) pw.println(); 18010 mSettings.dumpReadMessagesLPr(pw, dumpState); 18011 18012 pw.println(); 18013 pw.println("Package warning messages:"); 18014 BufferedReader in = null; 18015 String line = null; 18016 try { 18017 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18018 while ((line = in.readLine()) != null) { 18019 if (line.contains("ignored: updated version")) continue; 18020 pw.println(line); 18021 } 18022 } catch (IOException ignored) { 18023 } finally { 18024 IoUtils.closeQuietly(in); 18025 } 18026 } 18027 18028 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 18029 BufferedReader in = null; 18030 String line = null; 18031 try { 18032 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18033 while ((line = in.readLine()) != null) { 18034 if (line.contains("ignored: updated version")) continue; 18035 pw.print("msg,"); 18036 pw.println(line); 18037 } 18038 } catch (IOException ignored) { 18039 } finally { 18040 IoUtils.closeQuietly(in); 18041 } 18042 } 18043 } 18044 } 18045 18046 private String dumpDomainString(String packageName) { 18047 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 18048 .getList(); 18049 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 18050 18051 ArraySet<String> result = new ArraySet<>(); 18052 if (iviList.size() > 0) { 18053 for (IntentFilterVerificationInfo ivi : iviList) { 18054 for (String host : ivi.getDomains()) { 18055 result.add(host); 18056 } 18057 } 18058 } 18059 if (filters != null && filters.size() > 0) { 18060 for (IntentFilter filter : filters) { 18061 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 18062 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 18063 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 18064 result.addAll(filter.getHostsList()); 18065 } 18066 } 18067 } 18068 18069 StringBuilder sb = new StringBuilder(result.size() * 16); 18070 for (String domain : result) { 18071 if (sb.length() > 0) sb.append(" "); 18072 sb.append(domain); 18073 } 18074 return sb.toString(); 18075 } 18076 18077 // ------- apps on sdcard specific code ------- 18078 static final boolean DEBUG_SD_INSTALL = false; 18079 18080 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 18081 18082 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 18083 18084 private boolean mMediaMounted = false; 18085 18086 static String getEncryptKey() { 18087 try { 18088 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 18089 SD_ENCRYPTION_KEYSTORE_NAME); 18090 if (sdEncKey == null) { 18091 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 18092 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 18093 if (sdEncKey == null) { 18094 Slog.e(TAG, "Failed to create encryption keys"); 18095 return null; 18096 } 18097 } 18098 return sdEncKey; 18099 } catch (NoSuchAlgorithmException nsae) { 18100 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 18101 return null; 18102 } catch (IOException ioe) { 18103 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 18104 return null; 18105 } 18106 } 18107 18108 /* 18109 * Update media status on PackageManager. 18110 */ 18111 @Override 18112 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 18113 int callingUid = Binder.getCallingUid(); 18114 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 18115 throw new SecurityException("Media status can only be updated by the system"); 18116 } 18117 // reader; this apparently protects mMediaMounted, but should probably 18118 // be a different lock in that case. 18119 synchronized (mPackages) { 18120 Log.i(TAG, "Updating external media status from " 18121 + (mMediaMounted ? "mounted" : "unmounted") + " to " 18122 + (mediaStatus ? "mounted" : "unmounted")); 18123 if (DEBUG_SD_INSTALL) 18124 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 18125 + ", mMediaMounted=" + mMediaMounted); 18126 if (mediaStatus == mMediaMounted) { 18127 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 18128 : 0, -1); 18129 mHandler.sendMessage(msg); 18130 return; 18131 } 18132 mMediaMounted = mediaStatus; 18133 } 18134 // Queue up an async operation since the package installation may take a 18135 // little while. 18136 mHandler.post(new Runnable() { 18137 public void run() { 18138 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 18139 } 18140 }); 18141 } 18142 18143 /** 18144 * Called by MountService when the initial ASECs to scan are available. 18145 * Should block until all the ASEC containers are finished being scanned. 18146 */ 18147 public void scanAvailableAsecs() { 18148 updateExternalMediaStatusInner(true, false, false); 18149 } 18150 18151 /* 18152 * Collect information of applications on external media, map them against 18153 * existing containers and update information based on current mount status. 18154 * Please note that we always have to report status if reportStatus has been 18155 * set to true especially when unloading packages. 18156 */ 18157 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 18158 boolean externalStorage) { 18159 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 18160 int[] uidArr = EmptyArray.INT; 18161 18162 final String[] list = PackageHelper.getSecureContainerList(); 18163 if (ArrayUtils.isEmpty(list)) { 18164 Log.i(TAG, "No secure containers found"); 18165 } else { 18166 // Process list of secure containers and categorize them 18167 // as active or stale based on their package internal state. 18168 18169 // reader 18170 synchronized (mPackages) { 18171 for (String cid : list) { 18172 // Leave stages untouched for now; installer service owns them 18173 if (PackageInstallerService.isStageName(cid)) continue; 18174 18175 if (DEBUG_SD_INSTALL) 18176 Log.i(TAG, "Processing container " + cid); 18177 String pkgName = getAsecPackageName(cid); 18178 if (pkgName == null) { 18179 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 18180 continue; 18181 } 18182 if (DEBUG_SD_INSTALL) 18183 Log.i(TAG, "Looking for pkg : " + pkgName); 18184 18185 final PackageSetting ps = mSettings.mPackages.get(pkgName); 18186 if (ps == null) { 18187 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 18188 continue; 18189 } 18190 18191 /* 18192 * Skip packages that are not external if we're unmounting 18193 * external storage. 18194 */ 18195 if (externalStorage && !isMounted && !isExternal(ps)) { 18196 continue; 18197 } 18198 18199 final AsecInstallArgs args = new AsecInstallArgs(cid, 18200 getAppDexInstructionSets(ps), ps.isForwardLocked()); 18201 // The package status is changed only if the code path 18202 // matches between settings and the container id. 18203 if (ps.codePathString != null 18204 && ps.codePathString.startsWith(args.getCodePath())) { 18205 if (DEBUG_SD_INSTALL) { 18206 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 18207 + " at code path: " + ps.codePathString); 18208 } 18209 18210 // We do have a valid package installed on sdcard 18211 processCids.put(args, ps.codePathString); 18212 final int uid = ps.appId; 18213 if (uid != -1) { 18214 uidArr = ArrayUtils.appendInt(uidArr, uid); 18215 } 18216 } else { 18217 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 18218 + ps.codePathString); 18219 } 18220 } 18221 } 18222 18223 Arrays.sort(uidArr); 18224 } 18225 18226 // Process packages with valid entries. 18227 if (isMounted) { 18228 if (DEBUG_SD_INSTALL) 18229 Log.i(TAG, "Loading packages"); 18230 loadMediaPackages(processCids, uidArr, externalStorage); 18231 startCleaningPackages(); 18232 mInstallerService.onSecureContainersAvailable(); 18233 } else { 18234 if (DEBUG_SD_INSTALL) 18235 Log.i(TAG, "Unloading packages"); 18236 unloadMediaPackages(processCids, uidArr, reportStatus); 18237 } 18238 } 18239 18240 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18241 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 18242 final int size = infos.size(); 18243 final String[] packageNames = new String[size]; 18244 final int[] packageUids = new int[size]; 18245 for (int i = 0; i < size; i++) { 18246 final ApplicationInfo info = infos.get(i); 18247 packageNames[i] = info.packageName; 18248 packageUids[i] = info.uid; 18249 } 18250 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 18251 finishedReceiver); 18252 } 18253 18254 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18255 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18256 sendResourcesChangedBroadcast(mediaStatus, replacing, 18257 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 18258 } 18259 18260 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18261 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18262 int size = pkgList.length; 18263 if (size > 0) { 18264 // Send broadcasts here 18265 Bundle extras = new Bundle(); 18266 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 18267 if (uidArr != null) { 18268 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 18269 } 18270 if (replacing) { 18271 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 18272 } 18273 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 18274 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 18275 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 18276 } 18277 } 18278 18279 /* 18280 * Look at potentially valid container ids from processCids If package 18281 * information doesn't match the one on record or package scanning fails, 18282 * the cid is added to list of removeCids. We currently don't delete stale 18283 * containers. 18284 */ 18285 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 18286 boolean externalStorage) { 18287 ArrayList<String> pkgList = new ArrayList<String>(); 18288 Set<AsecInstallArgs> keys = processCids.keySet(); 18289 18290 for (AsecInstallArgs args : keys) { 18291 String codePath = processCids.get(args); 18292 if (DEBUG_SD_INSTALL) 18293 Log.i(TAG, "Loading container : " + args.cid); 18294 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 18295 try { 18296 // Make sure there are no container errors first. 18297 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 18298 Slog.e(TAG, "Failed to mount cid : " + args.cid 18299 + " when installing from sdcard"); 18300 continue; 18301 } 18302 // Check code path here. 18303 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 18304 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 18305 + " does not match one in settings " + codePath); 18306 continue; 18307 } 18308 // Parse package 18309 int parseFlags = mDefParseFlags; 18310 if (args.isExternalAsec()) { 18311 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 18312 } 18313 if (args.isFwdLocked()) { 18314 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 18315 } 18316 18317 synchronized (mInstallLock) { 18318 PackageParser.Package pkg = null; 18319 try { 18320 // Sadly we don't know the package name yet to freeze it 18321 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 18322 SCAN_IGNORE_FROZEN, 0, null); 18323 } catch (PackageManagerException e) { 18324 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 18325 } 18326 // Scan the package 18327 if (pkg != null) { 18328 /* 18329 * TODO why is the lock being held? doPostInstall is 18330 * called in other places without the lock. This needs 18331 * to be straightened out. 18332 */ 18333 // writer 18334 synchronized (mPackages) { 18335 retCode = PackageManager.INSTALL_SUCCEEDED; 18336 pkgList.add(pkg.packageName); 18337 // Post process args 18338 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 18339 pkg.applicationInfo.uid); 18340 } 18341 } else { 18342 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 18343 } 18344 } 18345 18346 } finally { 18347 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 18348 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 18349 } 18350 } 18351 } 18352 // writer 18353 synchronized (mPackages) { 18354 // If the platform SDK has changed since the last time we booted, 18355 // we need to re-grant app permission to catch any new ones that 18356 // appear. This is really a hack, and means that apps can in some 18357 // cases get permissions that the user didn't initially explicitly 18358 // allow... it would be nice to have some better way to handle 18359 // this situation. 18360 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 18361 : mSettings.getInternalVersion(); 18362 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 18363 : StorageManager.UUID_PRIVATE_INTERNAL; 18364 18365 int updateFlags = UPDATE_PERMISSIONS_ALL; 18366 if (ver.sdkVersion != mSdkVersion) { 18367 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 18368 + mSdkVersion + "; regranting permissions for external"); 18369 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 18370 } 18371 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 18372 18373 // Yay, everything is now upgraded 18374 ver.forceCurrent(); 18375 18376 // can downgrade to reader 18377 // Persist settings 18378 mSettings.writeLPr(); 18379 } 18380 // Send a broadcast to let everyone know we are done processing 18381 if (pkgList.size() > 0) { 18382 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 18383 } 18384 } 18385 18386 /* 18387 * Utility method to unload a list of specified containers 18388 */ 18389 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 18390 // Just unmount all valid containers. 18391 for (AsecInstallArgs arg : cidArgs) { 18392 synchronized (mInstallLock) { 18393 arg.doPostDeleteLI(false); 18394 } 18395 } 18396 } 18397 18398 /* 18399 * Unload packages mounted on external media. This involves deleting package 18400 * data from internal structures, sending broadcasts about disabled packages, 18401 * gc'ing to free up references, unmounting all secure containers 18402 * corresponding to packages on external media, and posting a 18403 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 18404 * that we always have to post this message if status has been requested no 18405 * matter what. 18406 */ 18407 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 18408 final boolean reportStatus) { 18409 if (DEBUG_SD_INSTALL) 18410 Log.i(TAG, "unloading media packages"); 18411 ArrayList<String> pkgList = new ArrayList<String>(); 18412 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 18413 final Set<AsecInstallArgs> keys = processCids.keySet(); 18414 for (AsecInstallArgs args : keys) { 18415 String pkgName = args.getPackageName(); 18416 if (DEBUG_SD_INSTALL) 18417 Log.i(TAG, "Trying to unload pkg : " + pkgName); 18418 // Delete package internally 18419 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 18420 synchronized (mInstallLock) { 18421 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 18422 final boolean res; 18423 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 18424 "unloadMediaPackages")) { 18425 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 18426 null); 18427 } 18428 if (res) { 18429 pkgList.add(pkgName); 18430 } else { 18431 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 18432 failedList.add(args); 18433 } 18434 } 18435 } 18436 18437 // reader 18438 synchronized (mPackages) { 18439 // We didn't update the settings after removing each package; 18440 // write them now for all packages. 18441 mSettings.writeLPr(); 18442 } 18443 18444 // We have to absolutely send UPDATED_MEDIA_STATUS only 18445 // after confirming that all the receivers processed the ordered 18446 // broadcast when packages get disabled, force a gc to clean things up. 18447 // and unload all the containers. 18448 if (pkgList.size() > 0) { 18449 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 18450 new IIntentReceiver.Stub() { 18451 public void performReceive(Intent intent, int resultCode, String data, 18452 Bundle extras, boolean ordered, boolean sticky, 18453 int sendingUser) throws RemoteException { 18454 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 18455 reportStatus ? 1 : 0, 1, keys); 18456 mHandler.sendMessage(msg); 18457 } 18458 }); 18459 } else { 18460 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 18461 keys); 18462 mHandler.sendMessage(msg); 18463 } 18464 } 18465 18466 private void loadPrivatePackages(final VolumeInfo vol) { 18467 mHandler.post(new Runnable() { 18468 @Override 18469 public void run() { 18470 loadPrivatePackagesInner(vol); 18471 } 18472 }); 18473 } 18474 18475 private void loadPrivatePackagesInner(VolumeInfo vol) { 18476 final String volumeUuid = vol.fsUuid; 18477 if (TextUtils.isEmpty(volumeUuid)) { 18478 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 18479 return; 18480 } 18481 18482 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 18483 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 18484 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 18485 18486 final VersionInfo ver; 18487 final List<PackageSetting> packages; 18488 synchronized (mPackages) { 18489 ver = mSettings.findOrCreateVersion(volumeUuid); 18490 packages = mSettings.getVolumePackagesLPr(volumeUuid); 18491 } 18492 18493 for (PackageSetting ps : packages) { 18494 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 18495 synchronized (mInstallLock) { 18496 final PackageParser.Package pkg; 18497 try { 18498 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 18499 loaded.add(pkg.applicationInfo); 18500 18501 } catch (PackageManagerException e) { 18502 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 18503 } 18504 18505 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 18506 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 18507 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 18508 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 18509 } 18510 } 18511 } 18512 18513 // Reconcile app data for all started/unlocked users 18514 final StorageManager sm = mContext.getSystemService(StorageManager.class); 18515 final UserManager um = mContext.getSystemService(UserManager.class); 18516 for (UserInfo user : um.getUsers()) { 18517 final int flags; 18518 if (um.isUserUnlocked(user.id)) { 18519 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18520 } else if (um.isUserRunning(user.id)) { 18521 flags = StorageManager.FLAG_STORAGE_DE; 18522 } else { 18523 continue; 18524 } 18525 18526 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 18527 synchronized (mInstallLock) { 18528 reconcileAppsDataLI(volumeUuid, user.id, flags); 18529 } 18530 } 18531 18532 synchronized (mPackages) { 18533 int updateFlags = UPDATE_PERMISSIONS_ALL; 18534 if (ver.sdkVersion != mSdkVersion) { 18535 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 18536 + mSdkVersion + "; regranting permissions for " + volumeUuid); 18537 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 18538 } 18539 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 18540 18541 // Yay, everything is now upgraded 18542 ver.forceCurrent(); 18543 18544 mSettings.writeLPr(); 18545 } 18546 18547 for (PackageFreezer freezer : freezers) { 18548 freezer.close(); 18549 } 18550 18551 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 18552 sendResourcesChangedBroadcast(true, false, loaded, null); 18553 } 18554 18555 private void unloadPrivatePackages(final VolumeInfo vol) { 18556 mHandler.post(new Runnable() { 18557 @Override 18558 public void run() { 18559 unloadPrivatePackagesInner(vol); 18560 } 18561 }); 18562 } 18563 18564 private void unloadPrivatePackagesInner(VolumeInfo vol) { 18565 final String volumeUuid = vol.fsUuid; 18566 if (TextUtils.isEmpty(volumeUuid)) { 18567 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 18568 return; 18569 } 18570 18571 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 18572 synchronized (mInstallLock) { 18573 synchronized (mPackages) { 18574 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 18575 for (PackageSetting ps : packages) { 18576 if (ps.pkg == null) continue; 18577 18578 final ApplicationInfo info = ps.pkg.applicationInfo; 18579 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 18580 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 18581 18582 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 18583 "unloadPrivatePackagesInner")) { 18584 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 18585 false, null)) { 18586 unloaded.add(info); 18587 } else { 18588 Slog.w(TAG, "Failed to unload " + ps.codePath); 18589 } 18590 } 18591 } 18592 18593 mSettings.writeLPr(); 18594 } 18595 } 18596 18597 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 18598 sendResourcesChangedBroadcast(false, false, unloaded, null); 18599 } 18600 18601 /** 18602 * Examine all users present on given mounted volume, and destroy data 18603 * belonging to users that are no longer valid, or whose user ID has been 18604 * recycled. 18605 */ 18606 private void reconcileUsers(String volumeUuid) { 18607 // TODO: also reconcile DE directories 18608 final File[] files = FileUtils 18609 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)); 18610 for (File file : files) { 18611 if (!file.isDirectory()) continue; 18612 18613 final int userId; 18614 final UserInfo info; 18615 try { 18616 userId = Integer.parseInt(file.getName()); 18617 info = sUserManager.getUserInfo(userId); 18618 } catch (NumberFormatException e) { 18619 Slog.w(TAG, "Invalid user directory " + file); 18620 continue; 18621 } 18622 18623 boolean destroyUser = false; 18624 if (info == null) { 18625 logCriticalInfo(Log.WARN, "Destroying user directory " + file 18626 + " because no matching user was found"); 18627 destroyUser = true; 18628 } else { 18629 try { 18630 UserManagerService.enforceSerialNumber(file, info.serialNumber); 18631 } catch (IOException e) { 18632 logCriticalInfo(Log.WARN, "Destroying user directory " + file 18633 + " because we failed to enforce serial number: " + e); 18634 destroyUser = true; 18635 } 18636 } 18637 18638 if (destroyUser) { 18639 synchronized (mInstallLock) { 18640 try { 18641 mInstaller.removeUserDataDirs(volumeUuid, userId); 18642 } catch (InstallerException e) { 18643 Slog.w(TAG, "Failed to clean up user dirs", e); 18644 } 18645 } 18646 } 18647 } 18648 } 18649 18650 private void assertPackageKnown(String volumeUuid, String packageName) 18651 throws PackageManagerException { 18652 synchronized (mPackages) { 18653 final PackageSetting ps = mSettings.mPackages.get(packageName); 18654 if (ps == null) { 18655 throw new PackageManagerException("Package " + packageName + " is unknown"); 18656 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 18657 throw new PackageManagerException( 18658 "Package " + packageName + " found on unknown volume " + volumeUuid 18659 + "; expected volume " + ps.volumeUuid); 18660 } 18661 } 18662 } 18663 18664 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 18665 throws PackageManagerException { 18666 synchronized (mPackages) { 18667 final PackageSetting ps = mSettings.mPackages.get(packageName); 18668 if (ps == null) { 18669 throw new PackageManagerException("Package " + packageName + " is unknown"); 18670 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 18671 throw new PackageManagerException( 18672 "Package " + packageName + " found on unknown volume " + volumeUuid 18673 + "; expected volume " + ps.volumeUuid); 18674 } else if (!ps.getInstalled(userId)) { 18675 throw new PackageManagerException( 18676 "Package " + packageName + " not installed for user " + userId); 18677 } 18678 } 18679 } 18680 18681 /** 18682 * Examine all apps present on given mounted volume, and destroy apps that 18683 * aren't expected, either due to uninstallation or reinstallation on 18684 * another volume. 18685 */ 18686 private void reconcileApps(String volumeUuid) { 18687 final File[] files = FileUtils 18688 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 18689 for (File file : files) { 18690 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 18691 && !PackageInstallerService.isStageName(file.getName()); 18692 if (!isPackage) { 18693 // Ignore entries which are not packages 18694 continue; 18695 } 18696 18697 try { 18698 final PackageLite pkg = PackageParser.parsePackageLite(file, 18699 PackageParser.PARSE_MUST_BE_APK); 18700 assertPackageKnown(volumeUuid, pkg.packageName); 18701 18702 } catch (PackageParserException | PackageManagerException e) { 18703 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 18704 synchronized (mInstallLock) { 18705 removeCodePathLI(file); 18706 } 18707 } 18708 } 18709 } 18710 18711 /** 18712 * Reconcile all app data for the given user. 18713 * <p> 18714 * Verifies that directories exist and that ownership and labeling is 18715 * correct for all installed apps on all mounted volumes. 18716 */ 18717 void reconcileAppsData(int userId, int flags) { 18718 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18719 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 18720 final String volumeUuid = vol.getFsUuid(); 18721 synchronized (mInstallLock) { 18722 reconcileAppsDataLI(volumeUuid, userId, flags); 18723 } 18724 } 18725 } 18726 18727 /** 18728 * Reconcile all app data on given mounted volume. 18729 * <p> 18730 * Destroys app data that isn't expected, either due to uninstallation or 18731 * reinstallation on another volume. 18732 * <p> 18733 * Verifies that directories exist and that ownership and labeling is 18734 * correct for all installed apps. 18735 */ 18736 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) { 18737 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 18738 + Integer.toHexString(flags)); 18739 18740 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 18741 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 18742 18743 boolean restoreconNeeded = false; 18744 18745 // First look for stale data that doesn't belong, and check if things 18746 // have changed since we did our last restorecon 18747 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18748 if (!isUserKeyUnlocked(userId)) { 18749 throw new RuntimeException( 18750 "Yikes, someone asked us to reconcile CE storage while " + userId 18751 + " was still locked; this would have caused massive data loss!"); 18752 } 18753 18754 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 18755 18756 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 18757 for (File file : files) { 18758 final String packageName = file.getName(); 18759 try { 18760 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 18761 } catch (PackageManagerException e) { 18762 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 18763 try { 18764 mInstaller.destroyAppData(volumeUuid, packageName, userId, 18765 StorageManager.FLAG_STORAGE_CE, 0); 18766 } catch (InstallerException e2) { 18767 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 18768 } 18769 } 18770 } 18771 } 18772 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 18773 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 18774 18775 final File[] files = FileUtils.listFilesOrEmpty(deDir); 18776 for (File file : files) { 18777 final String packageName = file.getName(); 18778 try { 18779 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 18780 } catch (PackageManagerException e) { 18781 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 18782 try { 18783 mInstaller.destroyAppData(volumeUuid, packageName, userId, 18784 StorageManager.FLAG_STORAGE_DE, 0); 18785 } catch (InstallerException e2) { 18786 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 18787 } 18788 } 18789 } 18790 } 18791 18792 // Ensure that data directories are ready to roll for all packages 18793 // installed for this volume and user 18794 final List<PackageSetting> packages; 18795 synchronized (mPackages) { 18796 packages = mSettings.getVolumePackagesLPr(volumeUuid); 18797 } 18798 int preparedCount = 0; 18799 for (PackageSetting ps : packages) { 18800 final String packageName = ps.name; 18801 if (ps.pkg == null) { 18802 Slog.w(TAG, "Odd, missing scanned package " + packageName); 18803 // TODO: might be due to legacy ASEC apps; we should circle back 18804 // and reconcile again once they're scanned 18805 continue; 18806 } 18807 18808 if (ps.getInstalled(userId)) { 18809 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 18810 18811 if (maybeMigrateAppDataLIF(ps.pkg, userId)) { 18812 // We may have just shuffled around app data directories, so 18813 // prepare them one more time 18814 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 18815 } 18816 18817 preparedCount++; 18818 } 18819 } 18820 18821 if (restoreconNeeded) { 18822 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18823 SELinuxMMAC.setRestoreconDone(ceDir); 18824 } 18825 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 18826 SELinuxMMAC.setRestoreconDone(deDir); 18827 } 18828 } 18829 18830 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 18831 + " packages; restoreconNeeded was " + restoreconNeeded); 18832 } 18833 18834 /** 18835 * Prepare app data for the given app just after it was installed or 18836 * upgraded. This method carefully only touches users that it's installed 18837 * for, and it forces a restorecon to handle any seinfo changes. 18838 * <p> 18839 * Verifies that directories exist and that ownership and labeling is 18840 * correct for all installed apps. If there is an ownership mismatch, it 18841 * will try recovering system apps by wiping data; third-party app data is 18842 * left intact. 18843 * <p> 18844 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 18845 */ 18846 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 18847 final PackageSetting ps; 18848 synchronized (mPackages) { 18849 ps = mSettings.mPackages.get(pkg.packageName); 18850 mSettings.writeKernelMappingLPr(ps); 18851 } 18852 18853 final UserManager um = mContext.getSystemService(UserManager.class); 18854 for (UserInfo user : um.getUsers()) { 18855 final int flags; 18856 if (um.isUserUnlocked(user.id)) { 18857 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18858 } else if (um.isUserRunning(user.id)) { 18859 flags = StorageManager.FLAG_STORAGE_DE; 18860 } else { 18861 continue; 18862 } 18863 18864 if (ps.getInstalled(user.id)) { 18865 // Whenever an app changes, force a restorecon of its data 18866 // TODO: when user data is locked, mark that we're still dirty 18867 prepareAppDataLIF(pkg, user.id, flags, true); 18868 } 18869 } 18870 } 18871 18872 /** 18873 * Prepare app data for the given app. 18874 * <p> 18875 * Verifies that directories exist and that ownership and labeling is 18876 * correct for all installed apps. If there is an ownership mismatch, this 18877 * will try recovering system apps by wiping data; third-party app data is 18878 * left intact. 18879 */ 18880 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags, 18881 boolean restoreconNeeded) { 18882 if (pkg == null) { 18883 Slog.wtf(TAG, "Package was null!", new Throwable()); 18884 return; 18885 } 18886 prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded); 18887 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 18888 for (int i = 0; i < childCount; i++) { 18889 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded); 18890 } 18891 } 18892 18893 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags, 18894 boolean restoreconNeeded) { 18895 if (DEBUG_APP_DATA) { 18896 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 18897 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 18898 } 18899 18900 final String volumeUuid = pkg.volumeUuid; 18901 final String packageName = pkg.packageName; 18902 final ApplicationInfo app = pkg.applicationInfo; 18903 final int appId = UserHandle.getAppId(app.uid); 18904 18905 Preconditions.checkNotNull(app.seinfo); 18906 18907 try { 18908 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 18909 appId, app.seinfo, app.targetSdkVersion); 18910 } catch (InstallerException e) { 18911 if (app.isSystemApp()) { 18912 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 18913 + ", but trying to recover: " + e); 18914 destroyAppDataLeafLIF(pkg, userId, flags); 18915 try { 18916 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 18917 appId, app.seinfo, app.targetSdkVersion); 18918 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 18919 } catch (InstallerException e2) { 18920 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 18921 } 18922 } else { 18923 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 18924 } 18925 } 18926 18927 if (restoreconNeeded) { 18928 try { 18929 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, 18930 app.seinfo); 18931 } catch (InstallerException e) { 18932 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 18933 } 18934 } 18935 18936 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18937 try { 18938 // CE storage is unlocked right now, so read out the inode and 18939 // remember for use later when it's locked 18940 // TODO: mark this structure as dirty so we persist it! 18941 final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId, 18942 StorageManager.FLAG_STORAGE_CE); 18943 synchronized (mPackages) { 18944 final PackageSetting ps = mSettings.mPackages.get(packageName); 18945 if (ps != null) { 18946 ps.setCeDataInode(ceDataInode, userId); 18947 } 18948 } 18949 } catch (InstallerException e) { 18950 Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e); 18951 } 18952 } 18953 18954 prepareAppDataContentsLeafLIF(pkg, userId, flags); 18955 } 18956 18957 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 18958 if (pkg == null) { 18959 Slog.wtf(TAG, "Package was null!", new Throwable()); 18960 return; 18961 } 18962 prepareAppDataContentsLeafLIF(pkg, userId, flags); 18963 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 18964 for (int i = 0; i < childCount; i++) { 18965 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 18966 } 18967 } 18968 18969 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 18970 final String volumeUuid = pkg.volumeUuid; 18971 final String packageName = pkg.packageName; 18972 final ApplicationInfo app = pkg.applicationInfo; 18973 18974 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18975 // Create a native library symlink only if we have native libraries 18976 // and if the native libraries are 32 bit libraries. We do not provide 18977 // this symlink for 64 bit libraries. 18978 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 18979 final String nativeLibPath = app.nativeLibraryDir; 18980 try { 18981 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 18982 nativeLibPath, userId); 18983 } catch (InstallerException e) { 18984 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 18985 } 18986 } 18987 } 18988 } 18989 18990 /** 18991 * For system apps on non-FBE devices, this method migrates any existing 18992 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 18993 * requested by the app. 18994 */ 18995 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 18996 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 18997 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 18998 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 18999 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 19000 try { 19001 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 19002 storageTarget); 19003 } catch (InstallerException e) { 19004 logCriticalInfo(Log.WARN, 19005 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 19006 } 19007 return true; 19008 } else { 19009 return false; 19010 } 19011 } 19012 19013 public PackageFreezer freezePackage(String packageName, String killReason) { 19014 return new PackageFreezer(packageName, killReason); 19015 } 19016 19017 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 19018 String killReason) { 19019 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 19020 return new PackageFreezer(); 19021 } else { 19022 return freezePackage(packageName, killReason); 19023 } 19024 } 19025 19026 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 19027 String killReason) { 19028 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 19029 return new PackageFreezer(); 19030 } else { 19031 return freezePackage(packageName, killReason); 19032 } 19033 } 19034 19035 /** 19036 * Class that freezes and kills the given package upon creation, and 19037 * unfreezes it upon closing. This is typically used when doing surgery on 19038 * app code/data to prevent the app from running while you're working. 19039 */ 19040 private class PackageFreezer implements AutoCloseable { 19041 private final String mPackageName; 19042 private final PackageFreezer[] mChildren; 19043 19044 private final boolean mWeFroze; 19045 19046 private final AtomicBoolean mClosed = new AtomicBoolean(); 19047 private final CloseGuard mCloseGuard = CloseGuard.get(); 19048 19049 /** 19050 * Create and return a stub freezer that doesn't actually do anything, 19051 * typically used when someone requested 19052 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 19053 * {@link PackageManager#DELETE_DONT_KILL_APP}. 19054 */ 19055 public PackageFreezer() { 19056 mPackageName = null; 19057 mChildren = null; 19058 mWeFroze = false; 19059 mCloseGuard.open("close"); 19060 } 19061 19062 public PackageFreezer(String packageName, String killReason) { 19063 synchronized (mPackages) { 19064 mPackageName = packageName; 19065 mWeFroze = mFrozenPackages.add(mPackageName); 19066 19067 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 19068 if (ps != null) { 19069 killApplication(ps.name, ps.appId, killReason); 19070 } 19071 19072 final PackageParser.Package p = mPackages.get(packageName); 19073 if (p != null && p.childPackages != null) { 19074 final int N = p.childPackages.size(); 19075 mChildren = new PackageFreezer[N]; 19076 for (int i = 0; i < N; i++) { 19077 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 19078 killReason); 19079 } 19080 } else { 19081 mChildren = null; 19082 } 19083 } 19084 mCloseGuard.open("close"); 19085 } 19086 19087 @Override 19088 protected void finalize() throws Throwable { 19089 try { 19090 mCloseGuard.warnIfOpen(); 19091 close(); 19092 } finally { 19093 super.finalize(); 19094 } 19095 } 19096 19097 @Override 19098 public void close() { 19099 mCloseGuard.close(); 19100 if (mClosed.compareAndSet(false, true)) { 19101 synchronized (mPackages) { 19102 if (mWeFroze) { 19103 mFrozenPackages.remove(mPackageName); 19104 } 19105 19106 if (mChildren != null) { 19107 for (PackageFreezer freezer : mChildren) { 19108 freezer.close(); 19109 } 19110 } 19111 } 19112 } 19113 } 19114 } 19115 19116 /** 19117 * Verify that given package is currently frozen. 19118 */ 19119 private void checkPackageFrozen(String packageName) { 19120 synchronized (mPackages) { 19121 if (!mFrozenPackages.contains(packageName)) { 19122 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 19123 } 19124 } 19125 } 19126 19127 @Override 19128 public int movePackage(final String packageName, final String volumeUuid) { 19129 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19130 19131 final int moveId = mNextMoveId.getAndIncrement(); 19132 mHandler.post(new Runnable() { 19133 @Override 19134 public void run() { 19135 try { 19136 movePackageInternal(packageName, volumeUuid, moveId); 19137 } catch (PackageManagerException e) { 19138 Slog.w(TAG, "Failed to move " + packageName, e); 19139 mMoveCallbacks.notifyStatusChanged(moveId, 19140 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19141 } 19142 } 19143 }); 19144 return moveId; 19145 } 19146 19147 private void movePackageInternal(final String packageName, final String volumeUuid, 19148 final int moveId) throws PackageManagerException { 19149 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 19150 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19151 final PackageManager pm = mContext.getPackageManager(); 19152 19153 final boolean currentAsec; 19154 final String currentVolumeUuid; 19155 final File codeFile; 19156 final String installerPackageName; 19157 final String packageAbiOverride; 19158 final int appId; 19159 final String seinfo; 19160 final String label; 19161 final int targetSdkVersion; 19162 final PackageFreezer freezer; 19163 19164 // reader 19165 synchronized (mPackages) { 19166 final PackageParser.Package pkg = mPackages.get(packageName); 19167 final PackageSetting ps = mSettings.mPackages.get(packageName); 19168 if (pkg == null || ps == null) { 19169 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 19170 } 19171 19172 if (pkg.applicationInfo.isSystemApp()) { 19173 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 19174 "Cannot move system application"); 19175 } 19176 19177 if (pkg.applicationInfo.isExternalAsec()) { 19178 currentAsec = true; 19179 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 19180 } else if (pkg.applicationInfo.isForwardLocked()) { 19181 currentAsec = true; 19182 currentVolumeUuid = "forward_locked"; 19183 } else { 19184 currentAsec = false; 19185 currentVolumeUuid = ps.volumeUuid; 19186 19187 final File probe = new File(pkg.codePath); 19188 final File probeOat = new File(probe, "oat"); 19189 if (!probe.isDirectory() || !probeOat.isDirectory()) { 19190 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19191 "Move only supported for modern cluster style installs"); 19192 } 19193 } 19194 19195 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 19196 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19197 "Package already moved to " + volumeUuid); 19198 } 19199 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 19200 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 19201 "Device admin cannot be moved"); 19202 } 19203 19204 if (mFrozenPackages.contains(packageName)) { 19205 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 19206 "Failed to move already frozen package"); 19207 } 19208 19209 codeFile = new File(pkg.codePath); 19210 installerPackageName = ps.installerPackageName; 19211 packageAbiOverride = ps.cpuAbiOverrideString; 19212 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 19213 seinfo = pkg.applicationInfo.seinfo; 19214 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 19215 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 19216 freezer = new PackageFreezer(packageName, "movePackageInternal"); 19217 } 19218 19219 final Bundle extras = new Bundle(); 19220 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 19221 extras.putString(Intent.EXTRA_TITLE, label); 19222 mMoveCallbacks.notifyCreated(moveId, extras); 19223 19224 int installFlags; 19225 final boolean moveCompleteApp; 19226 final File measurePath; 19227 19228 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 19229 installFlags = INSTALL_INTERNAL; 19230 moveCompleteApp = !currentAsec; 19231 measurePath = Environment.getDataAppDirectory(volumeUuid); 19232 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 19233 installFlags = INSTALL_EXTERNAL; 19234 moveCompleteApp = false; 19235 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 19236 } else { 19237 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 19238 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 19239 || !volume.isMountedWritable()) { 19240 freezer.close(); 19241 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19242 "Move location not mounted private volume"); 19243 } 19244 19245 Preconditions.checkState(!currentAsec); 19246 19247 installFlags = INSTALL_INTERNAL; 19248 moveCompleteApp = true; 19249 measurePath = Environment.getDataAppDirectory(volumeUuid); 19250 } 19251 19252 final PackageStats stats = new PackageStats(null, -1); 19253 synchronized (mInstaller) { 19254 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 19255 freezer.close(); 19256 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19257 "Failed to measure package size"); 19258 } 19259 } 19260 19261 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 19262 + stats.dataSize); 19263 19264 final long startFreeBytes = measurePath.getFreeSpace(); 19265 final long sizeBytes; 19266 if (moveCompleteApp) { 19267 sizeBytes = stats.codeSize + stats.dataSize; 19268 } else { 19269 sizeBytes = stats.codeSize; 19270 } 19271 19272 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 19273 freezer.close(); 19274 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19275 "Not enough free space to move"); 19276 } 19277 19278 mMoveCallbacks.notifyStatusChanged(moveId, 10); 19279 19280 final CountDownLatch installedLatch = new CountDownLatch(1); 19281 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 19282 @Override 19283 public void onUserActionRequired(Intent intent) throws RemoteException { 19284 throw new IllegalStateException(); 19285 } 19286 19287 @Override 19288 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 19289 Bundle extras) throws RemoteException { 19290 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 19291 + PackageManager.installStatusToString(returnCode, msg)); 19292 19293 installedLatch.countDown(); 19294 freezer.close(); 19295 19296 final int status = PackageManager.installStatusToPublicStatus(returnCode); 19297 switch (status) { 19298 case PackageInstaller.STATUS_SUCCESS: 19299 mMoveCallbacks.notifyStatusChanged(moveId, 19300 PackageManager.MOVE_SUCCEEDED); 19301 break; 19302 case PackageInstaller.STATUS_FAILURE_STORAGE: 19303 mMoveCallbacks.notifyStatusChanged(moveId, 19304 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 19305 break; 19306 default: 19307 mMoveCallbacks.notifyStatusChanged(moveId, 19308 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19309 break; 19310 } 19311 } 19312 }; 19313 19314 final MoveInfo move; 19315 if (moveCompleteApp) { 19316 // Kick off a thread to report progress estimates 19317 new Thread() { 19318 @Override 19319 public void run() { 19320 while (true) { 19321 try { 19322 if (installedLatch.await(1, TimeUnit.SECONDS)) { 19323 break; 19324 } 19325 } catch (InterruptedException ignored) { 19326 } 19327 19328 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 19329 final int progress = 10 + (int) MathUtils.constrain( 19330 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 19331 mMoveCallbacks.notifyStatusChanged(moveId, progress); 19332 } 19333 } 19334 }.start(); 19335 19336 final String dataAppName = codeFile.getName(); 19337 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 19338 dataAppName, appId, seinfo, targetSdkVersion); 19339 } else { 19340 move = null; 19341 } 19342 19343 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 19344 19345 final Message msg = mHandler.obtainMessage(INIT_COPY); 19346 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 19347 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 19348 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 19349 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/); 19350 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 19351 msg.obj = params; 19352 19353 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 19354 System.identityHashCode(msg.obj)); 19355 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 19356 System.identityHashCode(msg.obj)); 19357 19358 mHandler.sendMessage(msg); 19359 } 19360 19361 @Override 19362 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 19363 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19364 19365 final int realMoveId = mNextMoveId.getAndIncrement(); 19366 final Bundle extras = new Bundle(); 19367 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 19368 mMoveCallbacks.notifyCreated(realMoveId, extras); 19369 19370 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 19371 @Override 19372 public void onCreated(int moveId, Bundle extras) { 19373 // Ignored 19374 } 19375 19376 @Override 19377 public void onStatusChanged(int moveId, int status, long estMillis) { 19378 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 19379 } 19380 }; 19381 19382 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19383 storage.setPrimaryStorageUuid(volumeUuid, callback); 19384 return realMoveId; 19385 } 19386 19387 @Override 19388 public int getMoveStatus(int moveId) { 19389 mContext.enforceCallingOrSelfPermission( 19390 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19391 return mMoveCallbacks.mLastStatus.get(moveId); 19392 } 19393 19394 @Override 19395 public void registerMoveCallback(IPackageMoveObserver callback) { 19396 mContext.enforceCallingOrSelfPermission( 19397 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19398 mMoveCallbacks.register(callback); 19399 } 19400 19401 @Override 19402 public void unregisterMoveCallback(IPackageMoveObserver callback) { 19403 mContext.enforceCallingOrSelfPermission( 19404 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19405 mMoveCallbacks.unregister(callback); 19406 } 19407 19408 @Override 19409 public boolean setInstallLocation(int loc) { 19410 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 19411 null); 19412 if (getInstallLocation() == loc) { 19413 return true; 19414 } 19415 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 19416 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 19417 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 19418 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 19419 return true; 19420 } 19421 return false; 19422 } 19423 19424 @Override 19425 public int getInstallLocation() { 19426 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 19427 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 19428 PackageHelper.APP_INSTALL_AUTO); 19429 } 19430 19431 /** Called by UserManagerService */ 19432 void cleanUpUser(UserManagerService userManager, int userHandle) { 19433 synchronized (mPackages) { 19434 mDirtyUsers.remove(userHandle); 19435 mUserNeedsBadging.delete(userHandle); 19436 mSettings.removeUserLPw(userHandle); 19437 mPendingBroadcasts.remove(userHandle); 19438 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 19439 } 19440 synchronized (mInstallLock) { 19441 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19442 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19443 final String volumeUuid = vol.getFsUuid(); 19444 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 19445 try { 19446 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 19447 } catch (InstallerException e) { 19448 Slog.w(TAG, "Failed to remove user data", e); 19449 } 19450 } 19451 synchronized (mPackages) { 19452 removeUnusedPackagesLILPw(userManager, userHandle); 19453 } 19454 } 19455 } 19456 19457 /** 19458 * We're removing userHandle and would like to remove any downloaded packages 19459 * that are no longer in use by any other user. 19460 * @param userHandle the user being removed 19461 */ 19462 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 19463 final boolean DEBUG_CLEAN_APKS = false; 19464 int [] users = userManager.getUserIds(); 19465 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 19466 while (psit.hasNext()) { 19467 PackageSetting ps = psit.next(); 19468 if (ps.pkg == null) { 19469 continue; 19470 } 19471 final String packageName = ps.pkg.packageName; 19472 // Skip over if system app 19473 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 19474 continue; 19475 } 19476 if (DEBUG_CLEAN_APKS) { 19477 Slog.i(TAG, "Checking package " + packageName); 19478 } 19479 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 19480 if (keep) { 19481 if (DEBUG_CLEAN_APKS) { 19482 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 19483 } 19484 } else { 19485 for (int i = 0; i < users.length; i++) { 19486 if (users[i] != userHandle && ps.getInstalled(users[i])) { 19487 keep = true; 19488 if (DEBUG_CLEAN_APKS) { 19489 Slog.i(TAG, " Keeping package " + packageName + " for user " 19490 + users[i]); 19491 } 19492 break; 19493 } 19494 } 19495 } 19496 if (!keep) { 19497 if (DEBUG_CLEAN_APKS) { 19498 Slog.i(TAG, " Removing package " + packageName); 19499 } 19500 mHandler.post(new Runnable() { 19501 public void run() { 19502 deletePackageX(packageName, userHandle, 0); 19503 } //end run 19504 }); 19505 } 19506 } 19507 } 19508 19509 /** Called by UserManagerService */ 19510 void createNewUser(int userHandle) { 19511 synchronized (mInstallLock) { 19512 try { 19513 mInstaller.createUserConfig(userHandle); 19514 } catch (InstallerException e) { 19515 Slog.w(TAG, "Failed to create user config", e); 19516 } 19517 mSettings.createNewUserLI(this, mInstaller, userHandle); 19518 } 19519 synchronized (mPackages) { 19520 applyFactoryDefaultBrowserLPw(userHandle); 19521 primeDomainVerificationsLPw(userHandle); 19522 } 19523 } 19524 19525 void newUserCreated(final int userHandle) { 19526 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 19527 // If permission review for legacy apps is required, we represent 19528 // dagerous permissions for such apps as always granted runtime 19529 // permissions to keep per user flag state whether review is needed. 19530 // Hence, if a new user is added we have to propagate dangerous 19531 // permission grants for these legacy apps. 19532 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 19533 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 19534 | UPDATE_PERMISSIONS_REPLACE_ALL); 19535 } 19536 } 19537 19538 @Override 19539 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 19540 mContext.enforceCallingOrSelfPermission( 19541 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 19542 "Only package verification agents can read the verifier device identity"); 19543 19544 synchronized (mPackages) { 19545 return mSettings.getVerifierDeviceIdentityLPw(); 19546 } 19547 } 19548 19549 @Override 19550 public void setPermissionEnforced(String permission, boolean enforced) { 19551 // TODO: Now that we no longer change GID for storage, this should to away. 19552 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 19553 "setPermissionEnforced"); 19554 if (READ_EXTERNAL_STORAGE.equals(permission)) { 19555 synchronized (mPackages) { 19556 if (mSettings.mReadExternalStorageEnforced == null 19557 || mSettings.mReadExternalStorageEnforced != enforced) { 19558 mSettings.mReadExternalStorageEnforced = enforced; 19559 mSettings.writeLPr(); 19560 } 19561 } 19562 // kill any non-foreground processes so we restart them and 19563 // grant/revoke the GID. 19564 final IActivityManager am = ActivityManagerNative.getDefault(); 19565 if (am != null) { 19566 final long token = Binder.clearCallingIdentity(); 19567 try { 19568 am.killProcessesBelowForeground("setPermissionEnforcement"); 19569 } catch (RemoteException e) { 19570 } finally { 19571 Binder.restoreCallingIdentity(token); 19572 } 19573 } 19574 } else { 19575 throw new IllegalArgumentException("No selective enforcement for " + permission); 19576 } 19577 } 19578 19579 @Override 19580 @Deprecated 19581 public boolean isPermissionEnforced(String permission) { 19582 return true; 19583 } 19584 19585 @Override 19586 public boolean isStorageLow() { 19587 final long token = Binder.clearCallingIdentity(); 19588 try { 19589 final DeviceStorageMonitorInternal 19590 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 19591 if (dsm != null) { 19592 return dsm.isMemoryLow(); 19593 } else { 19594 return false; 19595 } 19596 } finally { 19597 Binder.restoreCallingIdentity(token); 19598 } 19599 } 19600 19601 @Override 19602 public IPackageInstaller getPackageInstaller() { 19603 return mInstallerService; 19604 } 19605 19606 private boolean userNeedsBadging(int userId) { 19607 int index = mUserNeedsBadging.indexOfKey(userId); 19608 if (index < 0) { 19609 final UserInfo userInfo; 19610 final long token = Binder.clearCallingIdentity(); 19611 try { 19612 userInfo = sUserManager.getUserInfo(userId); 19613 } finally { 19614 Binder.restoreCallingIdentity(token); 19615 } 19616 final boolean b; 19617 if (userInfo != null && userInfo.isManagedProfile()) { 19618 b = true; 19619 } else { 19620 b = false; 19621 } 19622 mUserNeedsBadging.put(userId, b); 19623 return b; 19624 } 19625 return mUserNeedsBadging.valueAt(index); 19626 } 19627 19628 @Override 19629 public KeySet getKeySetByAlias(String packageName, String alias) { 19630 if (packageName == null || alias == null) { 19631 return null; 19632 } 19633 synchronized(mPackages) { 19634 final PackageParser.Package pkg = mPackages.get(packageName); 19635 if (pkg == null) { 19636 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19637 throw new IllegalArgumentException("Unknown package: " + packageName); 19638 } 19639 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19640 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 19641 } 19642 } 19643 19644 @Override 19645 public KeySet getSigningKeySet(String packageName) { 19646 if (packageName == null) { 19647 return null; 19648 } 19649 synchronized(mPackages) { 19650 final PackageParser.Package pkg = mPackages.get(packageName); 19651 if (pkg == null) { 19652 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19653 throw new IllegalArgumentException("Unknown package: " + packageName); 19654 } 19655 if (pkg.applicationInfo.uid != Binder.getCallingUid() 19656 && Process.SYSTEM_UID != Binder.getCallingUid()) { 19657 throw new SecurityException("May not access signing KeySet of other apps."); 19658 } 19659 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19660 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 19661 } 19662 } 19663 19664 @Override 19665 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 19666 if (packageName == null || ks == null) { 19667 return false; 19668 } 19669 synchronized(mPackages) { 19670 final PackageParser.Package pkg = mPackages.get(packageName); 19671 if (pkg == null) { 19672 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19673 throw new IllegalArgumentException("Unknown package: " + packageName); 19674 } 19675 IBinder ksh = ks.getToken(); 19676 if (ksh instanceof KeySetHandle) { 19677 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19678 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 19679 } 19680 return false; 19681 } 19682 } 19683 19684 @Override 19685 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 19686 if (packageName == null || ks == null) { 19687 return false; 19688 } 19689 synchronized(mPackages) { 19690 final PackageParser.Package pkg = mPackages.get(packageName); 19691 if (pkg == null) { 19692 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19693 throw new IllegalArgumentException("Unknown package: " + packageName); 19694 } 19695 IBinder ksh = ks.getToken(); 19696 if (ksh instanceof KeySetHandle) { 19697 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19698 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 19699 } 19700 return false; 19701 } 19702 } 19703 19704 private void deletePackageIfUnusedLPr(final String packageName) { 19705 PackageSetting ps = mSettings.mPackages.get(packageName); 19706 if (ps == null) { 19707 return; 19708 } 19709 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 19710 // TODO Implement atomic delete if package is unused 19711 // It is currently possible that the package will be deleted even if it is installed 19712 // after this method returns. 19713 mHandler.post(new Runnable() { 19714 public void run() { 19715 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 19716 } 19717 }); 19718 } 19719 } 19720 19721 /** 19722 * Check and throw if the given before/after packages would be considered a 19723 * downgrade. 19724 */ 19725 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 19726 throws PackageManagerException { 19727 if (after.versionCode < before.mVersionCode) { 19728 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 19729 "Update version code " + after.versionCode + " is older than current " 19730 + before.mVersionCode); 19731 } else if (after.versionCode == before.mVersionCode) { 19732 if (after.baseRevisionCode < before.baseRevisionCode) { 19733 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 19734 "Update base revision code " + after.baseRevisionCode 19735 + " is older than current " + before.baseRevisionCode); 19736 } 19737 19738 if (!ArrayUtils.isEmpty(after.splitNames)) { 19739 for (int i = 0; i < after.splitNames.length; i++) { 19740 final String splitName = after.splitNames[i]; 19741 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 19742 if (j != -1) { 19743 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 19744 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 19745 "Update split " + splitName + " revision code " 19746 + after.splitRevisionCodes[i] + " is older than current " 19747 + before.splitRevisionCodes[j]); 19748 } 19749 } 19750 } 19751 } 19752 } 19753 } 19754 19755 private static class MoveCallbacks extends Handler { 19756 private static final int MSG_CREATED = 1; 19757 private static final int MSG_STATUS_CHANGED = 2; 19758 19759 private final RemoteCallbackList<IPackageMoveObserver> 19760 mCallbacks = new RemoteCallbackList<>(); 19761 19762 private final SparseIntArray mLastStatus = new SparseIntArray(); 19763 19764 public MoveCallbacks(Looper looper) { 19765 super(looper); 19766 } 19767 19768 public void register(IPackageMoveObserver callback) { 19769 mCallbacks.register(callback); 19770 } 19771 19772 public void unregister(IPackageMoveObserver callback) { 19773 mCallbacks.unregister(callback); 19774 } 19775 19776 @Override 19777 public void handleMessage(Message msg) { 19778 final SomeArgs args = (SomeArgs) msg.obj; 19779 final int n = mCallbacks.beginBroadcast(); 19780 for (int i = 0; i < n; i++) { 19781 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 19782 try { 19783 invokeCallback(callback, msg.what, args); 19784 } catch (RemoteException ignored) { 19785 } 19786 } 19787 mCallbacks.finishBroadcast(); 19788 args.recycle(); 19789 } 19790 19791 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 19792 throws RemoteException { 19793 switch (what) { 19794 case MSG_CREATED: { 19795 callback.onCreated(args.argi1, (Bundle) args.arg2); 19796 break; 19797 } 19798 case MSG_STATUS_CHANGED: { 19799 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 19800 break; 19801 } 19802 } 19803 } 19804 19805 private void notifyCreated(int moveId, Bundle extras) { 19806 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 19807 19808 final SomeArgs args = SomeArgs.obtain(); 19809 args.argi1 = moveId; 19810 args.arg2 = extras; 19811 obtainMessage(MSG_CREATED, args).sendToTarget(); 19812 } 19813 19814 private void notifyStatusChanged(int moveId, int status) { 19815 notifyStatusChanged(moveId, status, -1); 19816 } 19817 19818 private void notifyStatusChanged(int moveId, int status, long estMillis) { 19819 Slog.v(TAG, "Move " + moveId + " status " + status); 19820 19821 final SomeArgs args = SomeArgs.obtain(); 19822 args.argi1 = moveId; 19823 args.argi2 = status; 19824 args.arg3 = estMillis; 19825 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 19826 19827 synchronized (mLastStatus) { 19828 mLastStatus.put(moveId, status); 19829 } 19830 } 19831 } 19832 19833 private final static class OnPermissionChangeListeners extends Handler { 19834 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 19835 19836 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 19837 new RemoteCallbackList<>(); 19838 19839 public OnPermissionChangeListeners(Looper looper) { 19840 super(looper); 19841 } 19842 19843 @Override 19844 public void handleMessage(Message msg) { 19845 switch (msg.what) { 19846 case MSG_ON_PERMISSIONS_CHANGED: { 19847 final int uid = msg.arg1; 19848 handleOnPermissionsChanged(uid); 19849 } break; 19850 } 19851 } 19852 19853 public void addListenerLocked(IOnPermissionsChangeListener listener) { 19854 mPermissionListeners.register(listener); 19855 19856 } 19857 19858 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 19859 mPermissionListeners.unregister(listener); 19860 } 19861 19862 public void onPermissionsChanged(int uid) { 19863 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 19864 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 19865 } 19866 } 19867 19868 private void handleOnPermissionsChanged(int uid) { 19869 final int count = mPermissionListeners.beginBroadcast(); 19870 try { 19871 for (int i = 0; i < count; i++) { 19872 IOnPermissionsChangeListener callback = mPermissionListeners 19873 .getBroadcastItem(i); 19874 try { 19875 callback.onPermissionsChanged(uid); 19876 } catch (RemoteException e) { 19877 Log.e(TAG, "Permission listener is dead", e); 19878 } 19879 } 19880 } finally { 19881 mPermissionListeners.finishBroadcast(); 19882 } 19883 } 19884 } 19885 19886 private class PackageManagerInternalImpl extends PackageManagerInternal { 19887 @Override 19888 public void setLocationPackagesProvider(PackagesProvider provider) { 19889 synchronized (mPackages) { 19890 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 19891 } 19892 } 19893 19894 @Override 19895 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 19896 synchronized (mPackages) { 19897 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 19898 } 19899 } 19900 19901 @Override 19902 public void setSmsAppPackagesProvider(PackagesProvider provider) { 19903 synchronized (mPackages) { 19904 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 19905 } 19906 } 19907 19908 @Override 19909 public void setDialerAppPackagesProvider(PackagesProvider provider) { 19910 synchronized (mPackages) { 19911 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 19912 } 19913 } 19914 19915 @Override 19916 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 19917 synchronized (mPackages) { 19918 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 19919 } 19920 } 19921 19922 @Override 19923 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 19924 synchronized (mPackages) { 19925 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 19926 } 19927 } 19928 19929 @Override 19930 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 19931 synchronized (mPackages) { 19932 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 19933 packageName, userId); 19934 } 19935 } 19936 19937 @Override 19938 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 19939 synchronized (mPackages) { 19940 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 19941 packageName, userId); 19942 } 19943 } 19944 19945 @Override 19946 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 19947 synchronized (mPackages) { 19948 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 19949 packageName, userId); 19950 } 19951 } 19952 19953 @Override 19954 public void setKeepUninstalledPackages(final List<String> packageList) { 19955 Preconditions.checkNotNull(packageList); 19956 List<String> removedFromList = null; 19957 synchronized (mPackages) { 19958 if (mKeepUninstalledPackages != null) { 19959 final int packagesCount = mKeepUninstalledPackages.size(); 19960 for (int i = 0; i < packagesCount; i++) { 19961 String oldPackage = mKeepUninstalledPackages.get(i); 19962 if (packageList != null && packageList.contains(oldPackage)) { 19963 continue; 19964 } 19965 if (removedFromList == null) { 19966 removedFromList = new ArrayList<>(); 19967 } 19968 removedFromList.add(oldPackage); 19969 } 19970 } 19971 mKeepUninstalledPackages = new ArrayList<>(packageList); 19972 if (removedFromList != null) { 19973 final int removedCount = removedFromList.size(); 19974 for (int i = 0; i < removedCount; i++) { 19975 deletePackageIfUnusedLPr(removedFromList.get(i)); 19976 } 19977 } 19978 } 19979 } 19980 19981 @Override 19982 public boolean isPermissionsReviewRequired(String packageName, int userId) { 19983 synchronized (mPackages) { 19984 // If we do not support permission review, done. 19985 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 19986 return false; 19987 } 19988 19989 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 19990 if (packageSetting == null) { 19991 return false; 19992 } 19993 19994 // Permission review applies only to apps not supporting the new permission model. 19995 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 19996 return false; 19997 } 19998 19999 // Legacy apps have the permission and get user consent on launch. 20000 PermissionsState permissionsState = packageSetting.getPermissionsState(); 20001 return permissionsState.isPermissionReviewRequired(userId); 20002 } 20003 } 20004 20005 @Override 20006 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 20007 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 20008 } 20009 20010 @Override 20011 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 20012 int userId) { 20013 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 20014 } 20015 } 20016 20017 @Override 20018 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 20019 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 20020 synchronized (mPackages) { 20021 final long identity = Binder.clearCallingIdentity(); 20022 try { 20023 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 20024 packageNames, userId); 20025 } finally { 20026 Binder.restoreCallingIdentity(identity); 20027 } 20028 } 20029 } 20030 20031 private static void enforceSystemOrPhoneCaller(String tag) { 20032 int callingUid = Binder.getCallingUid(); 20033 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 20034 throw new SecurityException( 20035 "Cannot call " + tag + " from UID " + callingUid); 20036 } 20037 } 20038 20039 boolean isHistoricalPackageUsageAvailable() { 20040 return mPackageUsage.isHistoricalPackageUsageAvailable(); 20041 } 20042 20043 /** 20044 * Return a <b>copy</b> of the collection of packages known to the package manager. 20045 * @return A copy of the values of mPackages. 20046 */ 20047 Collection<PackageParser.Package> getPackages() { 20048 synchronized (mPackages) { 20049 return new ArrayList<>(mPackages.values()); 20050 } 20051 } 20052 20053 /** 20054 * Logs process start information (including base APK hash) to the security log. 20055 * @hide 20056 */ 20057 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 20058 String apkFile, int pid) { 20059 if (!SecurityLog.isLoggingEnabled()) { 20060 return; 20061 } 20062 Bundle data = new Bundle(); 20063 data.putLong("startTimestamp", System.currentTimeMillis()); 20064 data.putString("processName", processName); 20065 data.putInt("uid", uid); 20066 data.putString("seinfo", seinfo); 20067 data.putString("apkFile", apkFile); 20068 data.putInt("pid", pid); 20069 Message msg = mProcessLoggingHandler.obtainMessage( 20070 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 20071 msg.setData(data); 20072 mProcessLoggingHandler.sendMessage(msg); 20073 } 20074} 20075