PackageManagerService.java revision a9c2500a6863dabdd786f17a25ce0bf3683109a2
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.telephony.CarrierAppUtils; 233import com.android.internal.util.ArrayUtils; 234import com.android.internal.util.FastPrintWriter; 235import com.android.internal.util.FastXmlSerializer; 236import com.android.internal.util.IndentingPrintWriter; 237import com.android.internal.util.Preconditions; 238import com.android.internal.util.XmlUtils; 239import com.android.server.EventLogTags; 240import com.android.server.FgThread; 241import com.android.server.IntentResolver; 242import com.android.server.LocalServices; 243import com.android.server.ServiceThread; 244import com.android.server.SystemConfig; 245import com.android.server.Watchdog; 246import com.android.server.pm.PermissionsState.PermissionState; 247import com.android.server.pm.Settings.DatabaseVersion; 248import com.android.server.pm.Settings.VersionInfo; 249import com.android.server.storage.DeviceStorageMonitorInternal; 250 251import dalvik.system.CloseGuard; 252import dalvik.system.DexFile; 253import dalvik.system.VMRuntime; 254 255import libcore.io.IoUtils; 256import libcore.util.EmptyArray; 257 258import org.xmlpull.v1.XmlPullParser; 259import org.xmlpull.v1.XmlPullParserException; 260import org.xmlpull.v1.XmlSerializer; 261 262import java.io.BufferedInputStream; 263import java.io.BufferedOutputStream; 264import java.io.BufferedReader; 265import java.io.ByteArrayInputStream; 266import java.io.ByteArrayOutputStream; 267import java.io.File; 268import java.io.FileDescriptor; 269import java.io.FileNotFoundException; 270import java.io.FileOutputStream; 271import java.io.FileReader; 272import java.io.FilenameFilter; 273import java.io.IOException; 274import java.io.InputStream; 275import java.io.PrintWriter; 276import java.nio.charset.StandardCharsets; 277import java.security.MessageDigest; 278import java.security.NoSuchAlgorithmException; 279import java.security.PublicKey; 280import java.security.cert.Certificate; 281import java.security.cert.CertificateEncodingException; 282import java.security.cert.CertificateException; 283import java.text.SimpleDateFormat; 284import java.util.ArrayList; 285import java.util.Arrays; 286import java.util.Collection; 287import java.util.Collections; 288import java.util.Comparator; 289import java.util.Date; 290import java.util.HashSet; 291import java.util.Iterator; 292import java.util.List; 293import java.util.Map; 294import java.util.Objects; 295import java.util.Set; 296import java.util.concurrent.CountDownLatch; 297import java.util.concurrent.TimeUnit; 298import java.util.concurrent.atomic.AtomicBoolean; 299import java.util.concurrent.atomic.AtomicInteger; 300import java.util.concurrent.atomic.AtomicLong; 301 302/** 303 * Keep track of all those APKs everywhere. 304 * <p> 305 * Internally there are two important locks: 306 * <ul> 307 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 308 * and other related state. It is a fine-grained lock that should only be held 309 * momentarily, as it's one of the most contended locks in the system. 310 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 311 * operations typically involve heavy lifting of application data on disk. Since 312 * {@code installd} is single-threaded, and it's operations can often be slow, 313 * this lock should never be acquired while already holding {@link #mPackages}. 314 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 315 * holding {@link #mInstallLock}. 316 * </ul> 317 * Many internal methods rely on the caller to hold the appropriate locks, and 318 * this contract is expressed through method name suffixes: 319 * <ul> 320 * <li>fooLI(): the caller must hold {@link #mInstallLock} 321 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 322 * being modified must be frozen 323 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 324 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 325 * </ul> 326 * <p> 327 * Because this class is very central to the platform's security; please run all 328 * CTS and unit tests whenever making modifications: 329 * 330 * <pre> 331 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 332 * $ cts-tradefed run commandAndExit cts -m AppSecurityTests 333 * </pre> 334 */ 335public class PackageManagerService extends IPackageManager.Stub { 336 static final String TAG = "PackageManager"; 337 static final boolean DEBUG_SETTINGS = false; 338 static final boolean DEBUG_PREFERRED = false; 339 static final boolean DEBUG_UPGRADE = false; 340 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 341 private static final boolean DEBUG_BACKUP = false; 342 private static final boolean DEBUG_INSTALL = false; 343 private static final boolean DEBUG_REMOVE = false; 344 private static final boolean DEBUG_BROADCASTS = false; 345 private static final boolean DEBUG_SHOW_INFO = false; 346 private static final boolean DEBUG_PACKAGE_INFO = false; 347 private static final boolean DEBUG_INTENT_MATCHING = false; 348 private static final boolean DEBUG_PACKAGE_SCANNING = false; 349 private static final boolean DEBUG_VERIFY = false; 350 private static final boolean DEBUG_FILTERS = false; 351 352 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 353 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 354 // user, but by default initialize to this. 355 static final boolean DEBUG_DEXOPT = false; 356 357 private static final boolean DEBUG_ABI_SELECTION = false; 358 private static final boolean DEBUG_EPHEMERAL = false; 359 private static final boolean DEBUG_TRIAGED_MISSING = false; 360 private static final boolean DEBUG_APP_DATA = false; 361 362 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 363 364 private static final boolean DISABLE_EPHEMERAL_APPS = true; 365 366 private static final int RADIO_UID = Process.PHONE_UID; 367 private static final int LOG_UID = Process.LOG_UID; 368 private static final int NFC_UID = Process.NFC_UID; 369 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 370 private static final int SHELL_UID = Process.SHELL_UID; 371 372 // Cap the size of permission trees that 3rd party apps can define 373 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 374 375 // Suffix used during package installation when copying/moving 376 // package apks to install directory. 377 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 378 379 static final int SCAN_NO_DEX = 1<<1; 380 static final int SCAN_FORCE_DEX = 1<<2; 381 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 382 static final int SCAN_NEW_INSTALL = 1<<4; 383 static final int SCAN_NO_PATHS = 1<<5; 384 static final int SCAN_UPDATE_TIME = 1<<6; 385 static final int SCAN_DEFER_DEX = 1<<7; 386 static final int SCAN_BOOTING = 1<<8; 387 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 388 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 389 static final int SCAN_REPLACING = 1<<11; 390 static final int SCAN_REQUIRE_KNOWN = 1<<12; 391 static final int SCAN_MOVE = 1<<13; 392 static final int SCAN_INITIAL = 1<<14; 393 static final int SCAN_CHECK_ONLY = 1<<15; 394 static final int SCAN_DONT_KILL_APP = 1<<17; 395 static final int SCAN_IGNORE_FROZEN = 1<<18; 396 397 static final int REMOVE_CHATTY = 1<<16; 398 399 private static final int[] EMPTY_INT_ARRAY = new int[0]; 400 401 /** 402 * Timeout (in milliseconds) after which the watchdog should declare that 403 * our handler thread is wedged. The usual default for such things is one 404 * minute but we sometimes do very lengthy I/O operations on this thread, 405 * such as installing multi-gigabyte applications, so ours needs to be longer. 406 */ 407 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 408 409 /** 410 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 411 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 412 * settings entry if available, otherwise we use the hardcoded default. If it's been 413 * more than this long since the last fstrim, we force one during the boot sequence. 414 * 415 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 416 * one gets run at the next available charging+idle time. This final mandatory 417 * no-fstrim check kicks in only of the other scheduling criteria is never met. 418 */ 419 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 420 421 /** 422 * Whether verification is enabled by default. 423 */ 424 private static final boolean DEFAULT_VERIFY_ENABLE = true; 425 426 /** 427 * The default maximum time to wait for the verification agent to return in 428 * milliseconds. 429 */ 430 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 431 432 /** 433 * The default response for package verification timeout. 434 * 435 * This can be either PackageManager.VERIFICATION_ALLOW or 436 * PackageManager.VERIFICATION_REJECT. 437 */ 438 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 439 440 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 441 442 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 443 DEFAULT_CONTAINER_PACKAGE, 444 "com.android.defcontainer.DefaultContainerService"); 445 446 private static final String KILL_APP_REASON_GIDS_CHANGED = 447 "permission grant or revoke changed gids"; 448 449 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 450 "permissions revoked"; 451 452 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 453 454 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 455 456 /** Permission grant: not grant the permission. */ 457 private static final int GRANT_DENIED = 1; 458 459 /** Permission grant: grant the permission as an install permission. */ 460 private static final int GRANT_INSTALL = 2; 461 462 /** Permission grant: grant the permission as a runtime one. */ 463 private static final int GRANT_RUNTIME = 3; 464 465 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 466 private static final int GRANT_UPGRADE = 4; 467 468 /** Canonical intent used to identify what counts as a "web browser" app */ 469 private static final Intent sBrowserIntent; 470 static { 471 sBrowserIntent = new Intent(); 472 sBrowserIntent.setAction(Intent.ACTION_VIEW); 473 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 474 sBrowserIntent.setData(Uri.parse("http:")); 475 } 476 477 /** 478 * The set of all protected actions [i.e. those actions for which a high priority 479 * intent filter is disallowed]. 480 */ 481 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 482 static { 483 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 484 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 485 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 486 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 487 } 488 489 // Compilation reasons. 490 public static final int REASON_FIRST_BOOT = 0; 491 public static final int REASON_BOOT = 1; 492 public static final int REASON_INSTALL = 2; 493 public static final int REASON_BACKGROUND_DEXOPT = 3; 494 public static final int REASON_AB_OTA = 4; 495 public static final int REASON_NON_SYSTEM_LIBRARY = 5; 496 public static final int REASON_SHARED_APK = 6; 497 public static final int REASON_FORCED_DEXOPT = 7; 498 499 public static final int REASON_LAST = REASON_FORCED_DEXOPT; 500 501 final ServiceThread mHandlerThread; 502 503 final PackageHandler mHandler; 504 505 private final ProcessLoggingHandler mProcessLoggingHandler; 506 507 /** 508 * Messages for {@link #mHandler} that need to wait for system ready before 509 * being dispatched. 510 */ 511 private ArrayList<Message> mPostSystemReadyMessages; 512 513 final int mSdkVersion = Build.VERSION.SDK_INT; 514 515 final Context mContext; 516 final boolean mFactoryTest; 517 final boolean mOnlyCore; 518 final DisplayMetrics mMetrics; 519 final int mDefParseFlags; 520 final String[] mSeparateProcesses; 521 final boolean mIsUpgrade; 522 final boolean mIsPreNUpgrade; 523 524 /** The location for ASEC container files on internal storage. */ 525 final String mAsecInternalPath; 526 527 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 528 // LOCK HELD. Can be called with mInstallLock held. 529 @GuardedBy("mInstallLock") 530 final Installer mInstaller; 531 532 /** Directory where installed third-party apps stored */ 533 final File mAppInstallDir; 534 final File mEphemeralInstallDir; 535 536 /** 537 * Directory to which applications installed internally have their 538 * 32 bit native libraries copied. 539 */ 540 private File mAppLib32InstallDir; 541 542 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 543 // apps. 544 final File mDrmAppPrivateInstallDir; 545 546 // ---------------------------------------------------------------- 547 548 // Lock for state used when installing and doing other long running 549 // operations. Methods that must be called with this lock held have 550 // the suffix "LI". 551 final Object mInstallLock = new Object(); 552 553 // ---------------------------------------------------------------- 554 555 // Keys are String (package name), values are Package. This also serves 556 // as the lock for the global state. Methods that must be called with 557 // this lock held have the prefix "LP". 558 @GuardedBy("mPackages") 559 final ArrayMap<String, PackageParser.Package> mPackages = 560 new ArrayMap<String, PackageParser.Package>(); 561 562 final ArrayMap<String, Set<String>> mKnownCodebase = 563 new ArrayMap<String, Set<String>>(); 564 565 // Tracks available target package names -> overlay package paths. 566 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 567 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 568 569 /** 570 * Tracks new system packages [received in an OTA] that we expect to 571 * find updated user-installed versions. Keys are package name, values 572 * are package location. 573 */ 574 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 575 /** 576 * Tracks high priority intent filters for protected actions. During boot, certain 577 * filter actions are protected and should never be allowed to have a high priority 578 * intent filter for them. However, there is one, and only one exception -- the 579 * setup wizard. It must be able to define a high priority intent filter for these 580 * actions to ensure there are no escapes from the wizard. We need to delay processing 581 * of these during boot as we need to look at all of the system packages in order 582 * to know which component is the setup wizard. 583 */ 584 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 585 /** 586 * Whether or not processing protected filters should be deferred. 587 */ 588 private boolean mDeferProtectedFilters = true; 589 590 /** 591 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 592 */ 593 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 594 /** 595 * Whether or not system app permissions should be promoted from install to runtime. 596 */ 597 boolean mPromoteSystemApps; 598 599 @GuardedBy("mPackages") 600 final Settings mSettings; 601 602 /** 603 * Set of package names that are currently "frozen", which means active 604 * surgery is being done on the code/data for that package. The platform 605 * will refuse to launch frozen packages to avoid race conditions. 606 * 607 * @see PackageFreezer 608 */ 609 @GuardedBy("mPackages") 610 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 611 612 boolean mRestoredSettings; 613 614 // System configuration read by SystemConfig. 615 final int[] mGlobalGids; 616 final SparseArray<ArraySet<String>> mSystemPermissions; 617 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 618 619 // If mac_permissions.xml was found for seinfo labeling. 620 boolean mFoundPolicyFile; 621 622 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 623 624 public static final class SharedLibraryEntry { 625 public final String path; 626 public final String apk; 627 628 SharedLibraryEntry(String _path, String _apk) { 629 path = _path; 630 apk = _apk; 631 } 632 } 633 634 // Currently known shared libraries. 635 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 636 new ArrayMap<String, SharedLibraryEntry>(); 637 638 // All available activities, for your resolving pleasure. 639 final ActivityIntentResolver mActivities = 640 new ActivityIntentResolver(); 641 642 // All available receivers, for your resolving pleasure. 643 final ActivityIntentResolver mReceivers = 644 new ActivityIntentResolver(); 645 646 // All available services, for your resolving pleasure. 647 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 648 649 // All available providers, for your resolving pleasure. 650 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 651 652 // Mapping from provider base names (first directory in content URI codePath) 653 // to the provider information. 654 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 655 new ArrayMap<String, PackageParser.Provider>(); 656 657 // Mapping from instrumentation class names to info about them. 658 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 659 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 660 661 // Mapping from permission names to info about them. 662 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 663 new ArrayMap<String, PackageParser.PermissionGroup>(); 664 665 // Packages whose data we have transfered into another package, thus 666 // should no longer exist. 667 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 668 669 // Broadcast actions that are only available to the system. 670 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 671 672 /** List of packages waiting for verification. */ 673 final SparseArray<PackageVerificationState> mPendingVerification 674 = new SparseArray<PackageVerificationState>(); 675 676 /** Set of packages associated with each app op permission. */ 677 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 678 679 final PackageInstallerService mInstallerService; 680 681 private final PackageDexOptimizer mPackageDexOptimizer; 682 683 private AtomicInteger mNextMoveId = new AtomicInteger(); 684 private final MoveCallbacks mMoveCallbacks; 685 686 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 687 688 // Cache of users who need badging. 689 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 690 691 /** Token for keys in mPendingVerification. */ 692 private int mPendingVerificationToken = 0; 693 694 volatile boolean mSystemReady; 695 volatile boolean mSafeMode; 696 volatile boolean mHasSystemUidErrors; 697 698 ApplicationInfo mAndroidApplication; 699 final ActivityInfo mResolveActivity = new ActivityInfo(); 700 final ResolveInfo mResolveInfo = new ResolveInfo(); 701 ComponentName mResolveComponentName; 702 PackageParser.Package mPlatformPackage; 703 ComponentName mCustomResolverComponentName; 704 705 boolean mResolverReplaced = false; 706 707 private final @Nullable ComponentName mIntentFilterVerifierComponent; 708 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 709 710 private int mIntentFilterVerificationToken = 0; 711 712 /** Component that knows whether or not an ephemeral application exists */ 713 final ComponentName mEphemeralResolverComponent; 714 /** The service connection to the ephemeral resolver */ 715 final EphemeralResolverConnection mEphemeralResolverConnection; 716 717 /** Component used to install ephemeral applications */ 718 final ComponentName mEphemeralInstallerComponent; 719 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 720 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 721 722 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 723 = new SparseArray<IntentFilterVerificationState>(); 724 725 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 726 new DefaultPermissionGrantPolicy(this); 727 728 // List of packages names to keep cached, even if they are uninstalled for all users 729 private List<String> mKeepUninstalledPackages; 730 731 private static class IFVerificationParams { 732 PackageParser.Package pkg; 733 boolean replacing; 734 int userId; 735 int verifierUid; 736 737 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 738 int _userId, int _verifierUid) { 739 pkg = _pkg; 740 replacing = _replacing; 741 userId = _userId; 742 replacing = _replacing; 743 verifierUid = _verifierUid; 744 } 745 } 746 747 private interface IntentFilterVerifier<T extends IntentFilter> { 748 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 749 T filter, String packageName); 750 void startVerifications(int userId); 751 void receiveVerificationResponse(int verificationId); 752 } 753 754 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 755 private Context mContext; 756 private ComponentName mIntentFilterVerifierComponent; 757 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 758 759 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 760 mContext = context; 761 mIntentFilterVerifierComponent = verifierComponent; 762 } 763 764 private String getDefaultScheme() { 765 return IntentFilter.SCHEME_HTTPS; 766 } 767 768 @Override 769 public void startVerifications(int userId) { 770 // Launch verifications requests 771 int count = mCurrentIntentFilterVerifications.size(); 772 for (int n=0; n<count; n++) { 773 int verificationId = mCurrentIntentFilterVerifications.get(n); 774 final IntentFilterVerificationState ivs = 775 mIntentFilterVerificationStates.get(verificationId); 776 777 String packageName = ivs.getPackageName(); 778 779 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 780 final int filterCount = filters.size(); 781 ArraySet<String> domainsSet = new ArraySet<>(); 782 for (int m=0; m<filterCount; m++) { 783 PackageParser.ActivityIntentInfo filter = filters.get(m); 784 domainsSet.addAll(filter.getHostsList()); 785 } 786 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 787 synchronized (mPackages) { 788 if (mSettings.createIntentFilterVerificationIfNeededLPw( 789 packageName, domainsList) != null) { 790 scheduleWriteSettingsLocked(); 791 } 792 } 793 sendVerificationRequest(userId, verificationId, ivs); 794 } 795 mCurrentIntentFilterVerifications.clear(); 796 } 797 798 private void sendVerificationRequest(int userId, int verificationId, 799 IntentFilterVerificationState ivs) { 800 801 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 802 verificationIntent.putExtra( 803 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 804 verificationId); 805 verificationIntent.putExtra( 806 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 807 getDefaultScheme()); 808 verificationIntent.putExtra( 809 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 810 ivs.getHostsString()); 811 verificationIntent.putExtra( 812 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 813 ivs.getPackageName()); 814 verificationIntent.setComponent(mIntentFilterVerifierComponent); 815 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 816 817 UserHandle user = new UserHandle(userId); 818 mContext.sendBroadcastAsUser(verificationIntent, user); 819 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 820 "Sending IntentFilter verification broadcast"); 821 } 822 823 public void receiveVerificationResponse(int verificationId) { 824 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 825 826 final boolean verified = ivs.isVerified(); 827 828 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 829 final int count = filters.size(); 830 if (DEBUG_DOMAIN_VERIFICATION) { 831 Slog.i(TAG, "Received verification response " + verificationId 832 + " for " + count + " filters, verified=" + verified); 833 } 834 for (int n=0; n<count; n++) { 835 PackageParser.ActivityIntentInfo filter = filters.get(n); 836 filter.setVerified(verified); 837 838 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 839 + " verified with result:" + verified + " and hosts:" 840 + ivs.getHostsString()); 841 } 842 843 mIntentFilterVerificationStates.remove(verificationId); 844 845 final String packageName = ivs.getPackageName(); 846 IntentFilterVerificationInfo ivi = null; 847 848 synchronized (mPackages) { 849 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 850 } 851 if (ivi == null) { 852 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 853 + verificationId + " packageName:" + packageName); 854 return; 855 } 856 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 857 "Updating IntentFilterVerificationInfo for package " + packageName 858 +" verificationId:" + verificationId); 859 860 synchronized (mPackages) { 861 if (verified) { 862 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 863 } else { 864 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 865 } 866 scheduleWriteSettingsLocked(); 867 868 final int userId = ivs.getUserId(); 869 if (userId != UserHandle.USER_ALL) { 870 final int userStatus = 871 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 872 873 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 874 boolean needUpdate = false; 875 876 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 877 // already been set by the User thru the Disambiguation dialog 878 switch (userStatus) { 879 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 880 if (verified) { 881 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 882 } else { 883 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 884 } 885 needUpdate = true; 886 break; 887 888 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 889 if (verified) { 890 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 891 needUpdate = true; 892 } 893 break; 894 895 default: 896 // Nothing to do 897 } 898 899 if (needUpdate) { 900 mSettings.updateIntentFilterVerificationStatusLPw( 901 packageName, updatedStatus, userId); 902 scheduleWritePackageRestrictionsLocked(userId); 903 } 904 } 905 } 906 } 907 908 @Override 909 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 910 ActivityIntentInfo filter, String packageName) { 911 if (!hasValidDomains(filter)) { 912 return false; 913 } 914 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 915 if (ivs == null) { 916 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 917 packageName); 918 } 919 if (DEBUG_DOMAIN_VERIFICATION) { 920 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 921 } 922 ivs.addFilter(filter); 923 return true; 924 } 925 926 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 927 int userId, int verificationId, String packageName) { 928 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 929 verifierUid, userId, packageName); 930 ivs.setPendingState(); 931 synchronized (mPackages) { 932 mIntentFilterVerificationStates.append(verificationId, ivs); 933 mCurrentIntentFilterVerifications.add(verificationId); 934 } 935 return ivs; 936 } 937 } 938 939 private static boolean hasValidDomains(ActivityIntentInfo filter) { 940 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 941 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 942 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 943 } 944 945 // Set of pending broadcasts for aggregating enable/disable of components. 946 static class PendingPackageBroadcasts { 947 // for each user id, a map of <package name -> components within that package> 948 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 949 950 public PendingPackageBroadcasts() { 951 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 952 } 953 954 public ArrayList<String> get(int userId, String packageName) { 955 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 956 return packages.get(packageName); 957 } 958 959 public void put(int userId, String packageName, ArrayList<String> components) { 960 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 961 packages.put(packageName, components); 962 } 963 964 public void remove(int userId, String packageName) { 965 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 966 if (packages != null) { 967 packages.remove(packageName); 968 } 969 } 970 971 public void remove(int userId) { 972 mUidMap.remove(userId); 973 } 974 975 public int userIdCount() { 976 return mUidMap.size(); 977 } 978 979 public int userIdAt(int n) { 980 return mUidMap.keyAt(n); 981 } 982 983 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 984 return mUidMap.get(userId); 985 } 986 987 public int size() { 988 // total number of pending broadcast entries across all userIds 989 int num = 0; 990 for (int i = 0; i< mUidMap.size(); i++) { 991 num += mUidMap.valueAt(i).size(); 992 } 993 return num; 994 } 995 996 public void clear() { 997 mUidMap.clear(); 998 } 999 1000 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1001 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1002 if (map == null) { 1003 map = new ArrayMap<String, ArrayList<String>>(); 1004 mUidMap.put(userId, map); 1005 } 1006 return map; 1007 } 1008 } 1009 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1010 1011 // Service Connection to remote media container service to copy 1012 // package uri's from external media onto secure containers 1013 // or internal storage. 1014 private IMediaContainerService mContainerService = null; 1015 1016 static final int SEND_PENDING_BROADCAST = 1; 1017 static final int MCS_BOUND = 3; 1018 static final int END_COPY = 4; 1019 static final int INIT_COPY = 5; 1020 static final int MCS_UNBIND = 6; 1021 static final int START_CLEANING_PACKAGE = 7; 1022 static final int FIND_INSTALL_LOC = 8; 1023 static final int POST_INSTALL = 9; 1024 static final int MCS_RECONNECT = 10; 1025 static final int MCS_GIVE_UP = 11; 1026 static final int UPDATED_MEDIA_STATUS = 12; 1027 static final int WRITE_SETTINGS = 13; 1028 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1029 static final int PACKAGE_VERIFIED = 15; 1030 static final int CHECK_PENDING_VERIFICATION = 16; 1031 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1032 static final int INTENT_FILTER_VERIFIED = 18; 1033 1034 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1035 1036 // Delay time in millisecs 1037 static final int BROADCAST_DELAY = 10 * 1000; 1038 1039 static UserManagerService sUserManager; 1040 1041 // Stores a list of users whose package restrictions file needs to be updated 1042 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1043 1044 final private DefaultContainerConnection mDefContainerConn = 1045 new DefaultContainerConnection(); 1046 class DefaultContainerConnection implements ServiceConnection { 1047 public void onServiceConnected(ComponentName name, IBinder service) { 1048 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1049 IMediaContainerService imcs = 1050 IMediaContainerService.Stub.asInterface(service); 1051 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1052 } 1053 1054 public void onServiceDisconnected(ComponentName name) { 1055 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1056 } 1057 } 1058 1059 // Recordkeeping of restore-after-install operations that are currently in flight 1060 // between the Package Manager and the Backup Manager 1061 static class PostInstallData { 1062 public InstallArgs args; 1063 public PackageInstalledInfo res; 1064 1065 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1066 args = _a; 1067 res = _r; 1068 } 1069 } 1070 1071 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1072 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1073 1074 // XML tags for backup/restore of various bits of state 1075 private static final String TAG_PREFERRED_BACKUP = "pa"; 1076 private static final String TAG_DEFAULT_APPS = "da"; 1077 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1078 1079 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1080 private static final String TAG_ALL_GRANTS = "rt-grants"; 1081 private static final String TAG_GRANT = "grant"; 1082 private static final String ATTR_PACKAGE_NAME = "pkg"; 1083 1084 private static final String TAG_PERMISSION = "perm"; 1085 private static final String ATTR_PERMISSION_NAME = "name"; 1086 private static final String ATTR_IS_GRANTED = "g"; 1087 private static final String ATTR_USER_SET = "set"; 1088 private static final String ATTR_USER_FIXED = "fixed"; 1089 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1090 1091 // System/policy permission grants are not backed up 1092 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1093 FLAG_PERMISSION_POLICY_FIXED 1094 | FLAG_PERMISSION_SYSTEM_FIXED 1095 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1096 1097 // And we back up these user-adjusted states 1098 private static final int USER_RUNTIME_GRANT_MASK = 1099 FLAG_PERMISSION_USER_SET 1100 | FLAG_PERMISSION_USER_FIXED 1101 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1102 1103 final @Nullable String mRequiredVerifierPackage; 1104 final @NonNull String mRequiredInstallerPackage; 1105 final @Nullable String mSetupWizardPackage; 1106 final @NonNull String mServicesSystemSharedLibraryPackageName; 1107 final @NonNull String mSharedSystemSharedLibraryPackageName; 1108 1109 private final PackageUsage mPackageUsage = new PackageUsage(); 1110 1111 private class PackageUsage { 1112 private static final int WRITE_INTERVAL 1113 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 1114 1115 private final Object mFileLock = new Object(); 1116 private final AtomicLong mLastWritten = new AtomicLong(0); 1117 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 1118 1119 private boolean mIsHistoricalPackageUsageAvailable = true; 1120 1121 boolean isHistoricalPackageUsageAvailable() { 1122 return mIsHistoricalPackageUsageAvailable; 1123 } 1124 1125 void write(boolean force) { 1126 if (force) { 1127 writeInternal(); 1128 return; 1129 } 1130 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 1131 && !DEBUG_DEXOPT) { 1132 return; 1133 } 1134 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 1135 new Thread("PackageUsage_DiskWriter") { 1136 @Override 1137 public void run() { 1138 try { 1139 writeInternal(); 1140 } finally { 1141 mBackgroundWriteRunning.set(false); 1142 } 1143 } 1144 }.start(); 1145 } 1146 } 1147 1148 private void writeInternal() { 1149 synchronized (mPackages) { 1150 synchronized (mFileLock) { 1151 AtomicFile file = getFile(); 1152 FileOutputStream f = null; 1153 try { 1154 f = file.startWrite(); 1155 BufferedOutputStream out = new BufferedOutputStream(f); 1156 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1157 StringBuilder sb = new StringBuilder(); 1158 for (PackageParser.Package pkg : mPackages.values()) { 1159 if (pkg.mLastPackageUsageTimeInMills == 0) { 1160 continue; 1161 } 1162 sb.setLength(0); 1163 sb.append(pkg.packageName); 1164 sb.append(' '); 1165 sb.append((long)pkg.mLastPackageUsageTimeInMills); 1166 sb.append('\n'); 1167 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1168 } 1169 out.flush(); 1170 file.finishWrite(f); 1171 } catch (IOException e) { 1172 if (f != null) { 1173 file.failWrite(f); 1174 } 1175 Log.e(TAG, "Failed to write package usage times", e); 1176 } 1177 } 1178 } 1179 mLastWritten.set(SystemClock.elapsedRealtime()); 1180 } 1181 1182 void readLP() { 1183 synchronized (mFileLock) { 1184 AtomicFile file = getFile(); 1185 BufferedInputStream in = null; 1186 try { 1187 in = new BufferedInputStream(file.openRead()); 1188 StringBuffer sb = new StringBuffer(); 1189 while (true) { 1190 String packageName = readToken(in, sb, ' '); 1191 if (packageName == null) { 1192 break; 1193 } 1194 String timeInMillisString = readToken(in, sb, '\n'); 1195 if (timeInMillisString == null) { 1196 throw new IOException("Failed to find last usage time for package " 1197 + packageName); 1198 } 1199 PackageParser.Package pkg = mPackages.get(packageName); 1200 if (pkg == null) { 1201 continue; 1202 } 1203 long timeInMillis; 1204 try { 1205 timeInMillis = Long.parseLong(timeInMillisString); 1206 } catch (NumberFormatException e) { 1207 throw new IOException("Failed to parse " + timeInMillisString 1208 + " as a long.", e); 1209 } 1210 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1211 } 1212 } catch (FileNotFoundException expected) { 1213 mIsHistoricalPackageUsageAvailable = false; 1214 } catch (IOException e) { 1215 Log.w(TAG, "Failed to read package usage times", e); 1216 } finally { 1217 IoUtils.closeQuietly(in); 1218 } 1219 } 1220 mLastWritten.set(SystemClock.elapsedRealtime()); 1221 } 1222 1223 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1224 throws IOException { 1225 sb.setLength(0); 1226 while (true) { 1227 int ch = in.read(); 1228 if (ch == -1) { 1229 if (sb.length() == 0) { 1230 return null; 1231 } 1232 throw new IOException("Unexpected EOF"); 1233 } 1234 if (ch == endOfToken) { 1235 return sb.toString(); 1236 } 1237 sb.append((char)ch); 1238 } 1239 } 1240 1241 private AtomicFile getFile() { 1242 File dataDir = Environment.getDataDirectory(); 1243 File systemDir = new File(dataDir, "system"); 1244 File fname = new File(systemDir, "package-usage.list"); 1245 return new AtomicFile(fname); 1246 } 1247 } 1248 1249 class PackageHandler extends Handler { 1250 private boolean mBound = false; 1251 final ArrayList<HandlerParams> mPendingInstalls = 1252 new ArrayList<HandlerParams>(); 1253 1254 private boolean connectToService() { 1255 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1256 " DefaultContainerService"); 1257 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1258 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1259 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1260 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1261 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1262 mBound = true; 1263 return true; 1264 } 1265 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1266 return false; 1267 } 1268 1269 private void disconnectService() { 1270 mContainerService = null; 1271 mBound = false; 1272 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1273 mContext.unbindService(mDefContainerConn); 1274 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1275 } 1276 1277 PackageHandler(Looper looper) { 1278 super(looper); 1279 } 1280 1281 public void handleMessage(Message msg) { 1282 try { 1283 doHandleMessage(msg); 1284 } finally { 1285 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1286 } 1287 } 1288 1289 void doHandleMessage(Message msg) { 1290 switch (msg.what) { 1291 case INIT_COPY: { 1292 HandlerParams params = (HandlerParams) msg.obj; 1293 int idx = mPendingInstalls.size(); 1294 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1295 // If a bind was already initiated we dont really 1296 // need to do anything. The pending install 1297 // will be processed later on. 1298 if (!mBound) { 1299 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1300 System.identityHashCode(mHandler)); 1301 // If this is the only one pending we might 1302 // have to bind to the service again. 1303 if (!connectToService()) { 1304 Slog.e(TAG, "Failed to bind to media container service"); 1305 params.serviceError(); 1306 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1307 System.identityHashCode(mHandler)); 1308 if (params.traceMethod != null) { 1309 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1310 params.traceCookie); 1311 } 1312 return; 1313 } else { 1314 // Once we bind to the service, the first 1315 // pending request will be processed. 1316 mPendingInstalls.add(idx, params); 1317 } 1318 } else { 1319 mPendingInstalls.add(idx, params); 1320 // Already bound to the service. Just make 1321 // sure we trigger off processing the first request. 1322 if (idx == 0) { 1323 mHandler.sendEmptyMessage(MCS_BOUND); 1324 } 1325 } 1326 break; 1327 } 1328 case MCS_BOUND: { 1329 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1330 if (msg.obj != null) { 1331 mContainerService = (IMediaContainerService) msg.obj; 1332 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1333 System.identityHashCode(mHandler)); 1334 } 1335 if (mContainerService == null) { 1336 if (!mBound) { 1337 // Something seriously wrong since we are not bound and we are not 1338 // waiting for connection. Bail out. 1339 Slog.e(TAG, "Cannot bind to media container service"); 1340 for (HandlerParams params : mPendingInstalls) { 1341 // Indicate service bind error 1342 params.serviceError(); 1343 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1344 System.identityHashCode(params)); 1345 if (params.traceMethod != null) { 1346 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1347 params.traceMethod, params.traceCookie); 1348 } 1349 return; 1350 } 1351 mPendingInstalls.clear(); 1352 } else { 1353 Slog.w(TAG, "Waiting to connect to media container service"); 1354 } 1355 } else if (mPendingInstalls.size() > 0) { 1356 HandlerParams params = mPendingInstalls.get(0); 1357 if (params != null) { 1358 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1359 System.identityHashCode(params)); 1360 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1361 if (params.startCopy()) { 1362 // We are done... look for more work or to 1363 // go idle. 1364 if (DEBUG_SD_INSTALL) Log.i(TAG, 1365 "Checking for more work or unbind..."); 1366 // Delete pending install 1367 if (mPendingInstalls.size() > 0) { 1368 mPendingInstalls.remove(0); 1369 } 1370 if (mPendingInstalls.size() == 0) { 1371 if (mBound) { 1372 if (DEBUG_SD_INSTALL) Log.i(TAG, 1373 "Posting delayed MCS_UNBIND"); 1374 removeMessages(MCS_UNBIND); 1375 Message ubmsg = obtainMessage(MCS_UNBIND); 1376 // Unbind after a little delay, to avoid 1377 // continual thrashing. 1378 sendMessageDelayed(ubmsg, 10000); 1379 } 1380 } else { 1381 // There are more pending requests in queue. 1382 // Just post MCS_BOUND message to trigger processing 1383 // of next pending install. 1384 if (DEBUG_SD_INSTALL) Log.i(TAG, 1385 "Posting MCS_BOUND for next work"); 1386 mHandler.sendEmptyMessage(MCS_BOUND); 1387 } 1388 } 1389 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1390 } 1391 } else { 1392 // Should never happen ideally. 1393 Slog.w(TAG, "Empty queue"); 1394 } 1395 break; 1396 } 1397 case MCS_RECONNECT: { 1398 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1399 if (mPendingInstalls.size() > 0) { 1400 if (mBound) { 1401 disconnectService(); 1402 } 1403 if (!connectToService()) { 1404 Slog.e(TAG, "Failed to bind to media container service"); 1405 for (HandlerParams params : mPendingInstalls) { 1406 // Indicate service bind error 1407 params.serviceError(); 1408 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1409 System.identityHashCode(params)); 1410 } 1411 mPendingInstalls.clear(); 1412 } 1413 } 1414 break; 1415 } 1416 case MCS_UNBIND: { 1417 // If there is no actual work left, then time to unbind. 1418 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1419 1420 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1421 if (mBound) { 1422 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1423 1424 disconnectService(); 1425 } 1426 } else if (mPendingInstalls.size() > 0) { 1427 // There are more pending requests in queue. 1428 // Just post MCS_BOUND message to trigger processing 1429 // of next pending install. 1430 mHandler.sendEmptyMessage(MCS_BOUND); 1431 } 1432 1433 break; 1434 } 1435 case MCS_GIVE_UP: { 1436 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1437 HandlerParams params = mPendingInstalls.remove(0); 1438 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1439 System.identityHashCode(params)); 1440 break; 1441 } 1442 case SEND_PENDING_BROADCAST: { 1443 String packages[]; 1444 ArrayList<String> components[]; 1445 int size = 0; 1446 int uids[]; 1447 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1448 synchronized (mPackages) { 1449 if (mPendingBroadcasts == null) { 1450 return; 1451 } 1452 size = mPendingBroadcasts.size(); 1453 if (size <= 0) { 1454 // Nothing to be done. Just return 1455 return; 1456 } 1457 packages = new String[size]; 1458 components = new ArrayList[size]; 1459 uids = new int[size]; 1460 int i = 0; // filling out the above arrays 1461 1462 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1463 int packageUserId = mPendingBroadcasts.userIdAt(n); 1464 Iterator<Map.Entry<String, ArrayList<String>>> it 1465 = mPendingBroadcasts.packagesForUserId(packageUserId) 1466 .entrySet().iterator(); 1467 while (it.hasNext() && i < size) { 1468 Map.Entry<String, ArrayList<String>> ent = it.next(); 1469 packages[i] = ent.getKey(); 1470 components[i] = ent.getValue(); 1471 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1472 uids[i] = (ps != null) 1473 ? UserHandle.getUid(packageUserId, ps.appId) 1474 : -1; 1475 i++; 1476 } 1477 } 1478 size = i; 1479 mPendingBroadcasts.clear(); 1480 } 1481 // Send broadcasts 1482 for (int i = 0; i < size; i++) { 1483 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1484 } 1485 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1486 break; 1487 } 1488 case START_CLEANING_PACKAGE: { 1489 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1490 final String packageName = (String)msg.obj; 1491 final int userId = msg.arg1; 1492 final boolean andCode = msg.arg2 != 0; 1493 synchronized (mPackages) { 1494 if (userId == UserHandle.USER_ALL) { 1495 int[] users = sUserManager.getUserIds(); 1496 for (int user : users) { 1497 mSettings.addPackageToCleanLPw( 1498 new PackageCleanItem(user, packageName, andCode)); 1499 } 1500 } else { 1501 mSettings.addPackageToCleanLPw( 1502 new PackageCleanItem(userId, packageName, andCode)); 1503 } 1504 } 1505 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1506 startCleaningPackages(); 1507 } break; 1508 case POST_INSTALL: { 1509 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1510 1511 PostInstallData data = mRunningInstalls.get(msg.arg1); 1512 mRunningInstalls.delete(msg.arg1); 1513 1514 if (data != null) { 1515 InstallArgs args = data.args; 1516 PackageInstalledInfo parentRes = data.res; 1517 1518 final boolean grantPermissions = (args.installFlags 1519 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1520 final boolean killApp = (args.installFlags 1521 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1522 final String[] grantedPermissions = args.installGrantPermissions; 1523 1524 // Handle the parent package 1525 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1526 grantedPermissions, args.observer); 1527 1528 // Handle the child packages 1529 final int childCount = (parentRes.addedChildPackages != null) 1530 ? parentRes.addedChildPackages.size() : 0; 1531 for (int i = 0; i < childCount; i++) { 1532 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1533 handlePackagePostInstall(childRes, grantPermissions, killApp, 1534 grantedPermissions, args.observer); 1535 } 1536 1537 // Log tracing if needed 1538 if (args.traceMethod != null) { 1539 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1540 args.traceCookie); 1541 } 1542 } else { 1543 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1544 } 1545 1546 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1547 } break; 1548 case UPDATED_MEDIA_STATUS: { 1549 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1550 boolean reportStatus = msg.arg1 == 1; 1551 boolean doGc = msg.arg2 == 1; 1552 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1553 if (doGc) { 1554 // Force a gc to clear up stale containers. 1555 Runtime.getRuntime().gc(); 1556 } 1557 if (msg.obj != null) { 1558 @SuppressWarnings("unchecked") 1559 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1560 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1561 // Unload containers 1562 unloadAllContainers(args); 1563 } 1564 if (reportStatus) { 1565 try { 1566 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1567 PackageHelper.getMountService().finishMediaUpdate(); 1568 } catch (RemoteException e) { 1569 Log.e(TAG, "MountService not running?"); 1570 } 1571 } 1572 } break; 1573 case WRITE_SETTINGS: { 1574 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1575 synchronized (mPackages) { 1576 removeMessages(WRITE_SETTINGS); 1577 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1578 mSettings.writeLPr(); 1579 mDirtyUsers.clear(); 1580 } 1581 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1582 } break; 1583 case WRITE_PACKAGE_RESTRICTIONS: { 1584 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1585 synchronized (mPackages) { 1586 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1587 for (int userId : mDirtyUsers) { 1588 mSettings.writePackageRestrictionsLPr(userId); 1589 } 1590 mDirtyUsers.clear(); 1591 } 1592 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1593 } break; 1594 case CHECK_PENDING_VERIFICATION: { 1595 final int verificationId = msg.arg1; 1596 final PackageVerificationState state = mPendingVerification.get(verificationId); 1597 1598 if ((state != null) && !state.timeoutExtended()) { 1599 final InstallArgs args = state.getInstallArgs(); 1600 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1601 1602 Slog.i(TAG, "Verification timed out for " + originUri); 1603 mPendingVerification.remove(verificationId); 1604 1605 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1606 1607 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1608 Slog.i(TAG, "Continuing with installation of " + originUri); 1609 state.setVerifierResponse(Binder.getCallingUid(), 1610 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1611 broadcastPackageVerified(verificationId, originUri, 1612 PackageManager.VERIFICATION_ALLOW, 1613 state.getInstallArgs().getUser()); 1614 try { 1615 ret = args.copyApk(mContainerService, true); 1616 } catch (RemoteException e) { 1617 Slog.e(TAG, "Could not contact the ContainerService"); 1618 } 1619 } else { 1620 broadcastPackageVerified(verificationId, originUri, 1621 PackageManager.VERIFICATION_REJECT, 1622 state.getInstallArgs().getUser()); 1623 } 1624 1625 Trace.asyncTraceEnd( 1626 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1627 1628 processPendingInstall(args, ret); 1629 mHandler.sendEmptyMessage(MCS_UNBIND); 1630 } 1631 break; 1632 } 1633 case PACKAGE_VERIFIED: { 1634 final int verificationId = msg.arg1; 1635 1636 final PackageVerificationState state = mPendingVerification.get(verificationId); 1637 if (state == null) { 1638 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1639 break; 1640 } 1641 1642 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1643 1644 state.setVerifierResponse(response.callerUid, response.code); 1645 1646 if (state.isVerificationComplete()) { 1647 mPendingVerification.remove(verificationId); 1648 1649 final InstallArgs args = state.getInstallArgs(); 1650 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1651 1652 int ret; 1653 if (state.isInstallAllowed()) { 1654 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1655 broadcastPackageVerified(verificationId, originUri, 1656 response.code, state.getInstallArgs().getUser()); 1657 try { 1658 ret = args.copyApk(mContainerService, true); 1659 } catch (RemoteException e) { 1660 Slog.e(TAG, "Could not contact the ContainerService"); 1661 } 1662 } else { 1663 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1664 } 1665 1666 Trace.asyncTraceEnd( 1667 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1668 1669 processPendingInstall(args, ret); 1670 mHandler.sendEmptyMessage(MCS_UNBIND); 1671 } 1672 1673 break; 1674 } 1675 case START_INTENT_FILTER_VERIFICATIONS: { 1676 IFVerificationParams params = (IFVerificationParams) msg.obj; 1677 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1678 params.replacing, params.pkg); 1679 break; 1680 } 1681 case INTENT_FILTER_VERIFIED: { 1682 final int verificationId = msg.arg1; 1683 1684 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1685 verificationId); 1686 if (state == null) { 1687 Slog.w(TAG, "Invalid IntentFilter verification token " 1688 + verificationId + " received"); 1689 break; 1690 } 1691 1692 final int userId = state.getUserId(); 1693 1694 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1695 "Processing IntentFilter verification with token:" 1696 + verificationId + " and userId:" + userId); 1697 1698 final IntentFilterVerificationResponse response = 1699 (IntentFilterVerificationResponse) msg.obj; 1700 1701 state.setVerifierResponse(response.callerUid, response.code); 1702 1703 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1704 "IntentFilter verification with token:" + verificationId 1705 + " and userId:" + userId 1706 + " is settings verifier response with response code:" 1707 + response.code); 1708 1709 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1710 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1711 + response.getFailedDomainsString()); 1712 } 1713 1714 if (state.isVerificationComplete()) { 1715 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1716 } else { 1717 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1718 "IntentFilter verification with token:" + verificationId 1719 + " was not said to be complete"); 1720 } 1721 1722 break; 1723 } 1724 } 1725 } 1726 } 1727 1728 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1729 boolean killApp, String[] grantedPermissions, 1730 IPackageInstallObserver2 installObserver) { 1731 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1732 // Send the removed broadcasts 1733 if (res.removedInfo != null) { 1734 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1735 } 1736 1737 // Now that we successfully installed the package, grant runtime 1738 // permissions if requested before broadcasting the install. 1739 if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion 1740 >= Build.VERSION_CODES.M) { 1741 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1742 } 1743 1744 final boolean update = res.removedInfo != null 1745 && res.removedInfo.removedPackage != null; 1746 1747 // If this is the first time we have child packages for a disabled privileged 1748 // app that had no children, we grant requested runtime permissions to the new 1749 // children if the parent on the system image had them already granted. 1750 if (res.pkg.parentPackage != null) { 1751 synchronized (mPackages) { 1752 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1753 } 1754 } 1755 1756 synchronized (mPackages) { 1757 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1758 } 1759 1760 final String packageName = res.pkg.applicationInfo.packageName; 1761 Bundle extras = new Bundle(1); 1762 extras.putInt(Intent.EXTRA_UID, res.uid); 1763 1764 // Determine the set of users who are adding this package for 1765 // the first time vs. those who are seeing an update. 1766 int[] firstUsers = EMPTY_INT_ARRAY; 1767 int[] updateUsers = EMPTY_INT_ARRAY; 1768 if (res.origUsers == null || res.origUsers.length == 0) { 1769 firstUsers = res.newUsers; 1770 } else { 1771 for (int newUser : res.newUsers) { 1772 boolean isNew = true; 1773 for (int origUser : res.origUsers) { 1774 if (origUser == newUser) { 1775 isNew = false; 1776 break; 1777 } 1778 } 1779 if (isNew) { 1780 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1781 } else { 1782 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1783 } 1784 } 1785 } 1786 1787 // Send installed broadcasts if the install/update is not ephemeral 1788 if (!isEphemeral(res.pkg)) { 1789 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1790 1791 // Send added for users that see the package for the first time 1792 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1793 extras, 0 /*flags*/, null /*targetPackage*/, 1794 null /*finishedReceiver*/, firstUsers); 1795 1796 // Send added for users that don't see the package for the first time 1797 if (update) { 1798 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1799 } 1800 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1801 extras, 0 /*flags*/, null /*targetPackage*/, 1802 null /*finishedReceiver*/, updateUsers); 1803 1804 // Send replaced for users that don't see the package for the first time 1805 if (update) { 1806 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1807 packageName, extras, 0 /*flags*/, 1808 null /*targetPackage*/, null /*finishedReceiver*/, 1809 updateUsers); 1810 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1811 null /*package*/, null /*extras*/, 0 /*flags*/, 1812 packageName /*targetPackage*/, 1813 null /*finishedReceiver*/, updateUsers); 1814 } 1815 1816 // Send broadcast package appeared if forward locked/external for all users 1817 // treat asec-hosted packages like removable media on upgrade 1818 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1819 if (DEBUG_INSTALL) { 1820 Slog.i(TAG, "upgrading pkg " + res.pkg 1821 + " is ASEC-hosted -> AVAILABLE"); 1822 } 1823 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1824 ArrayList<String> pkgList = new ArrayList<>(1); 1825 pkgList.add(packageName); 1826 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1827 } 1828 } 1829 1830 // Work that needs to happen on first install within each user 1831 if (firstUsers != null && firstUsers.length > 0) { 1832 synchronized (mPackages) { 1833 for (int userId : firstUsers) { 1834 // If this app is a browser and it's newly-installed for some 1835 // users, clear any default-browser state in those users. The 1836 // app's nature doesn't depend on the user, so we can just check 1837 // its browser nature in any user and generalize. 1838 if (packageIsBrowser(packageName, userId)) { 1839 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1840 } 1841 1842 // We may also need to apply pending (restored) runtime 1843 // permission grants within these users. 1844 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1845 } 1846 } 1847 } 1848 1849 // Log current value of "unknown sources" setting 1850 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1851 getUnknownSourcesSettings()); 1852 1853 // Force a gc to clear up things 1854 Runtime.getRuntime().gc(); 1855 1856 // Remove the replaced package's older resources safely now 1857 // We delete after a gc for applications on sdcard. 1858 if (res.removedInfo != null && res.removedInfo.args != null) { 1859 synchronized (mInstallLock) { 1860 res.removedInfo.args.doPostDeleteLI(true); 1861 } 1862 } 1863 } 1864 1865 // If someone is watching installs - notify them 1866 if (installObserver != null) { 1867 try { 1868 Bundle extras = extrasForInstallResult(res); 1869 installObserver.onPackageInstalled(res.name, res.returnCode, 1870 res.returnMsg, extras); 1871 } catch (RemoteException e) { 1872 Slog.i(TAG, "Observer no longer exists."); 1873 } 1874 } 1875 } 1876 1877 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1878 PackageParser.Package pkg) { 1879 if (pkg.parentPackage == null) { 1880 return; 1881 } 1882 if (pkg.requestedPermissions == null) { 1883 return; 1884 } 1885 final PackageSetting disabledSysParentPs = mSettings 1886 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1887 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1888 || !disabledSysParentPs.isPrivileged() 1889 || (disabledSysParentPs.childPackageNames != null 1890 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1891 return; 1892 } 1893 final int[] allUserIds = sUserManager.getUserIds(); 1894 final int permCount = pkg.requestedPermissions.size(); 1895 for (int i = 0; i < permCount; i++) { 1896 String permission = pkg.requestedPermissions.get(i); 1897 BasePermission bp = mSettings.mPermissions.get(permission); 1898 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1899 continue; 1900 } 1901 for (int userId : allUserIds) { 1902 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1903 permission, userId)) { 1904 grantRuntimePermission(pkg.packageName, permission, userId); 1905 } 1906 } 1907 } 1908 } 1909 1910 private StorageEventListener mStorageListener = new StorageEventListener() { 1911 @Override 1912 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1913 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1914 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1915 final String volumeUuid = vol.getFsUuid(); 1916 1917 // Clean up any users or apps that were removed or recreated 1918 // while this volume was missing 1919 reconcileUsers(volumeUuid); 1920 reconcileApps(volumeUuid); 1921 1922 // Clean up any install sessions that expired or were 1923 // cancelled while this volume was missing 1924 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1925 1926 loadPrivatePackages(vol); 1927 1928 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1929 unloadPrivatePackages(vol); 1930 } 1931 } 1932 1933 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1934 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1935 updateExternalMediaStatus(true, false); 1936 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1937 updateExternalMediaStatus(false, false); 1938 } 1939 } 1940 } 1941 1942 @Override 1943 public void onVolumeForgotten(String fsUuid) { 1944 if (TextUtils.isEmpty(fsUuid)) { 1945 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1946 return; 1947 } 1948 1949 // Remove any apps installed on the forgotten volume 1950 synchronized (mPackages) { 1951 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1952 for (PackageSetting ps : packages) { 1953 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1954 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1955 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 1956 } 1957 1958 mSettings.onVolumeForgotten(fsUuid); 1959 mSettings.writeLPr(); 1960 } 1961 } 1962 }; 1963 1964 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 1965 String[] grantedPermissions) { 1966 for (int userId : userIds) { 1967 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1968 } 1969 1970 // We could have touched GID membership, so flush out packages.list 1971 synchronized (mPackages) { 1972 mSettings.writePackageListLPr(); 1973 } 1974 } 1975 1976 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1977 String[] grantedPermissions) { 1978 SettingBase sb = (SettingBase) pkg.mExtras; 1979 if (sb == null) { 1980 return; 1981 } 1982 1983 PermissionsState permissionsState = sb.getPermissionsState(); 1984 1985 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 1986 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 1987 1988 synchronized (mPackages) { 1989 for (String permission : pkg.requestedPermissions) { 1990 BasePermission bp = mSettings.mPermissions.get(permission); 1991 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 1992 && (grantedPermissions == null 1993 || ArrayUtils.contains(grantedPermissions, permission))) { 1994 final int flags = permissionsState.getPermissionFlags(permission, userId); 1995 // Installer cannot change immutable permissions. 1996 if ((flags & immutableFlags) == 0) { 1997 grantRuntimePermission(pkg.packageName, permission, userId); 1998 } 1999 } 2000 } 2001 } 2002 } 2003 2004 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2005 Bundle extras = null; 2006 switch (res.returnCode) { 2007 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2008 extras = new Bundle(); 2009 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2010 res.origPermission); 2011 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2012 res.origPackage); 2013 break; 2014 } 2015 case PackageManager.INSTALL_SUCCEEDED: { 2016 extras = new Bundle(); 2017 extras.putBoolean(Intent.EXTRA_REPLACING, 2018 res.removedInfo != null && res.removedInfo.removedPackage != null); 2019 break; 2020 } 2021 } 2022 return extras; 2023 } 2024 2025 void scheduleWriteSettingsLocked() { 2026 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2027 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2028 } 2029 } 2030 2031 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2032 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2033 scheduleWritePackageRestrictionsLocked(userId); 2034 } 2035 2036 void scheduleWritePackageRestrictionsLocked(int userId) { 2037 final int[] userIds = (userId == UserHandle.USER_ALL) 2038 ? sUserManager.getUserIds() : new int[]{userId}; 2039 for (int nextUserId : userIds) { 2040 if (!sUserManager.exists(nextUserId)) return; 2041 mDirtyUsers.add(nextUserId); 2042 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2043 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2044 } 2045 } 2046 } 2047 2048 public static PackageManagerService main(Context context, Installer installer, 2049 boolean factoryTest, boolean onlyCore) { 2050 // Self-check for initial settings. 2051 PackageManagerServiceCompilerMapping.checkProperties(); 2052 2053 PackageManagerService m = new PackageManagerService(context, installer, 2054 factoryTest, onlyCore); 2055 m.enableSystemUserPackages(); 2056 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 2057 // disabled after already being started. 2058 CarrierAppUtils.disableCarrierAppsUntilPrivileged(context.getOpPackageName(), m, 2059 UserHandle.USER_SYSTEM); 2060 ServiceManager.addService("package", m); 2061 return m; 2062 } 2063 2064 private void enableSystemUserPackages() { 2065 if (!UserManager.isSplitSystemUser()) { 2066 return; 2067 } 2068 // For system user, enable apps based on the following conditions: 2069 // - app is whitelisted or belong to one of these groups: 2070 // -- system app which has no launcher icons 2071 // -- system app which has INTERACT_ACROSS_USERS permission 2072 // -- system IME app 2073 // - app is not in the blacklist 2074 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2075 Set<String> enableApps = new ArraySet<>(); 2076 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2077 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2078 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2079 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2080 enableApps.addAll(wlApps); 2081 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2082 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2083 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2084 enableApps.removeAll(blApps); 2085 Log.i(TAG, "Applications installed for system user: " + enableApps); 2086 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2087 UserHandle.SYSTEM); 2088 final int allAppsSize = allAps.size(); 2089 synchronized (mPackages) { 2090 for (int i = 0; i < allAppsSize; i++) { 2091 String pName = allAps.get(i); 2092 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2093 // Should not happen, but we shouldn't be failing if it does 2094 if (pkgSetting == null) { 2095 continue; 2096 } 2097 boolean install = enableApps.contains(pName); 2098 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2099 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2100 + " for system user"); 2101 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2102 } 2103 } 2104 } 2105 } 2106 2107 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2108 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2109 Context.DISPLAY_SERVICE); 2110 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2111 } 2112 2113 public PackageManagerService(Context context, Installer installer, 2114 boolean factoryTest, boolean onlyCore) { 2115 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2116 SystemClock.uptimeMillis()); 2117 2118 if (mSdkVersion <= 0) { 2119 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2120 } 2121 2122 mContext = context; 2123 mFactoryTest = factoryTest; 2124 mOnlyCore = onlyCore; 2125 mMetrics = new DisplayMetrics(); 2126 mSettings = new Settings(mPackages); 2127 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2128 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2129 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2130 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2131 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2132 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2133 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2134 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2135 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2136 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2137 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2138 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2139 2140 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2141 if (separateProcesses != null && separateProcesses.length() > 0) { 2142 if ("*".equals(separateProcesses)) { 2143 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2144 mSeparateProcesses = null; 2145 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2146 } else { 2147 mDefParseFlags = 0; 2148 mSeparateProcesses = separateProcesses.split(","); 2149 Slog.w(TAG, "Running with debug.separate_processes: " 2150 + separateProcesses); 2151 } 2152 } else { 2153 mDefParseFlags = 0; 2154 mSeparateProcesses = null; 2155 } 2156 2157 mInstaller = installer; 2158 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2159 "*dexopt*"); 2160 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2161 2162 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2163 FgThread.get().getLooper()); 2164 2165 getDefaultDisplayMetrics(context, mMetrics); 2166 2167 SystemConfig systemConfig = SystemConfig.getInstance(); 2168 mGlobalGids = systemConfig.getGlobalGids(); 2169 mSystemPermissions = systemConfig.getSystemPermissions(); 2170 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2171 2172 synchronized (mInstallLock) { 2173 // writer 2174 synchronized (mPackages) { 2175 mHandlerThread = new ServiceThread(TAG, 2176 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2177 mHandlerThread.start(); 2178 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2179 mProcessLoggingHandler = new ProcessLoggingHandler(); 2180 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2181 2182 File dataDir = Environment.getDataDirectory(); 2183 mAppInstallDir = new File(dataDir, "app"); 2184 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2185 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2186 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2187 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2188 2189 sUserManager = new UserManagerService(context, this, mPackages); 2190 2191 // Propagate permission configuration in to package manager. 2192 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2193 = systemConfig.getPermissions(); 2194 for (int i=0; i<permConfig.size(); i++) { 2195 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2196 BasePermission bp = mSettings.mPermissions.get(perm.name); 2197 if (bp == null) { 2198 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2199 mSettings.mPermissions.put(perm.name, bp); 2200 } 2201 if (perm.gids != null) { 2202 bp.setGids(perm.gids, perm.perUser); 2203 } 2204 } 2205 2206 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2207 for (int i=0; i<libConfig.size(); i++) { 2208 mSharedLibraries.put(libConfig.keyAt(i), 2209 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2210 } 2211 2212 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2213 2214 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 2215 2216 String customResolverActivity = Resources.getSystem().getString( 2217 R.string.config_customResolverActivity); 2218 if (TextUtils.isEmpty(customResolverActivity)) { 2219 customResolverActivity = null; 2220 } else { 2221 mCustomResolverComponentName = ComponentName.unflattenFromString( 2222 customResolverActivity); 2223 } 2224 2225 long startTime = SystemClock.uptimeMillis(); 2226 2227 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2228 startTime); 2229 2230 // Set flag to monitor and not change apk file paths when 2231 // scanning install directories. 2232 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2233 2234 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2235 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2236 2237 if (bootClassPath == null) { 2238 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2239 } 2240 2241 if (systemServerClassPath == null) { 2242 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2243 } 2244 2245 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2246 final String[] dexCodeInstructionSets = 2247 getDexCodeInstructionSets( 2248 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2249 2250 /** 2251 * Ensure all external libraries have had dexopt run on them. 2252 */ 2253 if (mSharedLibraries.size() > 0) { 2254 // NOTE: For now, we're compiling these system "shared libraries" 2255 // (and framework jars) into all available architectures. It's possible 2256 // to compile them only when we come across an app that uses them (there's 2257 // already logic for that in scanPackageLI) but that adds some complexity. 2258 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2259 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2260 final String lib = libEntry.path; 2261 if (lib == null) { 2262 continue; 2263 } 2264 2265 try { 2266 // Shared libraries do not have profiles so we perform a full 2267 // AOT compilation (if needed). 2268 int dexoptNeeded = DexFile.getDexOptNeeded( 2269 lib, dexCodeInstructionSet, 2270 getCompilerFilterForReason(REASON_SHARED_APK), 2271 false /* newProfile */); 2272 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2273 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2274 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/, 2275 getCompilerFilterForReason(REASON_SHARED_APK), 2276 StorageManager.UUID_PRIVATE_INTERNAL); 2277 } 2278 } catch (FileNotFoundException e) { 2279 Slog.w(TAG, "Library not found: " + lib); 2280 } catch (IOException | InstallerException e) { 2281 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2282 + e.getMessage()); 2283 } 2284 } 2285 } 2286 } 2287 2288 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2289 2290 final VersionInfo ver = mSettings.getInternalVersion(); 2291 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2292 2293 // when upgrading from pre-M, promote system app permissions from install to runtime 2294 mPromoteSystemApps = 2295 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2296 2297 // save off the names of pre-existing system packages prior to scanning; we don't 2298 // want to automatically grant runtime permissions for new system apps 2299 if (mPromoteSystemApps) { 2300 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2301 while (pkgSettingIter.hasNext()) { 2302 PackageSetting ps = pkgSettingIter.next(); 2303 if (isSystemApp(ps)) { 2304 mExistingSystemPackages.add(ps.name); 2305 } 2306 } 2307 } 2308 2309 // When upgrading from pre-N, we need to handle package extraction like first boot, 2310 // as there is no profiling data available. 2311 mIsPreNUpgrade = !mSettings.isNWorkDone(); 2312 mSettings.setNWorkDone(); 2313 2314 // Collect vendor overlay packages. 2315 // (Do this before scanning any apps.) 2316 // For security and version matching reason, only consider 2317 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2318 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2319 scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 2320 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2321 2322 // Find base frameworks (resource packages without code). 2323 scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 2324 | PackageParser.PARSE_IS_SYSTEM_DIR 2325 | PackageParser.PARSE_IS_PRIVILEGED, 2326 scanFlags | SCAN_NO_DEX, 0); 2327 2328 // Collected privileged system packages. 2329 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2330 scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 2331 | PackageParser.PARSE_IS_SYSTEM_DIR 2332 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2333 2334 // Collect ordinary system packages. 2335 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2336 scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2337 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2338 2339 // Collect all vendor packages. 2340 File vendorAppDir = new File("/vendor/app"); 2341 try { 2342 vendorAppDir = vendorAppDir.getCanonicalFile(); 2343 } catch (IOException e) { 2344 // failed to look up canonical path, continue with original one 2345 } 2346 scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2347 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2348 2349 // Collect all OEM packages. 2350 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2351 scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2352 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2353 2354 // Prune any system packages that no longer exist. 2355 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2356 if (!mOnlyCore) { 2357 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2358 while (psit.hasNext()) { 2359 PackageSetting ps = psit.next(); 2360 2361 /* 2362 * If this is not a system app, it can't be a 2363 * disable system app. 2364 */ 2365 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2366 continue; 2367 } 2368 2369 /* 2370 * If the package is scanned, it's not erased. 2371 */ 2372 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2373 if (scannedPkg != null) { 2374 /* 2375 * If the system app is both scanned and in the 2376 * disabled packages list, then it must have been 2377 * added via OTA. Remove it from the currently 2378 * scanned package so the previously user-installed 2379 * application can be scanned. 2380 */ 2381 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2382 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2383 + ps.name + "; removing system app. Last known codePath=" 2384 + ps.codePathString + ", installStatus=" + ps.installStatus 2385 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2386 + scannedPkg.mVersionCode); 2387 removePackageLI(scannedPkg, true); 2388 mExpectingBetter.put(ps.name, ps.codePath); 2389 } 2390 2391 continue; 2392 } 2393 2394 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2395 psit.remove(); 2396 logCriticalInfo(Log.WARN, "System package " + ps.name 2397 + " no longer exists; it's data will be wiped"); 2398 // Actual deletion of code and data will be handled by later 2399 // reconciliation step 2400 } else { 2401 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2402 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2403 possiblyDeletedUpdatedSystemApps.add(ps.name); 2404 } 2405 } 2406 } 2407 } 2408 2409 //look for any incomplete package installations 2410 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2411 for (int i = 0; i < deletePkgsList.size(); i++) { 2412 // Actual deletion of code and data will be handled by later 2413 // reconciliation step 2414 final String packageName = deletePkgsList.get(i).name; 2415 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2416 synchronized (mPackages) { 2417 mSettings.removePackageLPw(packageName); 2418 } 2419 } 2420 2421 //delete tmp files 2422 deleteTempPackageFiles(); 2423 2424 // Remove any shared userIDs that have no associated packages 2425 mSettings.pruneSharedUsersLPw(); 2426 2427 if (!mOnlyCore) { 2428 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2429 SystemClock.uptimeMillis()); 2430 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2431 2432 scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2433 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2434 2435 scanDirLI(mEphemeralInstallDir, PackageParser.PARSE_IS_EPHEMERAL, 2436 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2437 2438 /** 2439 * Remove disable package settings for any updated system 2440 * apps that were removed via an OTA. If they're not a 2441 * previously-updated app, remove them completely. 2442 * Otherwise, just revoke their system-level permissions. 2443 */ 2444 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2445 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2446 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2447 2448 String msg; 2449 if (deletedPkg == null) { 2450 msg = "Updated system package " + deletedAppName 2451 + " no longer exists; it's data will be wiped"; 2452 // Actual deletion of code and data will be handled by later 2453 // reconciliation step 2454 } else { 2455 msg = "Updated system app + " + deletedAppName 2456 + " no longer present; removing system privileges for " 2457 + deletedAppName; 2458 2459 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2460 2461 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2462 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2463 } 2464 logCriticalInfo(Log.WARN, msg); 2465 } 2466 2467 /** 2468 * Make sure all system apps that we expected to appear on 2469 * the userdata partition actually showed up. If they never 2470 * appeared, crawl back and revive the system version. 2471 */ 2472 for (int i = 0; i < mExpectingBetter.size(); i++) { 2473 final String packageName = mExpectingBetter.keyAt(i); 2474 if (!mPackages.containsKey(packageName)) { 2475 final File scanFile = mExpectingBetter.valueAt(i); 2476 2477 logCriticalInfo(Log.WARN, "Expected better " + packageName 2478 + " but never showed up; reverting to system"); 2479 2480 final int reparseFlags; 2481 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2482 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2483 | PackageParser.PARSE_IS_SYSTEM_DIR 2484 | PackageParser.PARSE_IS_PRIVILEGED; 2485 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2486 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2487 | PackageParser.PARSE_IS_SYSTEM_DIR; 2488 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2489 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2490 | PackageParser.PARSE_IS_SYSTEM_DIR; 2491 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2492 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2493 | PackageParser.PARSE_IS_SYSTEM_DIR; 2494 } else { 2495 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2496 continue; 2497 } 2498 2499 mSettings.enableSystemPackageLPw(packageName); 2500 2501 try { 2502 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2503 } catch (PackageManagerException e) { 2504 Slog.e(TAG, "Failed to parse original system package: " 2505 + e.getMessage()); 2506 } 2507 } 2508 } 2509 } 2510 mExpectingBetter.clear(); 2511 2512 // Resolve protected action filters. Only the setup wizard is allowed to 2513 // have a high priority filter for these actions. 2514 mSetupWizardPackage = getSetupWizardPackageName(); 2515 if (mProtectedFilters.size() > 0) { 2516 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2517 Slog.i(TAG, "No setup wizard;" 2518 + " All protected intents capped to priority 0"); 2519 } 2520 for (ActivityIntentInfo filter : mProtectedFilters) { 2521 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2522 if (DEBUG_FILTERS) { 2523 Slog.i(TAG, "Found setup wizard;" 2524 + " allow priority " + filter.getPriority() + ";" 2525 + " package: " + filter.activity.info.packageName 2526 + " activity: " + filter.activity.className 2527 + " priority: " + filter.getPriority()); 2528 } 2529 // skip setup wizard; allow it to keep the high priority filter 2530 continue; 2531 } 2532 Slog.w(TAG, "Protected action; cap priority to 0;" 2533 + " package: " + filter.activity.info.packageName 2534 + " activity: " + filter.activity.className 2535 + " origPrio: " + filter.getPriority()); 2536 filter.setPriority(0); 2537 } 2538 } 2539 mDeferProtectedFilters = false; 2540 mProtectedFilters.clear(); 2541 2542 // Now that we know all of the shared libraries, update all clients to have 2543 // the correct library paths. 2544 updateAllSharedLibrariesLPw(); 2545 2546 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2547 // NOTE: We ignore potential failures here during a system scan (like 2548 // the rest of the commands above) because there's precious little we 2549 // can do about it. A settings error is reported, though. 2550 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2551 false /* boot complete */); 2552 } 2553 2554 // Now that we know all the packages we are keeping, 2555 // read and update their last usage times. 2556 mPackageUsage.readLP(); 2557 2558 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2559 SystemClock.uptimeMillis()); 2560 Slog.i(TAG, "Time to scan packages: " 2561 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2562 + " seconds"); 2563 2564 // If the platform SDK has changed since the last time we booted, 2565 // we need to re-grant app permission to catch any new ones that 2566 // appear. This is really a hack, and means that apps can in some 2567 // cases get permissions that the user didn't initially explicitly 2568 // allow... it would be nice to have some better way to handle 2569 // this situation. 2570 int updateFlags = UPDATE_PERMISSIONS_ALL; 2571 if (ver.sdkVersion != mSdkVersion) { 2572 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2573 + mSdkVersion + "; regranting permissions for internal storage"); 2574 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2575 } 2576 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2577 ver.sdkVersion = mSdkVersion; 2578 2579 // If this is the first boot or an update from pre-M, and it is a normal 2580 // boot, then we need to initialize the default preferred apps across 2581 // all defined users. 2582 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2583 for (UserInfo user : sUserManager.getUsers(true)) { 2584 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2585 applyFactoryDefaultBrowserLPw(user.id); 2586 primeDomainVerificationsLPw(user.id); 2587 } 2588 } 2589 2590 // Prepare storage for system user really early during boot, 2591 // since core system apps like SettingsProvider and SystemUI 2592 // can't wait for user to start 2593 final int storageFlags; 2594 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2595 storageFlags = StorageManager.FLAG_STORAGE_DE; 2596 } else { 2597 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2598 } 2599 reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2600 storageFlags); 2601 2602 // If this is first boot after an OTA, and a normal boot, then 2603 // we need to clear code cache directories. 2604 if (mIsUpgrade && !onlyCore) { 2605 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2606 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2607 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2608 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2609 // No apps are running this early, so no need to freeze 2610 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2611 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2612 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2613 } 2614 clearAppProfilesLIF(ps.pkg); 2615 } 2616 ver.fingerprint = Build.FINGERPRINT; 2617 } 2618 2619 checkDefaultBrowser(); 2620 2621 // clear only after permissions and other defaults have been updated 2622 mExistingSystemPackages.clear(); 2623 mPromoteSystemApps = false; 2624 2625 // All the changes are done during package scanning. 2626 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2627 2628 // can downgrade to reader 2629 mSettings.writeLPr(); 2630 2631 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2632 SystemClock.uptimeMillis()); 2633 2634 if (!mOnlyCore) { 2635 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2636 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2637 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2638 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2639 mIntentFilterVerifierComponent); 2640 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2641 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 2642 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2643 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED); 2644 } else { 2645 mRequiredVerifierPackage = null; 2646 mRequiredInstallerPackage = null; 2647 mIntentFilterVerifierComponent = null; 2648 mIntentFilterVerifier = null; 2649 mServicesSystemSharedLibraryPackageName = null; 2650 mSharedSystemSharedLibraryPackageName = null; 2651 } 2652 2653 mInstallerService = new PackageInstallerService(context, this); 2654 2655 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2656 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2657 // both the installer and resolver must be present to enable ephemeral 2658 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2659 if (DEBUG_EPHEMERAL) { 2660 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2661 + " installer:" + ephemeralInstallerComponent); 2662 } 2663 mEphemeralResolverComponent = ephemeralResolverComponent; 2664 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2665 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2666 mEphemeralResolverConnection = 2667 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2668 } else { 2669 if (DEBUG_EPHEMERAL) { 2670 final String missingComponent = 2671 (ephemeralResolverComponent == null) 2672 ? (ephemeralInstallerComponent == null) 2673 ? "resolver and installer" 2674 : "resolver" 2675 : "installer"; 2676 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2677 } 2678 mEphemeralResolverComponent = null; 2679 mEphemeralInstallerComponent = null; 2680 mEphemeralResolverConnection = null; 2681 } 2682 2683 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2684 } // synchronized (mPackages) 2685 } // synchronized (mInstallLock) 2686 2687 // Now after opening every single application zip, make sure they 2688 // are all flushed. Not really needed, but keeps things nice and 2689 // tidy. 2690 Runtime.getRuntime().gc(); 2691 2692 // The initial scanning above does many calls into installd while 2693 // holding the mPackages lock, but we're mostly interested in yelling 2694 // once we have a booted system. 2695 mInstaller.setWarnIfHeld(mPackages); 2696 2697 // Expose private service for system components to use. 2698 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2699 } 2700 2701 @Override 2702 public boolean isFirstBoot() { 2703 return !mRestoredSettings; 2704 } 2705 2706 @Override 2707 public boolean isOnlyCoreApps() { 2708 return mOnlyCore; 2709 } 2710 2711 @Override 2712 public boolean isUpgrade() { 2713 return mIsUpgrade; 2714 } 2715 2716 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2717 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2718 2719 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2720 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2721 UserHandle.USER_SYSTEM); 2722 if (matches.size() == 1) { 2723 return matches.get(0).getComponentInfo().packageName; 2724 } else { 2725 Log.e(TAG, "There should probably be exactly one verifier; found " + matches); 2726 return null; 2727 } 2728 } 2729 2730 private @NonNull String getRequiredSharedLibraryLPr(String libraryName) { 2731 synchronized (mPackages) { 2732 SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName); 2733 if (libraryEntry == null) { 2734 throw new IllegalStateException("Missing required shared library:" + libraryName); 2735 } 2736 return libraryEntry.apk; 2737 } 2738 } 2739 2740 private @NonNull String getRequiredInstallerLPr() { 2741 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2742 intent.addCategory(Intent.CATEGORY_DEFAULT); 2743 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2744 2745 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2746 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2747 UserHandle.USER_SYSTEM); 2748 if (matches.size() == 1) { 2749 ResolveInfo resolveInfo = matches.get(0); 2750 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 2751 throw new RuntimeException("The installer must be a privileged app"); 2752 } 2753 return matches.get(0).getComponentInfo().packageName; 2754 } else { 2755 throw new RuntimeException("There must be exactly one installer; found " + matches); 2756 } 2757 } 2758 2759 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2760 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2761 2762 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2763 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2764 UserHandle.USER_SYSTEM); 2765 ResolveInfo best = null; 2766 final int N = matches.size(); 2767 for (int i = 0; i < N; i++) { 2768 final ResolveInfo cur = matches.get(i); 2769 final String packageName = cur.getComponentInfo().packageName; 2770 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2771 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2772 continue; 2773 } 2774 2775 if (best == null || cur.priority > best.priority) { 2776 best = cur; 2777 } 2778 } 2779 2780 if (best != null) { 2781 return best.getComponentInfo().getComponentName(); 2782 } else { 2783 throw new RuntimeException("There must be at least one intent filter verifier"); 2784 } 2785 } 2786 2787 private @Nullable ComponentName getEphemeralResolverLPr() { 2788 final String[] packageArray = 2789 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2790 if (packageArray.length == 0) { 2791 if (DEBUG_EPHEMERAL) { 2792 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2793 } 2794 return null; 2795 } 2796 2797 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2798 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 2799 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2800 UserHandle.USER_SYSTEM); 2801 2802 final int N = resolvers.size(); 2803 if (N == 0) { 2804 if (DEBUG_EPHEMERAL) { 2805 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2806 } 2807 return null; 2808 } 2809 2810 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2811 for (int i = 0; i < N; i++) { 2812 final ResolveInfo info = resolvers.get(i); 2813 2814 if (info.serviceInfo == null) { 2815 continue; 2816 } 2817 2818 final String packageName = info.serviceInfo.packageName; 2819 if (!possiblePackages.contains(packageName)) { 2820 if (DEBUG_EPHEMERAL) { 2821 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2822 + " pkg: " + packageName + ", info:" + info); 2823 } 2824 continue; 2825 } 2826 2827 if (DEBUG_EPHEMERAL) { 2828 Slog.v(TAG, "Ephemeral resolver found;" 2829 + " pkg: " + packageName + ", info:" + info); 2830 } 2831 return new ComponentName(packageName, info.serviceInfo.name); 2832 } 2833 if (DEBUG_EPHEMERAL) { 2834 Slog.v(TAG, "Ephemeral resolver NOT found"); 2835 } 2836 return null; 2837 } 2838 2839 private @Nullable ComponentName getEphemeralInstallerLPr() { 2840 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2841 intent.addCategory(Intent.CATEGORY_DEFAULT); 2842 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2843 2844 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2845 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2846 UserHandle.USER_SYSTEM); 2847 if (matches.size() == 0) { 2848 return null; 2849 } else if (matches.size() == 1) { 2850 return matches.get(0).getComponentInfo().getComponentName(); 2851 } else { 2852 throw new RuntimeException( 2853 "There must be at most one ephemeral installer; found " + matches); 2854 } 2855 } 2856 2857 private void primeDomainVerificationsLPw(int userId) { 2858 if (DEBUG_DOMAIN_VERIFICATION) { 2859 Slog.d(TAG, "Priming domain verifications in user " + userId); 2860 } 2861 2862 SystemConfig systemConfig = SystemConfig.getInstance(); 2863 ArraySet<String> packages = systemConfig.getLinkedApps(); 2864 ArraySet<String> domains = new ArraySet<String>(); 2865 2866 for (String packageName : packages) { 2867 PackageParser.Package pkg = mPackages.get(packageName); 2868 if (pkg != null) { 2869 if (!pkg.isSystemApp()) { 2870 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2871 continue; 2872 } 2873 2874 domains.clear(); 2875 for (PackageParser.Activity a : pkg.activities) { 2876 for (ActivityIntentInfo filter : a.intents) { 2877 if (hasValidDomains(filter)) { 2878 domains.addAll(filter.getHostsList()); 2879 } 2880 } 2881 } 2882 2883 if (domains.size() > 0) { 2884 if (DEBUG_DOMAIN_VERIFICATION) { 2885 Slog.v(TAG, " + " + packageName); 2886 } 2887 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2888 // state w.r.t. the formal app-linkage "no verification attempted" state; 2889 // and then 'always' in the per-user state actually used for intent resolution. 2890 final IntentFilterVerificationInfo ivi; 2891 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2892 new ArrayList<String>(domains)); 2893 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2894 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2895 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2896 } else { 2897 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2898 + "' does not handle web links"); 2899 } 2900 } else { 2901 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 2902 } 2903 } 2904 2905 scheduleWritePackageRestrictionsLocked(userId); 2906 scheduleWriteSettingsLocked(); 2907 } 2908 2909 private void applyFactoryDefaultBrowserLPw(int userId) { 2910 // The default browser app's package name is stored in a string resource, 2911 // with a product-specific overlay used for vendor customization. 2912 String browserPkg = mContext.getResources().getString( 2913 com.android.internal.R.string.default_browser); 2914 if (!TextUtils.isEmpty(browserPkg)) { 2915 // non-empty string => required to be a known package 2916 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2917 if (ps == null) { 2918 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2919 browserPkg = null; 2920 } else { 2921 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2922 } 2923 } 2924 2925 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2926 // default. If there's more than one, just leave everything alone. 2927 if (browserPkg == null) { 2928 calculateDefaultBrowserLPw(userId); 2929 } 2930 } 2931 2932 private void calculateDefaultBrowserLPw(int userId) { 2933 List<String> allBrowsers = resolveAllBrowserApps(userId); 2934 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2935 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2936 } 2937 2938 private List<String> resolveAllBrowserApps(int userId) { 2939 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2940 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 2941 PackageManager.MATCH_ALL, userId); 2942 2943 final int count = list.size(); 2944 List<String> result = new ArrayList<String>(count); 2945 for (int i=0; i<count; i++) { 2946 ResolveInfo info = list.get(i); 2947 if (info.activityInfo == null 2948 || !info.handleAllWebDataURI 2949 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2950 || result.contains(info.activityInfo.packageName)) { 2951 continue; 2952 } 2953 result.add(info.activityInfo.packageName); 2954 } 2955 2956 return result; 2957 } 2958 2959 private boolean packageIsBrowser(String packageName, int userId) { 2960 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 2961 PackageManager.MATCH_ALL, userId); 2962 final int N = list.size(); 2963 for (int i = 0; i < N; i++) { 2964 ResolveInfo info = list.get(i); 2965 if (packageName.equals(info.activityInfo.packageName)) { 2966 return true; 2967 } 2968 } 2969 return false; 2970 } 2971 2972 private void checkDefaultBrowser() { 2973 final int myUserId = UserHandle.myUserId(); 2974 final String packageName = getDefaultBrowserPackageName(myUserId); 2975 if (packageName != null) { 2976 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2977 if (info == null) { 2978 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2979 synchronized (mPackages) { 2980 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2981 } 2982 } 2983 } 2984 } 2985 2986 @Override 2987 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2988 throws RemoteException { 2989 try { 2990 return super.onTransact(code, data, reply, flags); 2991 } catch (RuntimeException e) { 2992 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2993 Slog.wtf(TAG, "Package Manager Crash", e); 2994 } 2995 throw e; 2996 } 2997 } 2998 2999 static int[] appendInts(int[] cur, int[] add) { 3000 if (add == null) return cur; 3001 if (cur == null) return add; 3002 final int N = add.length; 3003 for (int i=0; i<N; i++) { 3004 cur = appendInt(cur, add[i]); 3005 } 3006 return cur; 3007 } 3008 3009 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3010 if (!sUserManager.exists(userId)) return null; 3011 if (ps == null) { 3012 return null; 3013 } 3014 final PackageParser.Package p = ps.pkg; 3015 if (p == null) { 3016 return null; 3017 } 3018 3019 final PermissionsState permissionsState = ps.getPermissionsState(); 3020 3021 final int[] gids = permissionsState.computeGids(userId); 3022 final Set<String> permissions = permissionsState.getPermissions(userId); 3023 final PackageUserState state = ps.readUserState(userId); 3024 3025 return PackageParser.generatePackageInfo(p, gids, flags, 3026 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3027 } 3028 3029 @Override 3030 public void checkPackageStartable(String packageName, int userId) { 3031 final boolean userKeyUnlocked = isUserKeyUnlocked(userId); 3032 3033 synchronized (mPackages) { 3034 final PackageSetting ps = mSettings.mPackages.get(packageName); 3035 if (ps == null) { 3036 throw new SecurityException("Package " + packageName + " was not found!"); 3037 } 3038 3039 if (!ps.getInstalled(userId)) { 3040 throw new SecurityException( 3041 "Package " + packageName + " was not installed for user " + userId + "!"); 3042 } 3043 3044 if (mSafeMode && !ps.isSystem()) { 3045 throw new SecurityException("Package " + packageName + " not a system app!"); 3046 } 3047 3048 if (mFrozenPackages.contains(packageName)) { 3049 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3050 } 3051 3052 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3053 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3054 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3055 } 3056 } 3057 } 3058 3059 @Override 3060 public boolean isPackageAvailable(String packageName, int userId) { 3061 if (!sUserManager.exists(userId)) return false; 3062 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3063 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3064 synchronized (mPackages) { 3065 PackageParser.Package p = mPackages.get(packageName); 3066 if (p != null) { 3067 final PackageSetting ps = (PackageSetting) p.mExtras; 3068 if (ps != null) { 3069 final PackageUserState state = ps.readUserState(userId); 3070 if (state != null) { 3071 return PackageParser.isAvailable(state); 3072 } 3073 } 3074 } 3075 } 3076 return false; 3077 } 3078 3079 @Override 3080 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3081 if (!sUserManager.exists(userId)) return null; 3082 flags = updateFlagsForPackage(flags, userId, packageName); 3083 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3084 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3085 // reader 3086 synchronized (mPackages) { 3087 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3088 PackageParser.Package p = null; 3089 if (matchFactoryOnly) { 3090 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3091 if (ps != null) { 3092 return generatePackageInfo(ps, flags, userId); 3093 } 3094 } 3095 if (p == null) { 3096 p = mPackages.get(packageName); 3097 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3098 return null; 3099 } 3100 } 3101 if (DEBUG_PACKAGE_INFO) 3102 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3103 if (p != null) { 3104 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3105 } 3106 if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3107 final PackageSetting ps = mSettings.mPackages.get(packageName); 3108 return generatePackageInfo(ps, flags, userId); 3109 } 3110 } 3111 return null; 3112 } 3113 3114 @Override 3115 public String[] currentToCanonicalPackageNames(String[] names) { 3116 String[] out = new String[names.length]; 3117 // reader 3118 synchronized (mPackages) { 3119 for (int i=names.length-1; i>=0; i--) { 3120 PackageSetting ps = mSettings.mPackages.get(names[i]); 3121 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3122 } 3123 } 3124 return out; 3125 } 3126 3127 @Override 3128 public String[] canonicalToCurrentPackageNames(String[] names) { 3129 String[] out = new String[names.length]; 3130 // reader 3131 synchronized (mPackages) { 3132 for (int i=names.length-1; i>=0; i--) { 3133 String cur = mSettings.mRenamedPackages.get(names[i]); 3134 out[i] = cur != null ? cur : names[i]; 3135 } 3136 } 3137 return out; 3138 } 3139 3140 @Override 3141 public int getPackageUid(String packageName, int flags, int userId) { 3142 if (!sUserManager.exists(userId)) return -1; 3143 flags = updateFlagsForPackage(flags, userId, packageName); 3144 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3145 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3146 3147 // reader 3148 synchronized (mPackages) { 3149 final PackageParser.Package p = mPackages.get(packageName); 3150 if (p != null && p.isMatch(flags)) { 3151 return UserHandle.getUid(userId, p.applicationInfo.uid); 3152 } 3153 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3154 final PackageSetting ps = mSettings.mPackages.get(packageName); 3155 if (ps != null && ps.isMatch(flags)) { 3156 return UserHandle.getUid(userId, ps.appId); 3157 } 3158 } 3159 } 3160 3161 return -1; 3162 } 3163 3164 @Override 3165 public int[] getPackageGids(String packageName, int flags, int userId) { 3166 if (!sUserManager.exists(userId)) return null; 3167 flags = updateFlagsForPackage(flags, userId, packageName); 3168 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3169 false /* requireFullPermission */, false /* checkShell */, 3170 "getPackageGids"); 3171 3172 // reader 3173 synchronized (mPackages) { 3174 final PackageParser.Package p = mPackages.get(packageName); 3175 if (p != null && p.isMatch(flags)) { 3176 PackageSetting ps = (PackageSetting) p.mExtras; 3177 return ps.getPermissionsState().computeGids(userId); 3178 } 3179 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3180 final PackageSetting ps = mSettings.mPackages.get(packageName); 3181 if (ps != null && ps.isMatch(flags)) { 3182 return ps.getPermissionsState().computeGids(userId); 3183 } 3184 } 3185 } 3186 3187 return null; 3188 } 3189 3190 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3191 if (bp.perm != null) { 3192 return PackageParser.generatePermissionInfo(bp.perm, flags); 3193 } 3194 PermissionInfo pi = new PermissionInfo(); 3195 pi.name = bp.name; 3196 pi.packageName = bp.sourcePackage; 3197 pi.nonLocalizedLabel = bp.name; 3198 pi.protectionLevel = bp.protectionLevel; 3199 return pi; 3200 } 3201 3202 @Override 3203 public PermissionInfo getPermissionInfo(String name, int flags) { 3204 // reader 3205 synchronized (mPackages) { 3206 final BasePermission p = mSettings.mPermissions.get(name); 3207 if (p != null) { 3208 return generatePermissionInfo(p, flags); 3209 } 3210 return null; 3211 } 3212 } 3213 3214 @Override 3215 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3216 int flags) { 3217 // reader 3218 synchronized (mPackages) { 3219 if (group != null && !mPermissionGroups.containsKey(group)) { 3220 // This is thrown as NameNotFoundException 3221 return null; 3222 } 3223 3224 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3225 for (BasePermission p : mSettings.mPermissions.values()) { 3226 if (group == null) { 3227 if (p.perm == null || p.perm.info.group == null) { 3228 out.add(generatePermissionInfo(p, flags)); 3229 } 3230 } else { 3231 if (p.perm != null && group.equals(p.perm.info.group)) { 3232 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3233 } 3234 } 3235 } 3236 return new ParceledListSlice<>(out); 3237 } 3238 } 3239 3240 @Override 3241 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3242 // reader 3243 synchronized (mPackages) { 3244 return PackageParser.generatePermissionGroupInfo( 3245 mPermissionGroups.get(name), flags); 3246 } 3247 } 3248 3249 @Override 3250 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3251 // reader 3252 synchronized (mPackages) { 3253 final int N = mPermissionGroups.size(); 3254 ArrayList<PermissionGroupInfo> out 3255 = new ArrayList<PermissionGroupInfo>(N); 3256 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3257 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3258 } 3259 return new ParceledListSlice<>(out); 3260 } 3261 } 3262 3263 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3264 int userId) { 3265 if (!sUserManager.exists(userId)) return null; 3266 PackageSetting ps = mSettings.mPackages.get(packageName); 3267 if (ps != null) { 3268 if (ps.pkg == null) { 3269 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3270 if (pInfo != null) { 3271 return pInfo.applicationInfo; 3272 } 3273 return null; 3274 } 3275 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3276 ps.readUserState(userId), userId); 3277 } 3278 return null; 3279 } 3280 3281 @Override 3282 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3283 if (!sUserManager.exists(userId)) return null; 3284 flags = updateFlagsForApplication(flags, userId, packageName); 3285 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3286 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3287 // writer 3288 synchronized (mPackages) { 3289 PackageParser.Package p = mPackages.get(packageName); 3290 if (DEBUG_PACKAGE_INFO) Log.v( 3291 TAG, "getApplicationInfo " + packageName 3292 + ": " + p); 3293 if (p != null) { 3294 PackageSetting ps = mSettings.mPackages.get(packageName); 3295 if (ps == null) return null; 3296 // Note: isEnabledLP() does not apply here - always return info 3297 return PackageParser.generateApplicationInfo( 3298 p, flags, ps.readUserState(userId), userId); 3299 } 3300 if ("android".equals(packageName)||"system".equals(packageName)) { 3301 return mAndroidApplication; 3302 } 3303 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3304 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3305 } 3306 } 3307 return null; 3308 } 3309 3310 @Override 3311 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3312 final IPackageDataObserver observer) { 3313 mContext.enforceCallingOrSelfPermission( 3314 android.Manifest.permission.CLEAR_APP_CACHE, null); 3315 // Queue up an async operation since clearing cache may take a little while. 3316 mHandler.post(new Runnable() { 3317 public void run() { 3318 mHandler.removeCallbacks(this); 3319 boolean success = true; 3320 synchronized (mInstallLock) { 3321 try { 3322 mInstaller.freeCache(volumeUuid, freeStorageSize); 3323 } catch (InstallerException e) { 3324 Slog.w(TAG, "Couldn't clear application caches: " + e); 3325 success = false; 3326 } 3327 } 3328 if (observer != null) { 3329 try { 3330 observer.onRemoveCompleted(null, success); 3331 } catch (RemoteException e) { 3332 Slog.w(TAG, "RemoveException when invoking call back"); 3333 } 3334 } 3335 } 3336 }); 3337 } 3338 3339 @Override 3340 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3341 final IntentSender pi) { 3342 mContext.enforceCallingOrSelfPermission( 3343 android.Manifest.permission.CLEAR_APP_CACHE, null); 3344 // Queue up an async operation since clearing cache may take a little while. 3345 mHandler.post(new Runnable() { 3346 public void run() { 3347 mHandler.removeCallbacks(this); 3348 boolean success = true; 3349 synchronized (mInstallLock) { 3350 try { 3351 mInstaller.freeCache(volumeUuid, freeStorageSize); 3352 } catch (InstallerException e) { 3353 Slog.w(TAG, "Couldn't clear application caches: " + e); 3354 success = false; 3355 } 3356 } 3357 if(pi != null) { 3358 try { 3359 // Callback via pending intent 3360 int code = success ? 1 : 0; 3361 pi.sendIntent(null, code, null, 3362 null, null); 3363 } catch (SendIntentException e1) { 3364 Slog.i(TAG, "Failed to send pending intent"); 3365 } 3366 } 3367 } 3368 }); 3369 } 3370 3371 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3372 synchronized (mInstallLock) { 3373 try { 3374 mInstaller.freeCache(volumeUuid, freeStorageSize); 3375 } catch (InstallerException e) { 3376 throw new IOException("Failed to free enough space", e); 3377 } 3378 } 3379 } 3380 3381 /** 3382 * Return if the user key is currently unlocked. 3383 */ 3384 private boolean isUserKeyUnlocked(int userId) { 3385 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 3386 final IMountService mount = IMountService.Stub 3387 .asInterface(ServiceManager.getService("mount")); 3388 if (mount == null) { 3389 Slog.w(TAG, "Early during boot, assuming locked"); 3390 return false; 3391 } 3392 final long token = Binder.clearCallingIdentity(); 3393 try { 3394 return mount.isUserKeyUnlocked(userId); 3395 } catch (RemoteException e) { 3396 throw e.rethrowAsRuntimeException(); 3397 } finally { 3398 Binder.restoreCallingIdentity(token); 3399 } 3400 } else { 3401 return true; 3402 } 3403 } 3404 3405 /** 3406 * Update given flags based on encryption status of current user. 3407 */ 3408 private int updateFlags(int flags, int userId) { 3409 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3410 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3411 // Caller expressed an explicit opinion about what encryption 3412 // aware/unaware components they want to see, so fall through and 3413 // give them what they want 3414 } else { 3415 // Caller expressed no opinion, so match based on user state 3416 if (isUserKeyUnlocked(userId)) { 3417 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3418 } else { 3419 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3420 } 3421 } 3422 return flags; 3423 } 3424 3425 /** 3426 * Update given flags when being used to request {@link PackageInfo}. 3427 */ 3428 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3429 boolean triaged = true; 3430 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3431 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3432 // Caller is asking for component details, so they'd better be 3433 // asking for specific encryption matching behavior, or be triaged 3434 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3435 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3436 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3437 triaged = false; 3438 } 3439 } 3440 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3441 | PackageManager.MATCH_SYSTEM_ONLY 3442 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3443 triaged = false; 3444 } 3445 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3446 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3447 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3448 } 3449 return updateFlags(flags, userId); 3450 } 3451 3452 /** 3453 * Update given flags when being used to request {@link ApplicationInfo}. 3454 */ 3455 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3456 return updateFlagsForPackage(flags, userId, cookie); 3457 } 3458 3459 /** 3460 * Update given flags when being used to request {@link ComponentInfo}. 3461 */ 3462 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3463 if (cookie instanceof Intent) { 3464 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3465 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3466 } 3467 } 3468 3469 boolean triaged = true; 3470 // Caller is asking for component details, so they'd better be 3471 // asking for specific encryption matching behavior, or be triaged 3472 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3473 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3474 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3475 triaged = false; 3476 } 3477 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3478 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3479 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3480 } 3481 3482 return updateFlags(flags, userId); 3483 } 3484 3485 /** 3486 * Update given flags when being used to request {@link ResolveInfo}. 3487 */ 3488 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3489 // Safe mode means we shouldn't match any third-party components 3490 if (mSafeMode) { 3491 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3492 } 3493 3494 return updateFlagsForComponent(flags, userId, cookie); 3495 } 3496 3497 @Override 3498 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3499 if (!sUserManager.exists(userId)) return null; 3500 flags = updateFlagsForComponent(flags, userId, component); 3501 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3502 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3503 synchronized (mPackages) { 3504 PackageParser.Activity a = mActivities.mActivities.get(component); 3505 3506 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3507 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3508 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3509 if (ps == null) return null; 3510 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3511 userId); 3512 } 3513 if (mResolveComponentName.equals(component)) { 3514 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3515 new PackageUserState(), userId); 3516 } 3517 } 3518 return null; 3519 } 3520 3521 @Override 3522 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3523 String resolvedType) { 3524 synchronized (mPackages) { 3525 if (component.equals(mResolveComponentName)) { 3526 // The resolver supports EVERYTHING! 3527 return true; 3528 } 3529 PackageParser.Activity a = mActivities.mActivities.get(component); 3530 if (a == null) { 3531 return false; 3532 } 3533 for (int i=0; i<a.intents.size(); i++) { 3534 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3535 intent.getData(), intent.getCategories(), TAG) >= 0) { 3536 return true; 3537 } 3538 } 3539 return false; 3540 } 3541 } 3542 3543 @Override 3544 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3545 if (!sUserManager.exists(userId)) return null; 3546 flags = updateFlagsForComponent(flags, userId, component); 3547 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3548 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3549 synchronized (mPackages) { 3550 PackageParser.Activity a = mReceivers.mActivities.get(component); 3551 if (DEBUG_PACKAGE_INFO) Log.v( 3552 TAG, "getReceiverInfo " + component + ": " + a); 3553 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3554 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3555 if (ps == null) return null; 3556 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3557 userId); 3558 } 3559 } 3560 return null; 3561 } 3562 3563 @Override 3564 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3565 if (!sUserManager.exists(userId)) return null; 3566 flags = updateFlagsForComponent(flags, userId, component); 3567 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3568 false /* requireFullPermission */, false /* checkShell */, "get service info"); 3569 synchronized (mPackages) { 3570 PackageParser.Service s = mServices.mServices.get(component); 3571 if (DEBUG_PACKAGE_INFO) Log.v( 3572 TAG, "getServiceInfo " + component + ": " + s); 3573 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3574 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3575 if (ps == null) return null; 3576 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3577 userId); 3578 } 3579 } 3580 return null; 3581 } 3582 3583 @Override 3584 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3585 if (!sUserManager.exists(userId)) return null; 3586 flags = updateFlagsForComponent(flags, userId, component); 3587 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3588 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 3589 synchronized (mPackages) { 3590 PackageParser.Provider p = mProviders.mProviders.get(component); 3591 if (DEBUG_PACKAGE_INFO) Log.v( 3592 TAG, "getProviderInfo " + component + ": " + p); 3593 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3594 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3595 if (ps == null) return null; 3596 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3597 userId); 3598 } 3599 } 3600 return null; 3601 } 3602 3603 @Override 3604 public String[] getSystemSharedLibraryNames() { 3605 Set<String> libSet; 3606 synchronized (mPackages) { 3607 libSet = mSharedLibraries.keySet(); 3608 int size = libSet.size(); 3609 if (size > 0) { 3610 String[] libs = new String[size]; 3611 libSet.toArray(libs); 3612 return libs; 3613 } 3614 } 3615 return null; 3616 } 3617 3618 @Override 3619 public @NonNull String getServicesSystemSharedLibraryPackageName() { 3620 synchronized (mPackages) { 3621 return mServicesSystemSharedLibraryPackageName; 3622 } 3623 } 3624 3625 @Override 3626 public @NonNull String getSharedSystemSharedLibraryPackageName() { 3627 synchronized (mPackages) { 3628 return mSharedSystemSharedLibraryPackageName; 3629 } 3630 } 3631 3632 @Override 3633 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 3634 synchronized (mPackages) { 3635 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values()); 3636 3637 final FeatureInfo fi = new FeatureInfo(); 3638 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3639 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3640 res.add(fi); 3641 3642 return new ParceledListSlice<>(res); 3643 } 3644 } 3645 3646 @Override 3647 public boolean hasSystemFeature(String name, int version) { 3648 synchronized (mPackages) { 3649 final FeatureInfo feat = mAvailableFeatures.get(name); 3650 if (feat == null) { 3651 return false; 3652 } else { 3653 return feat.version >= version; 3654 } 3655 } 3656 } 3657 3658 @Override 3659 public int checkPermission(String permName, String pkgName, int userId) { 3660 if (!sUserManager.exists(userId)) { 3661 return PackageManager.PERMISSION_DENIED; 3662 } 3663 3664 synchronized (mPackages) { 3665 final PackageParser.Package p = mPackages.get(pkgName); 3666 if (p != null && p.mExtras != null) { 3667 final PackageSetting ps = (PackageSetting) p.mExtras; 3668 final PermissionsState permissionsState = ps.getPermissionsState(); 3669 if (permissionsState.hasPermission(permName, userId)) { 3670 return PackageManager.PERMISSION_GRANTED; 3671 } 3672 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3673 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3674 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3675 return PackageManager.PERMISSION_GRANTED; 3676 } 3677 } 3678 } 3679 3680 return PackageManager.PERMISSION_DENIED; 3681 } 3682 3683 @Override 3684 public int checkUidPermission(String permName, int uid) { 3685 final int userId = UserHandle.getUserId(uid); 3686 3687 if (!sUserManager.exists(userId)) { 3688 return PackageManager.PERMISSION_DENIED; 3689 } 3690 3691 synchronized (mPackages) { 3692 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3693 if (obj != null) { 3694 final SettingBase ps = (SettingBase) obj; 3695 final PermissionsState permissionsState = ps.getPermissionsState(); 3696 if (permissionsState.hasPermission(permName, userId)) { 3697 return PackageManager.PERMISSION_GRANTED; 3698 } 3699 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3700 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3701 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3702 return PackageManager.PERMISSION_GRANTED; 3703 } 3704 } else { 3705 ArraySet<String> perms = mSystemPermissions.get(uid); 3706 if (perms != null) { 3707 if (perms.contains(permName)) { 3708 return PackageManager.PERMISSION_GRANTED; 3709 } 3710 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3711 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3712 return PackageManager.PERMISSION_GRANTED; 3713 } 3714 } 3715 } 3716 } 3717 3718 return PackageManager.PERMISSION_DENIED; 3719 } 3720 3721 @Override 3722 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3723 if (UserHandle.getCallingUserId() != userId) { 3724 mContext.enforceCallingPermission( 3725 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3726 "isPermissionRevokedByPolicy for user " + userId); 3727 } 3728 3729 if (checkPermission(permission, packageName, userId) 3730 == PackageManager.PERMISSION_GRANTED) { 3731 return false; 3732 } 3733 3734 final long identity = Binder.clearCallingIdentity(); 3735 try { 3736 final int flags = getPermissionFlags(permission, packageName, userId); 3737 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3738 } finally { 3739 Binder.restoreCallingIdentity(identity); 3740 } 3741 } 3742 3743 @Override 3744 public String getPermissionControllerPackageName() { 3745 synchronized (mPackages) { 3746 return mRequiredInstallerPackage; 3747 } 3748 } 3749 3750 /** 3751 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3752 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3753 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3754 * @param message the message to log on security exception 3755 */ 3756 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3757 boolean checkShell, String message) { 3758 if (userId < 0) { 3759 throw new IllegalArgumentException("Invalid userId " + userId); 3760 } 3761 if (checkShell) { 3762 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3763 } 3764 if (userId == UserHandle.getUserId(callingUid)) return; 3765 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3766 if (requireFullPermission) { 3767 mContext.enforceCallingOrSelfPermission( 3768 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3769 } else { 3770 try { 3771 mContext.enforceCallingOrSelfPermission( 3772 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3773 } catch (SecurityException se) { 3774 mContext.enforceCallingOrSelfPermission( 3775 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3776 } 3777 } 3778 } 3779 } 3780 3781 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3782 if (callingUid == Process.SHELL_UID) { 3783 if (userHandle >= 0 3784 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3785 throw new SecurityException("Shell does not have permission to access user " 3786 + userHandle); 3787 } else if (userHandle < 0) { 3788 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3789 + Debug.getCallers(3)); 3790 } 3791 } 3792 } 3793 3794 private BasePermission findPermissionTreeLP(String permName) { 3795 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3796 if (permName.startsWith(bp.name) && 3797 permName.length() > bp.name.length() && 3798 permName.charAt(bp.name.length()) == '.') { 3799 return bp; 3800 } 3801 } 3802 return null; 3803 } 3804 3805 private BasePermission checkPermissionTreeLP(String permName) { 3806 if (permName != null) { 3807 BasePermission bp = findPermissionTreeLP(permName); 3808 if (bp != null) { 3809 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3810 return bp; 3811 } 3812 throw new SecurityException("Calling uid " 3813 + Binder.getCallingUid() 3814 + " is not allowed to add to permission tree " 3815 + bp.name + " owned by uid " + bp.uid); 3816 } 3817 } 3818 throw new SecurityException("No permission tree found for " + permName); 3819 } 3820 3821 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3822 if (s1 == null) { 3823 return s2 == null; 3824 } 3825 if (s2 == null) { 3826 return false; 3827 } 3828 if (s1.getClass() != s2.getClass()) { 3829 return false; 3830 } 3831 return s1.equals(s2); 3832 } 3833 3834 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3835 if (pi1.icon != pi2.icon) return false; 3836 if (pi1.logo != pi2.logo) return false; 3837 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3838 if (!compareStrings(pi1.name, pi2.name)) return false; 3839 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3840 // We'll take care of setting this one. 3841 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3842 // These are not currently stored in settings. 3843 //if (!compareStrings(pi1.group, pi2.group)) return false; 3844 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3845 //if (pi1.labelRes != pi2.labelRes) return false; 3846 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3847 return true; 3848 } 3849 3850 int permissionInfoFootprint(PermissionInfo info) { 3851 int size = info.name.length(); 3852 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3853 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3854 return size; 3855 } 3856 3857 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3858 int size = 0; 3859 for (BasePermission perm : mSettings.mPermissions.values()) { 3860 if (perm.uid == tree.uid) { 3861 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3862 } 3863 } 3864 return size; 3865 } 3866 3867 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3868 // We calculate the max size of permissions defined by this uid and throw 3869 // if that plus the size of 'info' would exceed our stated maximum. 3870 if (tree.uid != Process.SYSTEM_UID) { 3871 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3872 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3873 throw new SecurityException("Permission tree size cap exceeded"); 3874 } 3875 } 3876 } 3877 3878 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3879 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3880 throw new SecurityException("Label must be specified in permission"); 3881 } 3882 BasePermission tree = checkPermissionTreeLP(info.name); 3883 BasePermission bp = mSettings.mPermissions.get(info.name); 3884 boolean added = bp == null; 3885 boolean changed = true; 3886 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3887 if (added) { 3888 enforcePermissionCapLocked(info, tree); 3889 bp = new BasePermission(info.name, tree.sourcePackage, 3890 BasePermission.TYPE_DYNAMIC); 3891 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3892 throw new SecurityException( 3893 "Not allowed to modify non-dynamic permission " 3894 + info.name); 3895 } else { 3896 if (bp.protectionLevel == fixedLevel 3897 && bp.perm.owner.equals(tree.perm.owner) 3898 && bp.uid == tree.uid 3899 && comparePermissionInfos(bp.perm.info, info)) { 3900 changed = false; 3901 } 3902 } 3903 bp.protectionLevel = fixedLevel; 3904 info = new PermissionInfo(info); 3905 info.protectionLevel = fixedLevel; 3906 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3907 bp.perm.info.packageName = tree.perm.info.packageName; 3908 bp.uid = tree.uid; 3909 if (added) { 3910 mSettings.mPermissions.put(info.name, bp); 3911 } 3912 if (changed) { 3913 if (!async) { 3914 mSettings.writeLPr(); 3915 } else { 3916 scheduleWriteSettingsLocked(); 3917 } 3918 } 3919 return added; 3920 } 3921 3922 @Override 3923 public boolean addPermission(PermissionInfo info) { 3924 synchronized (mPackages) { 3925 return addPermissionLocked(info, false); 3926 } 3927 } 3928 3929 @Override 3930 public boolean addPermissionAsync(PermissionInfo info) { 3931 synchronized (mPackages) { 3932 return addPermissionLocked(info, true); 3933 } 3934 } 3935 3936 @Override 3937 public void removePermission(String name) { 3938 synchronized (mPackages) { 3939 checkPermissionTreeLP(name); 3940 BasePermission bp = mSettings.mPermissions.get(name); 3941 if (bp != null) { 3942 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3943 throw new SecurityException( 3944 "Not allowed to modify non-dynamic permission " 3945 + name); 3946 } 3947 mSettings.mPermissions.remove(name); 3948 mSettings.writeLPr(); 3949 } 3950 } 3951 } 3952 3953 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 3954 BasePermission bp) { 3955 int index = pkg.requestedPermissions.indexOf(bp.name); 3956 if (index == -1) { 3957 throw new SecurityException("Package " + pkg.packageName 3958 + " has not requested permission " + bp.name); 3959 } 3960 if (!bp.isRuntime() && !bp.isDevelopment()) { 3961 throw new SecurityException("Permission " + bp.name 3962 + " is not a changeable permission type"); 3963 } 3964 } 3965 3966 @Override 3967 public void grantRuntimePermission(String packageName, String name, final int userId) { 3968 if (!sUserManager.exists(userId)) { 3969 Log.e(TAG, "No such user:" + userId); 3970 return; 3971 } 3972 3973 mContext.enforceCallingOrSelfPermission( 3974 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 3975 "grantRuntimePermission"); 3976 3977 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3978 true /* requireFullPermission */, true /* checkShell */, 3979 "grantRuntimePermission"); 3980 3981 final int uid; 3982 final SettingBase sb; 3983 3984 synchronized (mPackages) { 3985 final PackageParser.Package pkg = mPackages.get(packageName); 3986 if (pkg == null) { 3987 throw new IllegalArgumentException("Unknown package: " + packageName); 3988 } 3989 3990 final BasePermission bp = mSettings.mPermissions.get(name); 3991 if (bp == null) { 3992 throw new IllegalArgumentException("Unknown permission: " + name); 3993 } 3994 3995 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3996 3997 // If a permission review is required for legacy apps we represent 3998 // their permissions as always granted runtime ones since we need 3999 // to keep the review required permission flag per user while an 4000 // install permission's state is shared across all users. 4001 if (Build.PERMISSIONS_REVIEW_REQUIRED 4002 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4003 && bp.isRuntime()) { 4004 return; 4005 } 4006 4007 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4008 sb = (SettingBase) pkg.mExtras; 4009 if (sb == null) { 4010 throw new IllegalArgumentException("Unknown package: " + packageName); 4011 } 4012 4013 final PermissionsState permissionsState = sb.getPermissionsState(); 4014 4015 final int flags = permissionsState.getPermissionFlags(name, userId); 4016 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4017 throw new SecurityException("Cannot grant system fixed permission " 4018 + name + " for package " + packageName); 4019 } 4020 4021 if (bp.isDevelopment()) { 4022 // Development permissions must be handled specially, since they are not 4023 // normal runtime permissions. For now they apply to all users. 4024 if (permissionsState.grantInstallPermission(bp) != 4025 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4026 scheduleWriteSettingsLocked(); 4027 } 4028 return; 4029 } 4030 4031 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4032 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4033 return; 4034 } 4035 4036 final int result = permissionsState.grantRuntimePermission(bp, userId); 4037 switch (result) { 4038 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4039 return; 4040 } 4041 4042 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4043 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4044 mHandler.post(new Runnable() { 4045 @Override 4046 public void run() { 4047 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4048 } 4049 }); 4050 } 4051 break; 4052 } 4053 4054 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4055 4056 // Not critical if that is lost - app has to request again. 4057 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4058 } 4059 4060 // Only need to do this if user is initialized. Otherwise it's a new user 4061 // and there are no processes running as the user yet and there's no need 4062 // to make an expensive call to remount processes for the changed permissions. 4063 if (READ_EXTERNAL_STORAGE.equals(name) 4064 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4065 final long token = Binder.clearCallingIdentity(); 4066 try { 4067 if (sUserManager.isInitialized(userId)) { 4068 MountServiceInternal mountServiceInternal = LocalServices.getService( 4069 MountServiceInternal.class); 4070 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 4071 } 4072 } finally { 4073 Binder.restoreCallingIdentity(token); 4074 } 4075 } 4076 } 4077 4078 @Override 4079 public void revokeRuntimePermission(String packageName, String name, int userId) { 4080 if (!sUserManager.exists(userId)) { 4081 Log.e(TAG, "No such user:" + userId); 4082 return; 4083 } 4084 4085 mContext.enforceCallingOrSelfPermission( 4086 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4087 "revokeRuntimePermission"); 4088 4089 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4090 true /* requireFullPermission */, true /* checkShell */, 4091 "revokeRuntimePermission"); 4092 4093 final int appId; 4094 4095 synchronized (mPackages) { 4096 final PackageParser.Package pkg = mPackages.get(packageName); 4097 if (pkg == null) { 4098 throw new IllegalArgumentException("Unknown package: " + packageName); 4099 } 4100 4101 final BasePermission bp = mSettings.mPermissions.get(name); 4102 if (bp == null) { 4103 throw new IllegalArgumentException("Unknown permission: " + name); 4104 } 4105 4106 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4107 4108 // If a permission review is required for legacy apps we represent 4109 // their permissions as always granted runtime ones since we need 4110 // to keep the review required permission flag per user while an 4111 // install permission's state is shared across all users. 4112 if (Build.PERMISSIONS_REVIEW_REQUIRED 4113 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4114 && bp.isRuntime()) { 4115 return; 4116 } 4117 4118 SettingBase sb = (SettingBase) pkg.mExtras; 4119 if (sb == null) { 4120 throw new IllegalArgumentException("Unknown package: " + packageName); 4121 } 4122 4123 final PermissionsState permissionsState = sb.getPermissionsState(); 4124 4125 final int flags = permissionsState.getPermissionFlags(name, userId); 4126 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4127 throw new SecurityException("Cannot revoke system fixed permission " 4128 + name + " for package " + packageName); 4129 } 4130 4131 if (bp.isDevelopment()) { 4132 // Development permissions must be handled specially, since they are not 4133 // normal runtime permissions. For now they apply to all users. 4134 if (permissionsState.revokeInstallPermission(bp) != 4135 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4136 scheduleWriteSettingsLocked(); 4137 } 4138 return; 4139 } 4140 4141 if (permissionsState.revokeRuntimePermission(bp, userId) == 4142 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4143 return; 4144 } 4145 4146 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4147 4148 // Critical, after this call app should never have the permission. 4149 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4150 4151 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4152 } 4153 4154 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4155 } 4156 4157 @Override 4158 public void resetRuntimePermissions() { 4159 mContext.enforceCallingOrSelfPermission( 4160 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4161 "revokeRuntimePermission"); 4162 4163 int callingUid = Binder.getCallingUid(); 4164 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4165 mContext.enforceCallingOrSelfPermission( 4166 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4167 "resetRuntimePermissions"); 4168 } 4169 4170 synchronized (mPackages) { 4171 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4172 for (int userId : UserManagerService.getInstance().getUserIds()) { 4173 final int packageCount = mPackages.size(); 4174 for (int i = 0; i < packageCount; i++) { 4175 PackageParser.Package pkg = mPackages.valueAt(i); 4176 if (!(pkg.mExtras instanceof PackageSetting)) { 4177 continue; 4178 } 4179 PackageSetting ps = (PackageSetting) pkg.mExtras; 4180 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4181 } 4182 } 4183 } 4184 } 4185 4186 @Override 4187 public int getPermissionFlags(String name, String packageName, int userId) { 4188 if (!sUserManager.exists(userId)) { 4189 return 0; 4190 } 4191 4192 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4193 4194 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4195 true /* requireFullPermission */, false /* checkShell */, 4196 "getPermissionFlags"); 4197 4198 synchronized (mPackages) { 4199 final PackageParser.Package pkg = mPackages.get(packageName); 4200 if (pkg == null) { 4201 throw new IllegalArgumentException("Unknown package: " + packageName); 4202 } 4203 4204 final BasePermission bp = mSettings.mPermissions.get(name); 4205 if (bp == null) { 4206 throw new IllegalArgumentException("Unknown permission: " + name); 4207 } 4208 4209 SettingBase sb = (SettingBase) pkg.mExtras; 4210 if (sb == null) { 4211 throw new IllegalArgumentException("Unknown package: " + packageName); 4212 } 4213 4214 PermissionsState permissionsState = sb.getPermissionsState(); 4215 return permissionsState.getPermissionFlags(name, userId); 4216 } 4217 } 4218 4219 @Override 4220 public void updatePermissionFlags(String name, String packageName, int flagMask, 4221 int flagValues, int userId) { 4222 if (!sUserManager.exists(userId)) { 4223 return; 4224 } 4225 4226 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4227 4228 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4229 true /* requireFullPermission */, true /* checkShell */, 4230 "updatePermissionFlags"); 4231 4232 // Only the system can change these flags and nothing else. 4233 if (getCallingUid() != Process.SYSTEM_UID) { 4234 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4235 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4236 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4237 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4238 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4239 } 4240 4241 synchronized (mPackages) { 4242 final PackageParser.Package pkg = mPackages.get(packageName); 4243 if (pkg == null) { 4244 throw new IllegalArgumentException("Unknown package: " + packageName); 4245 } 4246 4247 final BasePermission bp = mSettings.mPermissions.get(name); 4248 if (bp == null) { 4249 throw new IllegalArgumentException("Unknown permission: " + name); 4250 } 4251 4252 SettingBase sb = (SettingBase) pkg.mExtras; 4253 if (sb == null) { 4254 throw new IllegalArgumentException("Unknown package: " + packageName); 4255 } 4256 4257 PermissionsState permissionsState = sb.getPermissionsState(); 4258 4259 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4260 4261 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4262 // Install and runtime permissions are stored in different places, 4263 // so figure out what permission changed and persist the change. 4264 if (permissionsState.getInstallPermissionState(name) != null) { 4265 scheduleWriteSettingsLocked(); 4266 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4267 || hadState) { 4268 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4269 } 4270 } 4271 } 4272 } 4273 4274 /** 4275 * Update the permission flags for all packages and runtime permissions of a user in order 4276 * to allow device or profile owner to remove POLICY_FIXED. 4277 */ 4278 @Override 4279 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4280 if (!sUserManager.exists(userId)) { 4281 return; 4282 } 4283 4284 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4285 4286 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4287 true /* requireFullPermission */, true /* checkShell */, 4288 "updatePermissionFlagsForAllApps"); 4289 4290 // Only the system can change system fixed flags. 4291 if (getCallingUid() != Process.SYSTEM_UID) { 4292 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4293 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4294 } 4295 4296 synchronized (mPackages) { 4297 boolean changed = false; 4298 final int packageCount = mPackages.size(); 4299 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4300 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4301 SettingBase sb = (SettingBase) pkg.mExtras; 4302 if (sb == null) { 4303 continue; 4304 } 4305 PermissionsState permissionsState = sb.getPermissionsState(); 4306 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4307 userId, flagMask, flagValues); 4308 } 4309 if (changed) { 4310 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4311 } 4312 } 4313 } 4314 4315 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4316 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4317 != PackageManager.PERMISSION_GRANTED 4318 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4319 != PackageManager.PERMISSION_GRANTED) { 4320 throw new SecurityException(message + " requires " 4321 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4322 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4323 } 4324 } 4325 4326 @Override 4327 public boolean shouldShowRequestPermissionRationale(String permissionName, 4328 String packageName, int userId) { 4329 if (UserHandle.getCallingUserId() != userId) { 4330 mContext.enforceCallingPermission( 4331 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4332 "canShowRequestPermissionRationale for user " + userId); 4333 } 4334 4335 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4336 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4337 return false; 4338 } 4339 4340 if (checkPermission(permissionName, packageName, userId) 4341 == PackageManager.PERMISSION_GRANTED) { 4342 return false; 4343 } 4344 4345 final int flags; 4346 4347 final long identity = Binder.clearCallingIdentity(); 4348 try { 4349 flags = getPermissionFlags(permissionName, 4350 packageName, userId); 4351 } finally { 4352 Binder.restoreCallingIdentity(identity); 4353 } 4354 4355 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4356 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4357 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4358 4359 if ((flags & fixedFlags) != 0) { 4360 return false; 4361 } 4362 4363 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4364 } 4365 4366 @Override 4367 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4368 mContext.enforceCallingOrSelfPermission( 4369 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4370 "addOnPermissionsChangeListener"); 4371 4372 synchronized (mPackages) { 4373 mOnPermissionChangeListeners.addListenerLocked(listener); 4374 } 4375 } 4376 4377 @Override 4378 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4379 synchronized (mPackages) { 4380 mOnPermissionChangeListeners.removeListenerLocked(listener); 4381 } 4382 } 4383 4384 @Override 4385 public boolean isProtectedBroadcast(String actionName) { 4386 synchronized (mPackages) { 4387 if (mProtectedBroadcasts.contains(actionName)) { 4388 return true; 4389 } else if (actionName != null) { 4390 // TODO: remove these terrible hacks 4391 if (actionName.startsWith("android.net.netmon.lingerExpired") 4392 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4393 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 4394 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 4395 return true; 4396 } 4397 } 4398 } 4399 return false; 4400 } 4401 4402 @Override 4403 public int checkSignatures(String pkg1, String pkg2) { 4404 synchronized (mPackages) { 4405 final PackageParser.Package p1 = mPackages.get(pkg1); 4406 final PackageParser.Package p2 = mPackages.get(pkg2); 4407 if (p1 == null || p1.mExtras == null 4408 || p2 == null || p2.mExtras == null) { 4409 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4410 } 4411 return compareSignatures(p1.mSignatures, p2.mSignatures); 4412 } 4413 } 4414 4415 @Override 4416 public int checkUidSignatures(int uid1, int uid2) { 4417 // Map to base uids. 4418 uid1 = UserHandle.getAppId(uid1); 4419 uid2 = UserHandle.getAppId(uid2); 4420 // reader 4421 synchronized (mPackages) { 4422 Signature[] s1; 4423 Signature[] s2; 4424 Object obj = mSettings.getUserIdLPr(uid1); 4425 if (obj != null) { 4426 if (obj instanceof SharedUserSetting) { 4427 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4428 } else if (obj instanceof PackageSetting) { 4429 s1 = ((PackageSetting)obj).signatures.mSignatures; 4430 } else { 4431 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4432 } 4433 } else { 4434 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4435 } 4436 obj = mSettings.getUserIdLPr(uid2); 4437 if (obj != null) { 4438 if (obj instanceof SharedUserSetting) { 4439 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4440 } else if (obj instanceof PackageSetting) { 4441 s2 = ((PackageSetting)obj).signatures.mSignatures; 4442 } else { 4443 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4444 } 4445 } else { 4446 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4447 } 4448 return compareSignatures(s1, s2); 4449 } 4450 } 4451 4452 /** 4453 * This method should typically only be used when granting or revoking 4454 * permissions, since the app may immediately restart after this call. 4455 * <p> 4456 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 4457 * guard your work against the app being relaunched. 4458 */ 4459 private void killUid(int appId, int userId, String reason) { 4460 final long identity = Binder.clearCallingIdentity(); 4461 try { 4462 IActivityManager am = ActivityManagerNative.getDefault(); 4463 if (am != null) { 4464 try { 4465 am.killUid(appId, userId, reason); 4466 } catch (RemoteException e) { 4467 /* ignore - same process */ 4468 } 4469 } 4470 } finally { 4471 Binder.restoreCallingIdentity(identity); 4472 } 4473 } 4474 4475 /** 4476 * Compares two sets of signatures. Returns: 4477 * <br /> 4478 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4479 * <br /> 4480 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4481 * <br /> 4482 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4483 * <br /> 4484 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4485 * <br /> 4486 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4487 */ 4488 static int compareSignatures(Signature[] s1, Signature[] s2) { 4489 if (s1 == null) { 4490 return s2 == null 4491 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4492 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4493 } 4494 4495 if (s2 == null) { 4496 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4497 } 4498 4499 if (s1.length != s2.length) { 4500 return PackageManager.SIGNATURE_NO_MATCH; 4501 } 4502 4503 // Since both signature sets are of size 1, we can compare without HashSets. 4504 if (s1.length == 1) { 4505 return s1[0].equals(s2[0]) ? 4506 PackageManager.SIGNATURE_MATCH : 4507 PackageManager.SIGNATURE_NO_MATCH; 4508 } 4509 4510 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4511 for (Signature sig : s1) { 4512 set1.add(sig); 4513 } 4514 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4515 for (Signature sig : s2) { 4516 set2.add(sig); 4517 } 4518 // Make sure s2 contains all signatures in s1. 4519 if (set1.equals(set2)) { 4520 return PackageManager.SIGNATURE_MATCH; 4521 } 4522 return PackageManager.SIGNATURE_NO_MATCH; 4523 } 4524 4525 /** 4526 * If the database version for this type of package (internal storage or 4527 * external storage) is less than the version where package signatures 4528 * were updated, return true. 4529 */ 4530 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4531 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4532 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4533 } 4534 4535 /** 4536 * Used for backward compatibility to make sure any packages with 4537 * certificate chains get upgraded to the new style. {@code existingSigs} 4538 * will be in the old format (since they were stored on disk from before the 4539 * system upgrade) and {@code scannedSigs} will be in the newer format. 4540 */ 4541 private int compareSignaturesCompat(PackageSignatures existingSigs, 4542 PackageParser.Package scannedPkg) { 4543 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4544 return PackageManager.SIGNATURE_NO_MATCH; 4545 } 4546 4547 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4548 for (Signature sig : existingSigs.mSignatures) { 4549 existingSet.add(sig); 4550 } 4551 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4552 for (Signature sig : scannedPkg.mSignatures) { 4553 try { 4554 Signature[] chainSignatures = sig.getChainSignatures(); 4555 for (Signature chainSig : chainSignatures) { 4556 scannedCompatSet.add(chainSig); 4557 } 4558 } catch (CertificateEncodingException e) { 4559 scannedCompatSet.add(sig); 4560 } 4561 } 4562 /* 4563 * Make sure the expanded scanned set contains all signatures in the 4564 * existing one. 4565 */ 4566 if (scannedCompatSet.equals(existingSet)) { 4567 // Migrate the old signatures to the new scheme. 4568 existingSigs.assignSignatures(scannedPkg.mSignatures); 4569 // The new KeySets will be re-added later in the scanning process. 4570 synchronized (mPackages) { 4571 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4572 } 4573 return PackageManager.SIGNATURE_MATCH; 4574 } 4575 return PackageManager.SIGNATURE_NO_MATCH; 4576 } 4577 4578 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4579 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4580 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4581 } 4582 4583 private int compareSignaturesRecover(PackageSignatures existingSigs, 4584 PackageParser.Package scannedPkg) { 4585 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4586 return PackageManager.SIGNATURE_NO_MATCH; 4587 } 4588 4589 String msg = null; 4590 try { 4591 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4592 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4593 + scannedPkg.packageName); 4594 return PackageManager.SIGNATURE_MATCH; 4595 } 4596 } catch (CertificateException e) { 4597 msg = e.getMessage(); 4598 } 4599 4600 logCriticalInfo(Log.INFO, 4601 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4602 return PackageManager.SIGNATURE_NO_MATCH; 4603 } 4604 4605 @Override 4606 public List<String> getAllPackages() { 4607 synchronized (mPackages) { 4608 return new ArrayList<String>(mPackages.keySet()); 4609 } 4610 } 4611 4612 @Override 4613 public String[] getPackagesForUid(int uid) { 4614 uid = UserHandle.getAppId(uid); 4615 // reader 4616 synchronized (mPackages) { 4617 Object obj = mSettings.getUserIdLPr(uid); 4618 if (obj instanceof SharedUserSetting) { 4619 final SharedUserSetting sus = (SharedUserSetting) obj; 4620 final int N = sus.packages.size(); 4621 final String[] res = new String[N]; 4622 final Iterator<PackageSetting> it = sus.packages.iterator(); 4623 int i = 0; 4624 while (it.hasNext()) { 4625 res[i++] = it.next().name; 4626 } 4627 return res; 4628 } else if (obj instanceof PackageSetting) { 4629 final PackageSetting ps = (PackageSetting) obj; 4630 return new String[] { ps.name }; 4631 } 4632 } 4633 return null; 4634 } 4635 4636 @Override 4637 public String getNameForUid(int uid) { 4638 // reader 4639 synchronized (mPackages) { 4640 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4641 if (obj instanceof SharedUserSetting) { 4642 final SharedUserSetting sus = (SharedUserSetting) obj; 4643 return sus.name + ":" + sus.userId; 4644 } else if (obj instanceof PackageSetting) { 4645 final PackageSetting ps = (PackageSetting) obj; 4646 return ps.name; 4647 } 4648 } 4649 return null; 4650 } 4651 4652 @Override 4653 public int getUidForSharedUser(String sharedUserName) { 4654 if(sharedUserName == null) { 4655 return -1; 4656 } 4657 // reader 4658 synchronized (mPackages) { 4659 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4660 if (suid == null) { 4661 return -1; 4662 } 4663 return suid.userId; 4664 } 4665 } 4666 4667 @Override 4668 public int getFlagsForUid(int uid) { 4669 synchronized (mPackages) { 4670 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4671 if (obj instanceof SharedUserSetting) { 4672 final SharedUserSetting sus = (SharedUserSetting) obj; 4673 return sus.pkgFlags; 4674 } else if (obj instanceof PackageSetting) { 4675 final PackageSetting ps = (PackageSetting) obj; 4676 return ps.pkgFlags; 4677 } 4678 } 4679 return 0; 4680 } 4681 4682 @Override 4683 public int getPrivateFlagsForUid(int uid) { 4684 synchronized (mPackages) { 4685 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4686 if (obj instanceof SharedUserSetting) { 4687 final SharedUserSetting sus = (SharedUserSetting) obj; 4688 return sus.pkgPrivateFlags; 4689 } else if (obj instanceof PackageSetting) { 4690 final PackageSetting ps = (PackageSetting) obj; 4691 return ps.pkgPrivateFlags; 4692 } 4693 } 4694 return 0; 4695 } 4696 4697 @Override 4698 public boolean isUidPrivileged(int uid) { 4699 uid = UserHandle.getAppId(uid); 4700 // reader 4701 synchronized (mPackages) { 4702 Object obj = mSettings.getUserIdLPr(uid); 4703 if (obj instanceof SharedUserSetting) { 4704 final SharedUserSetting sus = (SharedUserSetting) obj; 4705 final Iterator<PackageSetting> it = sus.packages.iterator(); 4706 while (it.hasNext()) { 4707 if (it.next().isPrivileged()) { 4708 return true; 4709 } 4710 } 4711 } else if (obj instanceof PackageSetting) { 4712 final PackageSetting ps = (PackageSetting) obj; 4713 return ps.isPrivileged(); 4714 } 4715 } 4716 return false; 4717 } 4718 4719 @Override 4720 public String[] getAppOpPermissionPackages(String permissionName) { 4721 synchronized (mPackages) { 4722 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4723 if (pkgs == null) { 4724 return null; 4725 } 4726 return pkgs.toArray(new String[pkgs.size()]); 4727 } 4728 } 4729 4730 @Override 4731 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4732 int flags, int userId) { 4733 try { 4734 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 4735 4736 if (!sUserManager.exists(userId)) return null; 4737 flags = updateFlagsForResolve(flags, userId, intent); 4738 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4739 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 4740 4741 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 4742 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 4743 flags, userId); 4744 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4745 4746 final ResolveInfo bestChoice = 4747 chooseBestActivity(intent, resolvedType, flags, query, userId); 4748 4749 if (isEphemeralAllowed(intent, query, userId)) { 4750 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 4751 final EphemeralResolveInfo ai = 4752 getEphemeralResolveInfo(intent, resolvedType, userId); 4753 if (ai != null) { 4754 if (DEBUG_EPHEMERAL) { 4755 Slog.v(TAG, "Returning an EphemeralResolveInfo"); 4756 } 4757 bestChoice.ephemeralInstaller = mEphemeralInstallerInfo; 4758 bestChoice.ephemeralResolveInfo = ai; 4759 } 4760 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4761 } 4762 return bestChoice; 4763 } finally { 4764 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4765 } 4766 } 4767 4768 @Override 4769 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4770 IntentFilter filter, int match, ComponentName activity) { 4771 final int userId = UserHandle.getCallingUserId(); 4772 if (DEBUG_PREFERRED) { 4773 Log.v(TAG, "setLastChosenActivity intent=" + intent 4774 + " resolvedType=" + resolvedType 4775 + " flags=" + flags 4776 + " filter=" + filter 4777 + " match=" + match 4778 + " activity=" + activity); 4779 filter.dump(new PrintStreamPrinter(System.out), " "); 4780 } 4781 intent.setComponent(null); 4782 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4783 userId); 4784 // Find any earlier preferred or last chosen entries and nuke them 4785 findPreferredActivity(intent, resolvedType, 4786 flags, query, 0, false, true, false, userId); 4787 // Add the new activity as the last chosen for this filter 4788 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4789 "Setting last chosen"); 4790 } 4791 4792 @Override 4793 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4794 final int userId = UserHandle.getCallingUserId(); 4795 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4796 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4797 userId); 4798 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4799 false, false, false, userId); 4800 } 4801 4802 4803 private boolean isEphemeralAllowed( 4804 Intent intent, List<ResolveInfo> resolvedActivites, int userId) { 4805 // Short circuit and return early if possible. 4806 if (DISABLE_EPHEMERAL_APPS) { 4807 return false; 4808 } 4809 final int callingUser = UserHandle.getCallingUserId(); 4810 if (callingUser != UserHandle.USER_SYSTEM) { 4811 return false; 4812 } 4813 if (mEphemeralResolverConnection == null) { 4814 return false; 4815 } 4816 if (intent.getComponent() != null) { 4817 return false; 4818 } 4819 if (intent.getPackage() != null) { 4820 return false; 4821 } 4822 final boolean isWebUri = hasWebURI(intent); 4823 if (!isWebUri) { 4824 return false; 4825 } 4826 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4827 synchronized (mPackages) { 4828 final int count = resolvedActivites.size(); 4829 for (int n = 0; n < count; n++) { 4830 ResolveInfo info = resolvedActivites.get(n); 4831 String packageName = info.activityInfo.packageName; 4832 PackageSetting ps = mSettings.mPackages.get(packageName); 4833 if (ps != null) { 4834 // Try to get the status from User settings first 4835 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4836 int status = (int) (packedStatus >> 32); 4837 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4838 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4839 if (DEBUG_EPHEMERAL) { 4840 Slog.v(TAG, "DENY ephemeral apps;" 4841 + " pkg: " + packageName + ", status: " + status); 4842 } 4843 return false; 4844 } 4845 } 4846 } 4847 } 4848 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4849 return true; 4850 } 4851 4852 private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType, 4853 int userId) { 4854 MessageDigest digest = null; 4855 try { 4856 digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM); 4857 } catch (NoSuchAlgorithmException e) { 4858 // If we can't create a digest, ignore ephemeral apps. 4859 return null; 4860 } 4861 4862 final byte[] hostBytes = intent.getData().getHost().getBytes(); 4863 final byte[] digestBytes = digest.digest(hostBytes); 4864 int shaPrefix = 4865 digestBytes[0] << 24 4866 | digestBytes[1] << 16 4867 | digestBytes[2] << 8 4868 | digestBytes[3] << 0; 4869 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4870 mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix); 4871 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4872 // No hash prefix match; there are no ephemeral apps for this domain. 4873 return null; 4874 } 4875 for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) { 4876 EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i); 4877 if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) { 4878 continue; 4879 } 4880 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 4881 // No filters; this should never happen. 4882 if (filters.isEmpty()) { 4883 continue; 4884 } 4885 // We have a domain match; resolve the filters to see if anything matches. 4886 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4887 for (int j = filters.size() - 1; j >= 0; --j) { 4888 final EphemeralResolveIntentInfo intentInfo = 4889 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 4890 ephemeralResolver.addFilter(intentInfo); 4891 } 4892 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 4893 intent, resolvedType, false /*defaultOnly*/, userId); 4894 if (!matchedResolveInfoList.isEmpty()) { 4895 return matchedResolveInfoList.get(0); 4896 } 4897 } 4898 // Hash or filter mis-match; no ephemeral apps for this domain. 4899 return null; 4900 } 4901 4902 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4903 int flags, List<ResolveInfo> query, int userId) { 4904 if (query != null) { 4905 final int N = query.size(); 4906 if (N == 1) { 4907 return query.get(0); 4908 } else if (N > 1) { 4909 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4910 // If there is more than one activity with the same priority, 4911 // then let the user decide between them. 4912 ResolveInfo r0 = query.get(0); 4913 ResolveInfo r1 = query.get(1); 4914 if (DEBUG_INTENT_MATCHING || debug) { 4915 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4916 + r1.activityInfo.name + "=" + r1.priority); 4917 } 4918 // If the first activity has a higher priority, or a different 4919 // default, then it is always desirable to pick it. 4920 if (r0.priority != r1.priority 4921 || r0.preferredOrder != r1.preferredOrder 4922 || r0.isDefault != r1.isDefault) { 4923 return query.get(0); 4924 } 4925 // If we have saved a preference for a preferred activity for 4926 // this Intent, use that. 4927 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4928 flags, query, r0.priority, true, false, debug, userId); 4929 if (ri != null) { 4930 return ri; 4931 } 4932 ri = new ResolveInfo(mResolveInfo); 4933 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4934 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 4935 ri.activityInfo.applicationInfo = new ApplicationInfo( 4936 ri.activityInfo.applicationInfo); 4937 if (userId != 0) { 4938 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4939 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4940 } 4941 // Make sure that the resolver is displayable in car mode 4942 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 4943 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 4944 return ri; 4945 } 4946 } 4947 return null; 4948 } 4949 4950 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4951 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4952 final int N = query.size(); 4953 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4954 .get(userId); 4955 // Get the list of persistent preferred activities that handle the intent 4956 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4957 List<PersistentPreferredActivity> pprefs = ppir != null 4958 ? ppir.queryIntent(intent, resolvedType, 4959 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4960 : null; 4961 if (pprefs != null && pprefs.size() > 0) { 4962 final int M = pprefs.size(); 4963 for (int i=0; i<M; i++) { 4964 final PersistentPreferredActivity ppa = pprefs.get(i); 4965 if (DEBUG_PREFERRED || debug) { 4966 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4967 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4968 + "\n component=" + ppa.mComponent); 4969 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4970 } 4971 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4972 flags | MATCH_DISABLED_COMPONENTS, userId); 4973 if (DEBUG_PREFERRED || debug) { 4974 Slog.v(TAG, "Found persistent preferred activity:"); 4975 if (ai != null) { 4976 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4977 } else { 4978 Slog.v(TAG, " null"); 4979 } 4980 } 4981 if (ai == null) { 4982 // This previously registered persistent preferred activity 4983 // component is no longer known. Ignore it and do NOT remove it. 4984 continue; 4985 } 4986 for (int j=0; j<N; j++) { 4987 final ResolveInfo ri = query.get(j); 4988 if (!ri.activityInfo.applicationInfo.packageName 4989 .equals(ai.applicationInfo.packageName)) { 4990 continue; 4991 } 4992 if (!ri.activityInfo.name.equals(ai.name)) { 4993 continue; 4994 } 4995 // Found a persistent preference that can handle the intent. 4996 if (DEBUG_PREFERRED || debug) { 4997 Slog.v(TAG, "Returning persistent preferred activity: " + 4998 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4999 } 5000 return ri; 5001 } 5002 } 5003 } 5004 return null; 5005 } 5006 5007 // TODO: handle preferred activities missing while user has amnesia 5008 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5009 List<ResolveInfo> query, int priority, boolean always, 5010 boolean removeMatches, boolean debug, int userId) { 5011 if (!sUserManager.exists(userId)) return null; 5012 flags = updateFlagsForResolve(flags, userId, intent); 5013 // writer 5014 synchronized (mPackages) { 5015 if (intent.getSelector() != null) { 5016 intent = intent.getSelector(); 5017 } 5018 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 5019 5020 // Try to find a matching persistent preferred activity. 5021 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5022 debug, userId); 5023 5024 // If a persistent preferred activity matched, use it. 5025 if (pri != null) { 5026 return pri; 5027 } 5028 5029 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5030 // Get the list of preferred activities that handle the intent 5031 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5032 List<PreferredActivity> prefs = pir != null 5033 ? pir.queryIntent(intent, resolvedType, 5034 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5035 : null; 5036 if (prefs != null && prefs.size() > 0) { 5037 boolean changed = false; 5038 try { 5039 // First figure out how good the original match set is. 5040 // We will only allow preferred activities that came 5041 // from the same match quality. 5042 int match = 0; 5043 5044 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5045 5046 final int N = query.size(); 5047 for (int j=0; j<N; j++) { 5048 final ResolveInfo ri = query.get(j); 5049 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5050 + ": 0x" + Integer.toHexString(match)); 5051 if (ri.match > match) { 5052 match = ri.match; 5053 } 5054 } 5055 5056 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5057 + Integer.toHexString(match)); 5058 5059 match &= IntentFilter.MATCH_CATEGORY_MASK; 5060 final int M = prefs.size(); 5061 for (int i=0; i<M; i++) { 5062 final PreferredActivity pa = prefs.get(i); 5063 if (DEBUG_PREFERRED || debug) { 5064 Slog.v(TAG, "Checking PreferredActivity ds=" 5065 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5066 + "\n component=" + pa.mPref.mComponent); 5067 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5068 } 5069 if (pa.mPref.mMatch != match) { 5070 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5071 + Integer.toHexString(pa.mPref.mMatch)); 5072 continue; 5073 } 5074 // If it's not an "always" type preferred activity and that's what we're 5075 // looking for, skip it. 5076 if (always && !pa.mPref.mAlways) { 5077 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5078 continue; 5079 } 5080 final ActivityInfo ai = getActivityInfo( 5081 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5082 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5083 userId); 5084 if (DEBUG_PREFERRED || debug) { 5085 Slog.v(TAG, "Found preferred activity:"); 5086 if (ai != null) { 5087 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5088 } else { 5089 Slog.v(TAG, " null"); 5090 } 5091 } 5092 if (ai == null) { 5093 // This previously registered preferred activity 5094 // component is no longer known. Most likely an update 5095 // to the app was installed and in the new version this 5096 // component no longer exists. Clean it up by removing 5097 // it from the preferred activities list, and skip it. 5098 Slog.w(TAG, "Removing dangling preferred activity: " 5099 + pa.mPref.mComponent); 5100 pir.removeFilter(pa); 5101 changed = true; 5102 continue; 5103 } 5104 for (int j=0; j<N; j++) { 5105 final ResolveInfo ri = query.get(j); 5106 if (!ri.activityInfo.applicationInfo.packageName 5107 .equals(ai.applicationInfo.packageName)) { 5108 continue; 5109 } 5110 if (!ri.activityInfo.name.equals(ai.name)) { 5111 continue; 5112 } 5113 5114 if (removeMatches) { 5115 pir.removeFilter(pa); 5116 changed = true; 5117 if (DEBUG_PREFERRED) { 5118 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 5119 } 5120 break; 5121 } 5122 5123 // Okay we found a previously set preferred or last chosen app. 5124 // If the result set is different from when this 5125 // was created, we need to clear it and re-ask the 5126 // user their preference, if we're looking for an "always" type entry. 5127 if (always && !pa.mPref.sameSet(query)) { 5128 Slog.i(TAG, "Result set changed, dropping preferred activity for " 5129 + intent + " type " + resolvedType); 5130 if (DEBUG_PREFERRED) { 5131 Slog.v(TAG, "Removing preferred activity since set changed " 5132 + pa.mPref.mComponent); 5133 } 5134 pir.removeFilter(pa); 5135 // Re-add the filter as a "last chosen" entry (!always) 5136 PreferredActivity lastChosen = new PreferredActivity( 5137 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5138 pir.addFilter(lastChosen); 5139 changed = true; 5140 return null; 5141 } 5142 5143 // Yay! Either the set matched or we're looking for the last chosen 5144 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5145 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5146 return ri; 5147 } 5148 } 5149 } finally { 5150 if (changed) { 5151 if (DEBUG_PREFERRED) { 5152 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5153 } 5154 scheduleWritePackageRestrictionsLocked(userId); 5155 } 5156 } 5157 } 5158 } 5159 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5160 return null; 5161 } 5162 5163 /* 5164 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5165 */ 5166 @Override 5167 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5168 int targetUserId) { 5169 mContext.enforceCallingOrSelfPermission( 5170 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5171 List<CrossProfileIntentFilter> matches = 5172 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5173 if (matches != null) { 5174 int size = matches.size(); 5175 for (int i = 0; i < size; i++) { 5176 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5177 } 5178 } 5179 if (hasWebURI(intent)) { 5180 // cross-profile app linking works only towards the parent. 5181 final UserInfo parent = getProfileParent(sourceUserId); 5182 synchronized(mPackages) { 5183 int flags = updateFlagsForResolve(0, parent.id, intent); 5184 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5185 intent, resolvedType, flags, sourceUserId, parent.id); 5186 return xpDomainInfo != null; 5187 } 5188 } 5189 return false; 5190 } 5191 5192 private UserInfo getProfileParent(int userId) { 5193 final long identity = Binder.clearCallingIdentity(); 5194 try { 5195 return sUserManager.getProfileParent(userId); 5196 } finally { 5197 Binder.restoreCallingIdentity(identity); 5198 } 5199 } 5200 5201 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5202 String resolvedType, int userId) { 5203 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5204 if (resolver != null) { 5205 return resolver.queryIntent(intent, resolvedType, false, userId); 5206 } 5207 return null; 5208 } 5209 5210 @Override 5211 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5212 String resolvedType, int flags, int userId) { 5213 try { 5214 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5215 5216 return new ParceledListSlice<>( 5217 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5218 } finally { 5219 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5220 } 5221 } 5222 5223 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5224 String resolvedType, int flags, int userId) { 5225 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5226 flags = updateFlagsForResolve(flags, userId, intent); 5227 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5228 false /* requireFullPermission */, false /* checkShell */, 5229 "query intent activities"); 5230 ComponentName comp = intent.getComponent(); 5231 if (comp == null) { 5232 if (intent.getSelector() != null) { 5233 intent = intent.getSelector(); 5234 comp = intent.getComponent(); 5235 } 5236 } 5237 5238 if (comp != null) { 5239 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5240 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5241 if (ai != null) { 5242 final ResolveInfo ri = new ResolveInfo(); 5243 ri.activityInfo = ai; 5244 list.add(ri); 5245 } 5246 return list; 5247 } 5248 5249 // reader 5250 synchronized (mPackages) { 5251 final String pkgName = intent.getPackage(); 5252 if (pkgName == null) { 5253 List<CrossProfileIntentFilter> matchingFilters = 5254 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5255 // Check for results that need to skip the current profile. 5256 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5257 resolvedType, flags, userId); 5258 if (xpResolveInfo != null) { 5259 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 5260 result.add(xpResolveInfo); 5261 return filterIfNotSystemUser(result, userId); 5262 } 5263 5264 // Check for results in the current profile. 5265 List<ResolveInfo> result = mActivities.queryIntent( 5266 intent, resolvedType, flags, userId); 5267 result = filterIfNotSystemUser(result, userId); 5268 5269 // Check for cross profile results. 5270 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5271 xpResolveInfo = queryCrossProfileIntents( 5272 matchingFilters, intent, resolvedType, flags, userId, 5273 hasNonNegativePriorityResult); 5274 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5275 boolean isVisibleToUser = filterIfNotSystemUser( 5276 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5277 if (isVisibleToUser) { 5278 result.add(xpResolveInfo); 5279 Collections.sort(result, mResolvePrioritySorter); 5280 } 5281 } 5282 if (hasWebURI(intent)) { 5283 CrossProfileDomainInfo xpDomainInfo = null; 5284 final UserInfo parent = getProfileParent(userId); 5285 if (parent != null) { 5286 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5287 flags, userId, parent.id); 5288 } 5289 if (xpDomainInfo != null) { 5290 if (xpResolveInfo != null) { 5291 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5292 // in the result. 5293 result.remove(xpResolveInfo); 5294 } 5295 if (result.size() == 0) { 5296 result.add(xpDomainInfo.resolveInfo); 5297 return result; 5298 } 5299 } else if (result.size() <= 1) { 5300 return result; 5301 } 5302 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 5303 xpDomainInfo, userId); 5304 Collections.sort(result, mResolvePrioritySorter); 5305 } 5306 return result; 5307 } 5308 final PackageParser.Package pkg = mPackages.get(pkgName); 5309 if (pkg != null) { 5310 return filterIfNotSystemUser( 5311 mActivities.queryIntentForPackage( 5312 intent, resolvedType, flags, pkg.activities, userId), 5313 userId); 5314 } 5315 return new ArrayList<ResolveInfo>(); 5316 } 5317 } 5318 5319 private static class CrossProfileDomainInfo { 5320 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5321 ResolveInfo resolveInfo; 5322 /* Best domain verification status of the activities found in the other profile */ 5323 int bestDomainVerificationStatus; 5324 } 5325 5326 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5327 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5328 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5329 sourceUserId)) { 5330 return null; 5331 } 5332 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5333 resolvedType, flags, parentUserId); 5334 5335 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5336 return null; 5337 } 5338 CrossProfileDomainInfo result = null; 5339 int size = resultTargetUser.size(); 5340 for (int i = 0; i < size; i++) { 5341 ResolveInfo riTargetUser = resultTargetUser.get(i); 5342 // Intent filter verification is only for filters that specify a host. So don't return 5343 // those that handle all web uris. 5344 if (riTargetUser.handleAllWebDataURI) { 5345 continue; 5346 } 5347 String packageName = riTargetUser.activityInfo.packageName; 5348 PackageSetting ps = mSettings.mPackages.get(packageName); 5349 if (ps == null) { 5350 continue; 5351 } 5352 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5353 int status = (int)(verificationState >> 32); 5354 if (result == null) { 5355 result = new CrossProfileDomainInfo(); 5356 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5357 sourceUserId, parentUserId); 5358 result.bestDomainVerificationStatus = status; 5359 } else { 5360 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5361 result.bestDomainVerificationStatus); 5362 } 5363 } 5364 // Don't consider matches with status NEVER across profiles. 5365 if (result != null && result.bestDomainVerificationStatus 5366 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5367 return null; 5368 } 5369 return result; 5370 } 5371 5372 /** 5373 * Verification statuses are ordered from the worse to the best, except for 5374 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5375 */ 5376 private int bestDomainVerificationStatus(int status1, int status2) { 5377 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5378 return status2; 5379 } 5380 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5381 return status1; 5382 } 5383 return (int) MathUtils.max(status1, status2); 5384 } 5385 5386 private boolean isUserEnabled(int userId) { 5387 long callingId = Binder.clearCallingIdentity(); 5388 try { 5389 UserInfo userInfo = sUserManager.getUserInfo(userId); 5390 return userInfo != null && userInfo.isEnabled(); 5391 } finally { 5392 Binder.restoreCallingIdentity(callingId); 5393 } 5394 } 5395 5396 /** 5397 * Filter out activities with systemUserOnly flag set, when current user is not System. 5398 * 5399 * @return filtered list 5400 */ 5401 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5402 if (userId == UserHandle.USER_SYSTEM) { 5403 return resolveInfos; 5404 } 5405 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5406 ResolveInfo info = resolveInfos.get(i); 5407 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5408 resolveInfos.remove(i); 5409 } 5410 } 5411 return resolveInfos; 5412 } 5413 5414 /** 5415 * @param resolveInfos list of resolve infos in descending priority order 5416 * @return if the list contains a resolve info with non-negative priority 5417 */ 5418 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5419 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5420 } 5421 5422 private static boolean hasWebURI(Intent intent) { 5423 if (intent.getData() == null) { 5424 return false; 5425 } 5426 final String scheme = intent.getScheme(); 5427 if (TextUtils.isEmpty(scheme)) { 5428 return false; 5429 } 5430 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5431 } 5432 5433 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5434 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5435 int userId) { 5436 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5437 5438 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5439 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5440 candidates.size()); 5441 } 5442 5443 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5444 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5445 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5446 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5447 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5448 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5449 5450 synchronized (mPackages) { 5451 final int count = candidates.size(); 5452 // First, try to use linked apps. Partition the candidates into four lists: 5453 // one for the final results, one for the "do not use ever", one for "undefined status" 5454 // and finally one for "browser app type". 5455 for (int n=0; n<count; n++) { 5456 ResolveInfo info = candidates.get(n); 5457 String packageName = info.activityInfo.packageName; 5458 PackageSetting ps = mSettings.mPackages.get(packageName); 5459 if (ps != null) { 5460 // Add to the special match all list (Browser use case) 5461 if (info.handleAllWebDataURI) { 5462 matchAllList.add(info); 5463 continue; 5464 } 5465 // Try to get the status from User settings first 5466 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5467 int status = (int)(packedStatus >> 32); 5468 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5469 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5470 if (DEBUG_DOMAIN_VERIFICATION) { 5471 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5472 + " : linkgen=" + linkGeneration); 5473 } 5474 // Use link-enabled generation as preferredOrder, i.e. 5475 // prefer newly-enabled over earlier-enabled. 5476 info.preferredOrder = linkGeneration; 5477 alwaysList.add(info); 5478 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5479 if (DEBUG_DOMAIN_VERIFICATION) { 5480 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5481 } 5482 neverList.add(info); 5483 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5484 if (DEBUG_DOMAIN_VERIFICATION) { 5485 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5486 } 5487 alwaysAskList.add(info); 5488 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5489 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5490 if (DEBUG_DOMAIN_VERIFICATION) { 5491 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5492 } 5493 undefinedList.add(info); 5494 } 5495 } 5496 } 5497 5498 // We'll want to include browser possibilities in a few cases 5499 boolean includeBrowser = false; 5500 5501 // First try to add the "always" resolution(s) for the current user, if any 5502 if (alwaysList.size() > 0) { 5503 result.addAll(alwaysList); 5504 } else { 5505 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5506 result.addAll(undefinedList); 5507 // Maybe add one for the other profile. 5508 if (xpDomainInfo != null && ( 5509 xpDomainInfo.bestDomainVerificationStatus 5510 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5511 result.add(xpDomainInfo.resolveInfo); 5512 } 5513 includeBrowser = true; 5514 } 5515 5516 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5517 // If there were 'always' entries their preferred order has been set, so we also 5518 // back that off to make the alternatives equivalent 5519 if (alwaysAskList.size() > 0) { 5520 for (ResolveInfo i : result) { 5521 i.preferredOrder = 0; 5522 } 5523 result.addAll(alwaysAskList); 5524 includeBrowser = true; 5525 } 5526 5527 if (includeBrowser) { 5528 // Also add browsers (all of them or only the default one) 5529 if (DEBUG_DOMAIN_VERIFICATION) { 5530 Slog.v(TAG, " ...including browsers in candidate set"); 5531 } 5532 if ((matchFlags & MATCH_ALL) != 0) { 5533 result.addAll(matchAllList); 5534 } else { 5535 // Browser/generic handling case. If there's a default browser, go straight 5536 // to that (but only if there is no other higher-priority match). 5537 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5538 int maxMatchPrio = 0; 5539 ResolveInfo defaultBrowserMatch = null; 5540 final int numCandidates = matchAllList.size(); 5541 for (int n = 0; n < numCandidates; n++) { 5542 ResolveInfo info = matchAllList.get(n); 5543 // track the highest overall match priority... 5544 if (info.priority > maxMatchPrio) { 5545 maxMatchPrio = info.priority; 5546 } 5547 // ...and the highest-priority default browser match 5548 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5549 if (defaultBrowserMatch == null 5550 || (defaultBrowserMatch.priority < info.priority)) { 5551 if (debug) { 5552 Slog.v(TAG, "Considering default browser match " + info); 5553 } 5554 defaultBrowserMatch = info; 5555 } 5556 } 5557 } 5558 if (defaultBrowserMatch != null 5559 && defaultBrowserMatch.priority >= maxMatchPrio 5560 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5561 { 5562 if (debug) { 5563 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5564 } 5565 result.add(defaultBrowserMatch); 5566 } else { 5567 result.addAll(matchAllList); 5568 } 5569 } 5570 5571 // If there is nothing selected, add all candidates and remove the ones that the user 5572 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5573 if (result.size() == 0) { 5574 result.addAll(candidates); 5575 result.removeAll(neverList); 5576 } 5577 } 5578 } 5579 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5580 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5581 result.size()); 5582 for (ResolveInfo info : result) { 5583 Slog.v(TAG, " + " + info.activityInfo); 5584 } 5585 } 5586 return result; 5587 } 5588 5589 // Returns a packed value as a long: 5590 // 5591 // high 'int'-sized word: link status: undefined/ask/never/always. 5592 // low 'int'-sized word: relative priority among 'always' results. 5593 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5594 long result = ps.getDomainVerificationStatusForUser(userId); 5595 // if none available, get the master status 5596 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5597 if (ps.getIntentFilterVerificationInfo() != null) { 5598 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5599 } 5600 } 5601 return result; 5602 } 5603 5604 private ResolveInfo querySkipCurrentProfileIntents( 5605 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5606 int flags, int sourceUserId) { 5607 if (matchingFilters != null) { 5608 int size = matchingFilters.size(); 5609 for (int i = 0; i < size; i ++) { 5610 CrossProfileIntentFilter filter = matchingFilters.get(i); 5611 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5612 // Checking if there are activities in the target user that can handle the 5613 // intent. 5614 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5615 resolvedType, flags, sourceUserId); 5616 if (resolveInfo != null) { 5617 return resolveInfo; 5618 } 5619 } 5620 } 5621 } 5622 return null; 5623 } 5624 5625 // Return matching ResolveInfo in target user if any. 5626 private ResolveInfo queryCrossProfileIntents( 5627 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5628 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5629 if (matchingFilters != null) { 5630 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5631 // match the same intent. For performance reasons, it is better not to 5632 // run queryIntent twice for the same userId 5633 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5634 int size = matchingFilters.size(); 5635 for (int i = 0; i < size; i++) { 5636 CrossProfileIntentFilter filter = matchingFilters.get(i); 5637 int targetUserId = filter.getTargetUserId(); 5638 boolean skipCurrentProfile = 5639 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5640 boolean skipCurrentProfileIfNoMatchFound = 5641 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5642 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5643 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5644 // Checking if there are activities in the target user that can handle the 5645 // intent. 5646 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5647 resolvedType, flags, sourceUserId); 5648 if (resolveInfo != null) return resolveInfo; 5649 alreadyTriedUserIds.put(targetUserId, true); 5650 } 5651 } 5652 } 5653 return null; 5654 } 5655 5656 /** 5657 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5658 * will forward the intent to the filter's target user. 5659 * Otherwise, returns null. 5660 */ 5661 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5662 String resolvedType, int flags, int sourceUserId) { 5663 int targetUserId = filter.getTargetUserId(); 5664 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5665 resolvedType, flags, targetUserId); 5666 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5667 // If all the matches in the target profile are suspended, return null. 5668 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5669 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5670 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5671 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5672 targetUserId); 5673 } 5674 } 5675 } 5676 return null; 5677 } 5678 5679 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5680 int sourceUserId, int targetUserId) { 5681 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5682 long ident = Binder.clearCallingIdentity(); 5683 boolean targetIsProfile; 5684 try { 5685 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5686 } finally { 5687 Binder.restoreCallingIdentity(ident); 5688 } 5689 String className; 5690 if (targetIsProfile) { 5691 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5692 } else { 5693 className = FORWARD_INTENT_TO_PARENT; 5694 } 5695 ComponentName forwardingActivityComponentName = new ComponentName( 5696 mAndroidApplication.packageName, className); 5697 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5698 sourceUserId); 5699 if (!targetIsProfile) { 5700 forwardingActivityInfo.showUserIcon = targetUserId; 5701 forwardingResolveInfo.noResourceId = true; 5702 } 5703 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5704 forwardingResolveInfo.priority = 0; 5705 forwardingResolveInfo.preferredOrder = 0; 5706 forwardingResolveInfo.match = 0; 5707 forwardingResolveInfo.isDefault = true; 5708 forwardingResolveInfo.filter = filter; 5709 forwardingResolveInfo.targetUserId = targetUserId; 5710 return forwardingResolveInfo; 5711 } 5712 5713 @Override 5714 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5715 Intent[] specifics, String[] specificTypes, Intent intent, 5716 String resolvedType, int flags, int userId) { 5717 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 5718 specificTypes, intent, resolvedType, flags, userId)); 5719 } 5720 5721 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 5722 Intent[] specifics, String[] specificTypes, Intent intent, 5723 String resolvedType, int flags, int userId) { 5724 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5725 flags = updateFlagsForResolve(flags, userId, intent); 5726 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5727 false /* requireFullPermission */, false /* checkShell */, 5728 "query intent activity options"); 5729 final String resultsAction = intent.getAction(); 5730 5731 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 5732 | PackageManager.GET_RESOLVED_FILTER, userId); 5733 5734 if (DEBUG_INTENT_MATCHING) { 5735 Log.v(TAG, "Query " + intent + ": " + results); 5736 } 5737 5738 int specificsPos = 0; 5739 int N; 5740 5741 // todo: note that the algorithm used here is O(N^2). This 5742 // isn't a problem in our current environment, but if we start running 5743 // into situations where we have more than 5 or 10 matches then this 5744 // should probably be changed to something smarter... 5745 5746 // First we go through and resolve each of the specific items 5747 // that were supplied, taking care of removing any corresponding 5748 // duplicate items in the generic resolve list. 5749 if (specifics != null) { 5750 for (int i=0; i<specifics.length; i++) { 5751 final Intent sintent = specifics[i]; 5752 if (sintent == null) { 5753 continue; 5754 } 5755 5756 if (DEBUG_INTENT_MATCHING) { 5757 Log.v(TAG, "Specific #" + i + ": " + sintent); 5758 } 5759 5760 String action = sintent.getAction(); 5761 if (resultsAction != null && resultsAction.equals(action)) { 5762 // If this action was explicitly requested, then don't 5763 // remove things that have it. 5764 action = null; 5765 } 5766 5767 ResolveInfo ri = null; 5768 ActivityInfo ai = null; 5769 5770 ComponentName comp = sintent.getComponent(); 5771 if (comp == null) { 5772 ri = resolveIntent( 5773 sintent, 5774 specificTypes != null ? specificTypes[i] : null, 5775 flags, userId); 5776 if (ri == null) { 5777 continue; 5778 } 5779 if (ri == mResolveInfo) { 5780 // ACK! Must do something better with this. 5781 } 5782 ai = ri.activityInfo; 5783 comp = new ComponentName(ai.applicationInfo.packageName, 5784 ai.name); 5785 } else { 5786 ai = getActivityInfo(comp, flags, userId); 5787 if (ai == null) { 5788 continue; 5789 } 5790 } 5791 5792 // Look for any generic query activities that are duplicates 5793 // of this specific one, and remove them from the results. 5794 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5795 N = results.size(); 5796 int j; 5797 for (j=specificsPos; j<N; j++) { 5798 ResolveInfo sri = results.get(j); 5799 if ((sri.activityInfo.name.equals(comp.getClassName()) 5800 && sri.activityInfo.applicationInfo.packageName.equals( 5801 comp.getPackageName())) 5802 || (action != null && sri.filter.matchAction(action))) { 5803 results.remove(j); 5804 if (DEBUG_INTENT_MATCHING) Log.v( 5805 TAG, "Removing duplicate item from " + j 5806 + " due to specific " + specificsPos); 5807 if (ri == null) { 5808 ri = sri; 5809 } 5810 j--; 5811 N--; 5812 } 5813 } 5814 5815 // Add this specific item to its proper place. 5816 if (ri == null) { 5817 ri = new ResolveInfo(); 5818 ri.activityInfo = ai; 5819 } 5820 results.add(specificsPos, ri); 5821 ri.specificIndex = i; 5822 specificsPos++; 5823 } 5824 } 5825 5826 // Now we go through the remaining generic results and remove any 5827 // duplicate actions that are found here. 5828 N = results.size(); 5829 for (int i=specificsPos; i<N-1; i++) { 5830 final ResolveInfo rii = results.get(i); 5831 if (rii.filter == null) { 5832 continue; 5833 } 5834 5835 // Iterate over all of the actions of this result's intent 5836 // filter... typically this should be just one. 5837 final Iterator<String> it = rii.filter.actionsIterator(); 5838 if (it == null) { 5839 continue; 5840 } 5841 while (it.hasNext()) { 5842 final String action = it.next(); 5843 if (resultsAction != null && resultsAction.equals(action)) { 5844 // If this action was explicitly requested, then don't 5845 // remove things that have it. 5846 continue; 5847 } 5848 for (int j=i+1; j<N; j++) { 5849 final ResolveInfo rij = results.get(j); 5850 if (rij.filter != null && rij.filter.hasAction(action)) { 5851 results.remove(j); 5852 if (DEBUG_INTENT_MATCHING) Log.v( 5853 TAG, "Removing duplicate item from " + j 5854 + " due to action " + action + " at " + i); 5855 j--; 5856 N--; 5857 } 5858 } 5859 } 5860 5861 // If the caller didn't request filter information, drop it now 5862 // so we don't have to marshall/unmarshall it. 5863 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5864 rii.filter = null; 5865 } 5866 } 5867 5868 // Filter out the caller activity if so requested. 5869 if (caller != null) { 5870 N = results.size(); 5871 for (int i=0; i<N; i++) { 5872 ActivityInfo ainfo = results.get(i).activityInfo; 5873 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5874 && caller.getClassName().equals(ainfo.name)) { 5875 results.remove(i); 5876 break; 5877 } 5878 } 5879 } 5880 5881 // If the caller didn't request filter information, 5882 // drop them now so we don't have to 5883 // marshall/unmarshall it. 5884 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5885 N = results.size(); 5886 for (int i=0; i<N; i++) { 5887 results.get(i).filter = null; 5888 } 5889 } 5890 5891 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5892 return results; 5893 } 5894 5895 @Override 5896 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 5897 String resolvedType, int flags, int userId) { 5898 return new ParceledListSlice<>( 5899 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 5900 } 5901 5902 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 5903 String resolvedType, int flags, int userId) { 5904 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5905 flags = updateFlagsForResolve(flags, userId, intent); 5906 ComponentName comp = intent.getComponent(); 5907 if (comp == null) { 5908 if (intent.getSelector() != null) { 5909 intent = intent.getSelector(); 5910 comp = intent.getComponent(); 5911 } 5912 } 5913 if (comp != null) { 5914 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5915 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5916 if (ai != null) { 5917 ResolveInfo ri = new ResolveInfo(); 5918 ri.activityInfo = ai; 5919 list.add(ri); 5920 } 5921 return list; 5922 } 5923 5924 // reader 5925 synchronized (mPackages) { 5926 String pkgName = intent.getPackage(); 5927 if (pkgName == null) { 5928 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5929 } 5930 final PackageParser.Package pkg = mPackages.get(pkgName); 5931 if (pkg != null) { 5932 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5933 userId); 5934 } 5935 return Collections.emptyList(); 5936 } 5937 } 5938 5939 @Override 5940 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5941 if (!sUserManager.exists(userId)) return null; 5942 flags = updateFlagsForResolve(flags, userId, intent); 5943 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 5944 if (query != null) { 5945 if (query.size() >= 1) { 5946 // If there is more than one service with the same priority, 5947 // just arbitrarily pick the first one. 5948 return query.get(0); 5949 } 5950 } 5951 return null; 5952 } 5953 5954 @Override 5955 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 5956 String resolvedType, int flags, int userId) { 5957 return new ParceledListSlice<>( 5958 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 5959 } 5960 5961 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 5962 String resolvedType, int flags, int userId) { 5963 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5964 flags = updateFlagsForResolve(flags, userId, intent); 5965 ComponentName comp = intent.getComponent(); 5966 if (comp == null) { 5967 if (intent.getSelector() != null) { 5968 intent = intent.getSelector(); 5969 comp = intent.getComponent(); 5970 } 5971 } 5972 if (comp != null) { 5973 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5974 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5975 if (si != null) { 5976 final ResolveInfo ri = new ResolveInfo(); 5977 ri.serviceInfo = si; 5978 list.add(ri); 5979 } 5980 return list; 5981 } 5982 5983 // reader 5984 synchronized (mPackages) { 5985 String pkgName = intent.getPackage(); 5986 if (pkgName == null) { 5987 return mServices.queryIntent(intent, resolvedType, flags, userId); 5988 } 5989 final PackageParser.Package pkg = mPackages.get(pkgName); 5990 if (pkg != null) { 5991 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5992 userId); 5993 } 5994 return Collections.emptyList(); 5995 } 5996 } 5997 5998 @Override 5999 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 6000 String resolvedType, int flags, int userId) { 6001 return new ParceledListSlice<>( 6002 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 6003 } 6004 6005 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 6006 Intent intent, String resolvedType, int flags, int userId) { 6007 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6008 flags = updateFlagsForResolve(flags, userId, intent); 6009 ComponentName comp = intent.getComponent(); 6010 if (comp == null) { 6011 if (intent.getSelector() != null) { 6012 intent = intent.getSelector(); 6013 comp = intent.getComponent(); 6014 } 6015 } 6016 if (comp != null) { 6017 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6018 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 6019 if (pi != null) { 6020 final ResolveInfo ri = new ResolveInfo(); 6021 ri.providerInfo = pi; 6022 list.add(ri); 6023 } 6024 return list; 6025 } 6026 6027 // reader 6028 synchronized (mPackages) { 6029 String pkgName = intent.getPackage(); 6030 if (pkgName == null) { 6031 return mProviders.queryIntent(intent, resolvedType, flags, userId); 6032 } 6033 final PackageParser.Package pkg = mPackages.get(pkgName); 6034 if (pkg != null) { 6035 return mProviders.queryIntentForPackage( 6036 intent, resolvedType, flags, pkg.providers, userId); 6037 } 6038 return Collections.emptyList(); 6039 } 6040 } 6041 6042 @Override 6043 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 6044 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6045 flags = updateFlagsForPackage(flags, userId, null); 6046 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6047 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6048 true /* requireFullPermission */, false /* checkShell */, 6049 "get installed packages"); 6050 6051 // writer 6052 synchronized (mPackages) { 6053 ArrayList<PackageInfo> list; 6054 if (listUninstalled) { 6055 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 6056 for (PackageSetting ps : mSettings.mPackages.values()) { 6057 final PackageInfo pi; 6058 if (ps.pkg != null) { 6059 pi = generatePackageInfo(ps, flags, userId); 6060 } else { 6061 pi = generatePackageInfo(ps, flags, userId); 6062 } 6063 if (pi != null) { 6064 list.add(pi); 6065 } 6066 } 6067 } else { 6068 list = new ArrayList<PackageInfo>(mPackages.size()); 6069 for (PackageParser.Package p : mPackages.values()) { 6070 final PackageInfo pi = 6071 generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 6072 if (pi != null) { 6073 list.add(pi); 6074 } 6075 } 6076 } 6077 6078 return new ParceledListSlice<PackageInfo>(list); 6079 } 6080 } 6081 6082 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 6083 String[] permissions, boolean[] tmp, int flags, int userId) { 6084 int numMatch = 0; 6085 final PermissionsState permissionsState = ps.getPermissionsState(); 6086 for (int i=0; i<permissions.length; i++) { 6087 final String permission = permissions[i]; 6088 if (permissionsState.hasPermission(permission, userId)) { 6089 tmp[i] = true; 6090 numMatch++; 6091 } else { 6092 tmp[i] = false; 6093 } 6094 } 6095 if (numMatch == 0) { 6096 return; 6097 } 6098 final PackageInfo pi; 6099 if (ps.pkg != null) { 6100 pi = generatePackageInfo(ps, flags, userId); 6101 } else { 6102 pi = generatePackageInfo(ps, flags, userId); 6103 } 6104 // The above might return null in cases of uninstalled apps or install-state 6105 // skew across users/profiles. 6106 if (pi != null) { 6107 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 6108 if (numMatch == permissions.length) { 6109 pi.requestedPermissions = permissions; 6110 } else { 6111 pi.requestedPermissions = new String[numMatch]; 6112 numMatch = 0; 6113 for (int i=0; i<permissions.length; i++) { 6114 if (tmp[i]) { 6115 pi.requestedPermissions[numMatch] = permissions[i]; 6116 numMatch++; 6117 } 6118 } 6119 } 6120 } 6121 list.add(pi); 6122 } 6123 } 6124 6125 @Override 6126 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 6127 String[] permissions, int flags, int userId) { 6128 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6129 flags = updateFlagsForPackage(flags, userId, permissions); 6130 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6131 6132 // writer 6133 synchronized (mPackages) { 6134 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 6135 boolean[] tmpBools = new boolean[permissions.length]; 6136 if (listUninstalled) { 6137 for (PackageSetting ps : mSettings.mPackages.values()) { 6138 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 6139 } 6140 } else { 6141 for (PackageParser.Package pkg : mPackages.values()) { 6142 PackageSetting ps = (PackageSetting)pkg.mExtras; 6143 if (ps != null) { 6144 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6145 userId); 6146 } 6147 } 6148 } 6149 6150 return new ParceledListSlice<PackageInfo>(list); 6151 } 6152 } 6153 6154 @Override 6155 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 6156 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6157 flags = updateFlagsForApplication(flags, userId, null); 6158 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6159 6160 // writer 6161 synchronized (mPackages) { 6162 ArrayList<ApplicationInfo> list; 6163 if (listUninstalled) { 6164 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 6165 for (PackageSetting ps : mSettings.mPackages.values()) { 6166 ApplicationInfo ai; 6167 if (ps.pkg != null) { 6168 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 6169 ps.readUserState(userId), userId); 6170 } else { 6171 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 6172 } 6173 if (ai != null) { 6174 list.add(ai); 6175 } 6176 } 6177 } else { 6178 list = new ArrayList<ApplicationInfo>(mPackages.size()); 6179 for (PackageParser.Package p : mPackages.values()) { 6180 if (p.mExtras != null) { 6181 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6182 ((PackageSetting)p.mExtras).readUserState(userId), userId); 6183 if (ai != null) { 6184 list.add(ai); 6185 } 6186 } 6187 } 6188 } 6189 6190 return new ParceledListSlice<ApplicationInfo>(list); 6191 } 6192 } 6193 6194 @Override 6195 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 6196 if (DISABLE_EPHEMERAL_APPS) { 6197 return null; 6198 } 6199 6200 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6201 "getEphemeralApplications"); 6202 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6203 true /* requireFullPermission */, false /* checkShell */, 6204 "getEphemeralApplications"); 6205 synchronized (mPackages) { 6206 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 6207 .getEphemeralApplicationsLPw(userId); 6208 if (ephemeralApps != null) { 6209 return new ParceledListSlice<>(ephemeralApps); 6210 } 6211 } 6212 return null; 6213 } 6214 6215 @Override 6216 public boolean isEphemeralApplication(String packageName, int userId) { 6217 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6218 true /* requireFullPermission */, false /* checkShell */, 6219 "isEphemeral"); 6220 if (DISABLE_EPHEMERAL_APPS) { 6221 return false; 6222 } 6223 6224 if (!isCallerSameApp(packageName)) { 6225 return false; 6226 } 6227 synchronized (mPackages) { 6228 PackageParser.Package pkg = mPackages.get(packageName); 6229 if (pkg != null) { 6230 return pkg.applicationInfo.isEphemeralApp(); 6231 } 6232 } 6233 return false; 6234 } 6235 6236 @Override 6237 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6238 if (DISABLE_EPHEMERAL_APPS) { 6239 return null; 6240 } 6241 6242 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6243 true /* requireFullPermission */, false /* checkShell */, 6244 "getCookie"); 6245 if (!isCallerSameApp(packageName)) { 6246 return null; 6247 } 6248 synchronized (mPackages) { 6249 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6250 packageName, userId); 6251 } 6252 } 6253 6254 @Override 6255 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6256 if (DISABLE_EPHEMERAL_APPS) { 6257 return true; 6258 } 6259 6260 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6261 true /* requireFullPermission */, true /* checkShell */, 6262 "setCookie"); 6263 if (!isCallerSameApp(packageName)) { 6264 return false; 6265 } 6266 synchronized (mPackages) { 6267 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6268 packageName, cookie, userId); 6269 } 6270 } 6271 6272 @Override 6273 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6274 if (DISABLE_EPHEMERAL_APPS) { 6275 return null; 6276 } 6277 6278 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6279 "getEphemeralApplicationIcon"); 6280 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6281 true /* requireFullPermission */, false /* checkShell */, 6282 "getEphemeralApplicationIcon"); 6283 synchronized (mPackages) { 6284 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6285 packageName, userId); 6286 } 6287 } 6288 6289 private boolean isCallerSameApp(String packageName) { 6290 PackageParser.Package pkg = mPackages.get(packageName); 6291 return pkg != null 6292 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6293 } 6294 6295 @Override 6296 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 6297 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 6298 } 6299 6300 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 6301 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6302 6303 // reader 6304 synchronized (mPackages) { 6305 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6306 final int userId = UserHandle.getCallingUserId(); 6307 while (i.hasNext()) { 6308 final PackageParser.Package p = i.next(); 6309 if (p.applicationInfo == null) continue; 6310 6311 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 6312 && !p.applicationInfo.isDirectBootAware(); 6313 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 6314 && p.applicationInfo.isDirectBootAware(); 6315 6316 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6317 && (!mSafeMode || isSystemApp(p)) 6318 && (matchesUnaware || matchesAware)) { 6319 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6320 if (ps != null) { 6321 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6322 ps.readUserState(userId), userId); 6323 if (ai != null) { 6324 finalList.add(ai); 6325 } 6326 } 6327 } 6328 } 6329 } 6330 6331 return finalList; 6332 } 6333 6334 @Override 6335 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6336 if (!sUserManager.exists(userId)) return null; 6337 flags = updateFlagsForComponent(flags, userId, name); 6338 // reader 6339 synchronized (mPackages) { 6340 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6341 PackageSetting ps = provider != null 6342 ? mSettings.mPackages.get(provider.owner.packageName) 6343 : null; 6344 return ps != null 6345 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6346 ? PackageParser.generateProviderInfo(provider, flags, 6347 ps.readUserState(userId), userId) 6348 : null; 6349 } 6350 } 6351 6352 /** 6353 * @deprecated 6354 */ 6355 @Deprecated 6356 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6357 // reader 6358 synchronized (mPackages) { 6359 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6360 .entrySet().iterator(); 6361 final int userId = UserHandle.getCallingUserId(); 6362 while (i.hasNext()) { 6363 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6364 PackageParser.Provider p = entry.getValue(); 6365 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6366 6367 if (ps != null && p.syncable 6368 && (!mSafeMode || (p.info.applicationInfo.flags 6369 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6370 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6371 ps.readUserState(userId), userId); 6372 if (info != null) { 6373 outNames.add(entry.getKey()); 6374 outInfo.add(info); 6375 } 6376 } 6377 } 6378 } 6379 } 6380 6381 @Override 6382 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6383 int uid, int flags) { 6384 final int userId = processName != null ? UserHandle.getUserId(uid) 6385 : UserHandle.getCallingUserId(); 6386 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6387 flags = updateFlagsForComponent(flags, userId, processName); 6388 6389 ArrayList<ProviderInfo> finalList = null; 6390 // reader 6391 synchronized (mPackages) { 6392 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6393 while (i.hasNext()) { 6394 final PackageParser.Provider p = i.next(); 6395 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6396 if (ps != null && p.info.authority != null 6397 && (processName == null 6398 || (p.info.processName.equals(processName) 6399 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6400 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6401 if (finalList == null) { 6402 finalList = new ArrayList<ProviderInfo>(3); 6403 } 6404 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6405 ps.readUserState(userId), userId); 6406 if (info != null) { 6407 finalList.add(info); 6408 } 6409 } 6410 } 6411 } 6412 6413 if (finalList != null) { 6414 Collections.sort(finalList, mProviderInitOrderSorter); 6415 return new ParceledListSlice<ProviderInfo>(finalList); 6416 } 6417 6418 return ParceledListSlice.emptyList(); 6419 } 6420 6421 @Override 6422 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6423 // reader 6424 synchronized (mPackages) { 6425 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6426 return PackageParser.generateInstrumentationInfo(i, flags); 6427 } 6428 } 6429 6430 @Override 6431 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 6432 String targetPackage, int flags) { 6433 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 6434 } 6435 6436 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 6437 int flags) { 6438 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 6439 6440 // reader 6441 synchronized (mPackages) { 6442 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6443 while (i.hasNext()) { 6444 final PackageParser.Instrumentation p = i.next(); 6445 if (targetPackage == null 6446 || targetPackage.equals(p.info.targetPackage)) { 6447 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6448 flags); 6449 if (ii != null) { 6450 finalList.add(ii); 6451 } 6452 } 6453 } 6454 } 6455 6456 return finalList; 6457 } 6458 6459 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6460 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6461 if (overlays == null) { 6462 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6463 return; 6464 } 6465 for (PackageParser.Package opkg : overlays.values()) { 6466 // Not much to do if idmap fails: we already logged the error 6467 // and we certainly don't want to abort installation of pkg simply 6468 // because an overlay didn't fit properly. For these reasons, 6469 // ignore the return value of createIdmapForPackagePairLI. 6470 createIdmapForPackagePairLI(pkg, opkg); 6471 } 6472 } 6473 6474 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6475 PackageParser.Package opkg) { 6476 if (!opkg.mTrustedOverlay) { 6477 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6478 opkg.baseCodePath + ": overlay not trusted"); 6479 return false; 6480 } 6481 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6482 if (overlaySet == null) { 6483 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6484 opkg.baseCodePath + " but target package has no known overlays"); 6485 return false; 6486 } 6487 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6488 // TODO: generate idmap for split APKs 6489 try { 6490 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6491 } catch (InstallerException e) { 6492 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6493 + opkg.baseCodePath); 6494 return false; 6495 } 6496 PackageParser.Package[] overlayArray = 6497 overlaySet.values().toArray(new PackageParser.Package[0]); 6498 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6499 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6500 return p1.mOverlayPriority - p2.mOverlayPriority; 6501 } 6502 }; 6503 Arrays.sort(overlayArray, cmp); 6504 6505 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6506 int i = 0; 6507 for (PackageParser.Package p : overlayArray) { 6508 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6509 } 6510 return true; 6511 } 6512 6513 private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6514 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6515 try { 6516 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6517 } finally { 6518 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6519 } 6520 } 6521 6522 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6523 final File[] files = dir.listFiles(); 6524 if (ArrayUtils.isEmpty(files)) { 6525 Log.d(TAG, "No files in app dir " + dir); 6526 return; 6527 } 6528 6529 if (DEBUG_PACKAGE_SCANNING) { 6530 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6531 + " flags=0x" + Integer.toHexString(parseFlags)); 6532 } 6533 6534 for (File file : files) { 6535 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6536 && !PackageInstallerService.isStageName(file.getName()); 6537 if (!isPackage) { 6538 // Ignore entries which are not packages 6539 continue; 6540 } 6541 try { 6542 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6543 scanFlags, currentTime, null); 6544 } catch (PackageManagerException e) { 6545 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6546 6547 // Delete invalid userdata apps 6548 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6549 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6550 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6551 removeCodePathLI(file); 6552 } 6553 } 6554 } 6555 } 6556 6557 private static File getSettingsProblemFile() { 6558 File dataDir = Environment.getDataDirectory(); 6559 File systemDir = new File(dataDir, "system"); 6560 File fname = new File(systemDir, "uiderrors.txt"); 6561 return fname; 6562 } 6563 6564 static void reportSettingsProblem(int priority, String msg) { 6565 logCriticalInfo(priority, msg); 6566 } 6567 6568 static void logCriticalInfo(int priority, String msg) { 6569 Slog.println(priority, TAG, msg); 6570 EventLogTags.writePmCriticalInfo(msg); 6571 try { 6572 File fname = getSettingsProblemFile(); 6573 FileOutputStream out = new FileOutputStream(fname, true); 6574 PrintWriter pw = new FastPrintWriter(out); 6575 SimpleDateFormat formatter = new SimpleDateFormat(); 6576 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6577 pw.println(dateString + ": " + msg); 6578 pw.close(); 6579 FileUtils.setPermissions( 6580 fname.toString(), 6581 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6582 -1, -1); 6583 } catch (java.io.IOException e) { 6584 } 6585 } 6586 6587 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6588 int parseFlags) throws PackageManagerException { 6589 if (ps != null 6590 && ps.codePath.equals(srcFile) 6591 && ps.timeStamp == srcFile.lastModified() 6592 && !isCompatSignatureUpdateNeeded(pkg) 6593 && !isRecoverSignatureUpdateNeeded(pkg)) { 6594 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6595 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6596 ArraySet<PublicKey> signingKs; 6597 synchronized (mPackages) { 6598 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6599 } 6600 if (ps.signatures.mSignatures != null 6601 && ps.signatures.mSignatures.length != 0 6602 && signingKs != null) { 6603 // Optimization: reuse the existing cached certificates 6604 // if the package appears to be unchanged. 6605 pkg.mSignatures = ps.signatures.mSignatures; 6606 pkg.mSigningKeys = signingKs; 6607 return; 6608 } 6609 6610 Slog.w(TAG, "PackageSetting for " + ps.name 6611 + " is missing signatures. Collecting certs again to recover them."); 6612 } else { 6613 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6614 } 6615 6616 try { 6617 PackageParser.collectCertificates(pkg, parseFlags); 6618 } catch (PackageParserException e) { 6619 throw PackageManagerException.from(e); 6620 } 6621 } 6622 6623 /** 6624 * Traces a package scan. 6625 * @see #scanPackageLI(File, int, int, long, UserHandle) 6626 */ 6627 private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags, 6628 long currentTime, UserHandle user) throws PackageManagerException { 6629 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6630 try { 6631 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6632 } finally { 6633 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6634 } 6635 } 6636 6637 /** 6638 * Scans a package and returns the newly parsed package. 6639 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6640 */ 6641 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6642 long currentTime, UserHandle user) throws PackageManagerException { 6643 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6644 parseFlags |= mDefParseFlags; 6645 PackageParser pp = new PackageParser(); 6646 pp.setSeparateProcesses(mSeparateProcesses); 6647 pp.setOnlyCoreApps(mOnlyCore); 6648 pp.setDisplayMetrics(mMetrics); 6649 6650 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6651 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6652 } 6653 6654 final PackageParser.Package pkg; 6655 try { 6656 pkg = pp.parsePackage(scanFile, parseFlags); 6657 } catch (PackageParserException e) { 6658 throw PackageManagerException.from(e); 6659 } 6660 6661 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6662 } 6663 6664 /** 6665 * Scans a package and returns the newly parsed package. 6666 * @throws PackageManagerException on a parse error. 6667 */ 6668 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6669 int parseFlags, int scanFlags, long currentTime, UserHandle user) 6670 throws PackageManagerException { 6671 // If the package has children and this is the first dive in the function 6672 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6673 // packages (parent and children) would be successfully scanned before the 6674 // actual scan since scanning mutates internal state and we want to atomically 6675 // install the package and its children. 6676 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6677 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6678 scanFlags |= SCAN_CHECK_ONLY; 6679 } 6680 } else { 6681 scanFlags &= ~SCAN_CHECK_ONLY; 6682 } 6683 6684 // Scan the parent 6685 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, parseFlags, 6686 scanFlags, currentTime, user); 6687 6688 // Scan the children 6689 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6690 for (int i = 0; i < childCount; i++) { 6691 PackageParser.Package childPackage = pkg.childPackages.get(i); 6692 scanPackageInternalLI(childPackage, scanFile, parseFlags, scanFlags, 6693 currentTime, user); 6694 } 6695 6696 6697 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6698 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6699 } 6700 6701 return scannedPkg; 6702 } 6703 6704 /** 6705 * Scans a package and returns the newly parsed package. 6706 * @throws PackageManagerException on a parse error. 6707 */ 6708 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6709 int parseFlags, int scanFlags, long currentTime, UserHandle user) 6710 throws PackageManagerException { 6711 PackageSetting ps = null; 6712 PackageSetting updatedPkg; 6713 // reader 6714 synchronized (mPackages) { 6715 // Look to see if we already know about this package. 6716 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6717 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6718 // This package has been renamed to its original name. Let's 6719 // use that. 6720 ps = mSettings.peekPackageLPr(oldName); 6721 } 6722 // If there was no original package, see one for the real package name. 6723 if (ps == null) { 6724 ps = mSettings.peekPackageLPr(pkg.packageName); 6725 } 6726 // Check to see if this package could be hiding/updating a system 6727 // package. Must look for it either under the original or real 6728 // package name depending on our state. 6729 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6730 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6731 6732 // If this is a package we don't know about on the system partition, we 6733 // may need to remove disabled child packages on the system partition 6734 // or may need to not add child packages if the parent apk is updated 6735 // on the data partition and no longer defines this child package. 6736 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6737 // If this is a parent package for an updated system app and this system 6738 // app got an OTA update which no longer defines some of the child packages 6739 // we have to prune them from the disabled system packages. 6740 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6741 if (disabledPs != null) { 6742 final int scannedChildCount = (pkg.childPackages != null) 6743 ? pkg.childPackages.size() : 0; 6744 final int disabledChildCount = disabledPs.childPackageNames != null 6745 ? disabledPs.childPackageNames.size() : 0; 6746 for (int i = 0; i < disabledChildCount; i++) { 6747 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6748 boolean disabledPackageAvailable = false; 6749 for (int j = 0; j < scannedChildCount; j++) { 6750 PackageParser.Package childPkg = pkg.childPackages.get(j); 6751 if (childPkg.packageName.equals(disabledChildPackageName)) { 6752 disabledPackageAvailable = true; 6753 break; 6754 } 6755 } 6756 if (!disabledPackageAvailable) { 6757 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6758 } 6759 } 6760 } 6761 } 6762 } 6763 6764 boolean updatedPkgBetter = false; 6765 // First check if this is a system package that may involve an update 6766 if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6767 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6768 // it needs to drop FLAG_PRIVILEGED. 6769 if (locationIsPrivileged(scanFile)) { 6770 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6771 } else { 6772 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6773 } 6774 6775 if (ps != null && !ps.codePath.equals(scanFile)) { 6776 // The path has changed from what was last scanned... check the 6777 // version of the new path against what we have stored to determine 6778 // what to do. 6779 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6780 if (pkg.mVersionCode <= ps.versionCode) { 6781 // The system package has been updated and the code path does not match 6782 // Ignore entry. Skip it. 6783 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6784 + " ignored: updated version " + ps.versionCode 6785 + " better than this " + pkg.mVersionCode); 6786 if (!updatedPkg.codePath.equals(scanFile)) { 6787 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6788 + ps.name + " changing from " + updatedPkg.codePathString 6789 + " to " + scanFile); 6790 updatedPkg.codePath = scanFile; 6791 updatedPkg.codePathString = scanFile.toString(); 6792 updatedPkg.resourcePath = scanFile; 6793 updatedPkg.resourcePathString = scanFile.toString(); 6794 } 6795 updatedPkg.pkg = pkg; 6796 updatedPkg.versionCode = pkg.mVersionCode; 6797 6798 // Update the disabled system child packages to point to the package too. 6799 final int childCount = updatedPkg.childPackageNames != null 6800 ? updatedPkg.childPackageNames.size() : 0; 6801 for (int i = 0; i < childCount; i++) { 6802 String childPackageName = updatedPkg.childPackageNames.get(i); 6803 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 6804 childPackageName); 6805 if (updatedChildPkg != null) { 6806 updatedChildPkg.pkg = pkg; 6807 updatedChildPkg.versionCode = pkg.mVersionCode; 6808 } 6809 } 6810 6811 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 6812 + scanFile + " ignored: updated version " + ps.versionCode 6813 + " better than this " + pkg.mVersionCode); 6814 } else { 6815 // The current app on the system partition is better than 6816 // what we have updated to on the data partition; switch 6817 // back to the system partition version. 6818 // At this point, its safely assumed that package installation for 6819 // apps in system partition will go through. If not there won't be a working 6820 // version of the app 6821 // writer 6822 synchronized (mPackages) { 6823 // Just remove the loaded entries from package lists. 6824 mPackages.remove(ps.name); 6825 } 6826 6827 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6828 + " reverting from " + ps.codePathString 6829 + ": new version " + pkg.mVersionCode 6830 + " better than installed " + ps.versionCode); 6831 6832 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6833 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6834 synchronized (mInstallLock) { 6835 args.cleanUpResourcesLI(); 6836 } 6837 synchronized (mPackages) { 6838 mSettings.enableSystemPackageLPw(ps.name); 6839 } 6840 updatedPkgBetter = true; 6841 } 6842 } 6843 } 6844 6845 if (updatedPkg != null) { 6846 // An updated system app will not have the PARSE_IS_SYSTEM flag set 6847 // initially 6848 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 6849 6850 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 6851 // flag set initially 6852 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 6853 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 6854 } 6855 } 6856 6857 // Verify certificates against what was last scanned 6858 collectCertificatesLI(ps, pkg, scanFile, parseFlags); 6859 6860 /* 6861 * A new system app appeared, but we already had a non-system one of the 6862 * same name installed earlier. 6863 */ 6864 boolean shouldHideSystemApp = false; 6865 if (updatedPkg == null && ps != null 6866 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 6867 /* 6868 * Check to make sure the signatures match first. If they don't, 6869 * wipe the installed application and its data. 6870 */ 6871 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 6872 != PackageManager.SIGNATURE_MATCH) { 6873 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 6874 + " signatures don't match existing userdata copy; removing"); 6875 try (PackageFreezer freezer = freezePackage(pkg.packageName, 6876 "scanPackageInternalLI")) { 6877 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 6878 } 6879 ps = null; 6880 } else { 6881 /* 6882 * If the newly-added system app is an older version than the 6883 * already installed version, hide it. It will be scanned later 6884 * and re-added like an update. 6885 */ 6886 if (pkg.mVersionCode <= ps.versionCode) { 6887 shouldHideSystemApp = true; 6888 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 6889 + " but new version " + pkg.mVersionCode + " better than installed " 6890 + ps.versionCode + "; hiding system"); 6891 } else { 6892 /* 6893 * The newly found system app is a newer version that the 6894 * one previously installed. Simply remove the 6895 * already-installed application and replace it with our own 6896 * while keeping the application data. 6897 */ 6898 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6899 + " reverting from " + ps.codePathString + ": new version " 6900 + pkg.mVersionCode + " better than installed " + ps.versionCode); 6901 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6902 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6903 synchronized (mInstallLock) { 6904 args.cleanUpResourcesLI(); 6905 } 6906 } 6907 } 6908 } 6909 6910 // The apk is forward locked (not public) if its code and resources 6911 // are kept in different files. (except for app in either system or 6912 // vendor path). 6913 // TODO grab this value from PackageSettings 6914 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6915 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 6916 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 6917 } 6918 } 6919 6920 // TODO: extend to support forward-locked splits 6921 String resourcePath = null; 6922 String baseResourcePath = null; 6923 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 6924 if (ps != null && ps.resourcePathString != null) { 6925 resourcePath = ps.resourcePathString; 6926 baseResourcePath = ps.resourcePathString; 6927 } else { 6928 // Should not happen at all. Just log an error. 6929 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 6930 } 6931 } else { 6932 resourcePath = pkg.codePath; 6933 baseResourcePath = pkg.baseCodePath; 6934 } 6935 6936 // Set application objects path explicitly. 6937 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 6938 pkg.setApplicationInfoCodePath(pkg.codePath); 6939 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 6940 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 6941 pkg.setApplicationInfoResourcePath(resourcePath); 6942 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 6943 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 6944 6945 // Note that we invoke the following method only if we are about to unpack an application 6946 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 6947 | SCAN_UPDATE_SIGNATURE, currentTime, user); 6948 6949 /* 6950 * If the system app should be overridden by a previously installed 6951 * data, hide the system app now and let the /data/app scan pick it up 6952 * again. 6953 */ 6954 if (shouldHideSystemApp) { 6955 synchronized (mPackages) { 6956 mSettings.disableSystemPackageLPw(pkg.packageName, true); 6957 } 6958 } 6959 6960 return scannedPkg; 6961 } 6962 6963 private static String fixProcessName(String defProcessName, 6964 String processName, int uid) { 6965 if (processName == null) { 6966 return defProcessName; 6967 } 6968 return processName; 6969 } 6970 6971 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 6972 throws PackageManagerException { 6973 if (pkgSetting.signatures.mSignatures != null) { 6974 // Already existing package. Make sure signatures match 6975 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 6976 == PackageManager.SIGNATURE_MATCH; 6977 if (!match) { 6978 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 6979 == PackageManager.SIGNATURE_MATCH; 6980 } 6981 if (!match) { 6982 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 6983 == PackageManager.SIGNATURE_MATCH; 6984 } 6985 if (!match) { 6986 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 6987 + pkg.packageName + " signatures do not match the " 6988 + "previously installed version; ignoring!"); 6989 } 6990 } 6991 6992 // Check for shared user signatures 6993 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 6994 // Already existing package. Make sure signatures match 6995 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6996 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 6997 if (!match) { 6998 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 6999 == PackageManager.SIGNATURE_MATCH; 7000 } 7001 if (!match) { 7002 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 7003 == PackageManager.SIGNATURE_MATCH; 7004 } 7005 if (!match) { 7006 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 7007 "Package " + pkg.packageName 7008 + " has no signatures that match those in shared user " 7009 + pkgSetting.sharedUser.name + "; ignoring!"); 7010 } 7011 } 7012 } 7013 7014 /** 7015 * Enforces that only the system UID or root's UID can call a method exposed 7016 * via Binder. 7017 * 7018 * @param message used as message if SecurityException is thrown 7019 * @throws SecurityException if the caller is not system or root 7020 */ 7021 private static final void enforceSystemOrRoot(String message) { 7022 final int uid = Binder.getCallingUid(); 7023 if (uid != Process.SYSTEM_UID && uid != 0) { 7024 throw new SecurityException(message); 7025 } 7026 } 7027 7028 @Override 7029 public void performFstrimIfNeeded() { 7030 enforceSystemOrRoot("Only the system can request fstrim"); 7031 7032 // Before everything else, see whether we need to fstrim. 7033 try { 7034 IMountService ms = PackageHelper.getMountService(); 7035 if (ms != null) { 7036 final boolean isUpgrade = isUpgrade(); 7037 boolean doTrim = isUpgrade; 7038 if (doTrim) { 7039 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 7040 } else { 7041 final long interval = android.provider.Settings.Global.getLong( 7042 mContext.getContentResolver(), 7043 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 7044 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 7045 if (interval > 0) { 7046 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 7047 if (timeSinceLast > interval) { 7048 doTrim = true; 7049 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 7050 + "; running immediately"); 7051 } 7052 } 7053 } 7054 if (doTrim) { 7055 if (!isFirstBoot()) { 7056 try { 7057 ActivityManagerNative.getDefault().showBootMessage( 7058 mContext.getResources().getString( 7059 R.string.android_upgrading_fstrim), true); 7060 } catch (RemoteException e) { 7061 } 7062 } 7063 ms.runMaintenance(); 7064 } 7065 } else { 7066 Slog.e(TAG, "Mount service unavailable!"); 7067 } 7068 } catch (RemoteException e) { 7069 // Can't happen; MountService is local 7070 } 7071 } 7072 7073 @Override 7074 public void updatePackagesIfNeeded() { 7075 enforceSystemOrRoot("Only the system can request package update"); 7076 7077 // We need to re-extract after an OTA. 7078 boolean causeUpgrade = isUpgrade(); 7079 7080 // First boot or factory reset. 7081 // Note: we also handle devices that are upgrading to N right now as if it is their 7082 // first boot, as they do not have profile data. 7083 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 7084 7085 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 7086 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 7087 7088 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 7089 return; 7090 } 7091 7092 List<PackageParser.Package> pkgs; 7093 synchronized (mPackages) { 7094 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 7095 } 7096 7097 int curr = 0; 7098 int total = pkgs.size(); 7099 for (PackageParser.Package pkg : pkgs) { 7100 curr++; 7101 7102 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 7103 if (DEBUG_DEXOPT) { 7104 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 7105 } 7106 continue; 7107 } 7108 7109 if (DEBUG_DEXOPT) { 7110 Log.i(TAG, "Extracting app " + curr + " of " + total + ": " + pkg.packageName); 7111 } 7112 7113 if (!isFirstBoot()) { 7114 try { 7115 ActivityManagerNative.getDefault().showBootMessage( 7116 mContext.getResources().getString(R.string.android_upgrading_apk, 7117 curr, total), true); 7118 } catch (RemoteException e) { 7119 } 7120 } 7121 7122 performDexOpt(pkg.packageName, 7123 null /* instructionSet */, 7124 false /* checkProfiles */, 7125 causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT, 7126 false /* force */); 7127 } 7128 } 7129 7130 @Override 7131 public void notifyPackageUse(String packageName) { 7132 synchronized (mPackages) { 7133 PackageParser.Package p = mPackages.get(packageName); 7134 if (p == null) { 7135 return; 7136 } 7137 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 7138 } 7139 } 7140 7141 // TODO: this is not used nor needed. Delete it. 7142 @Override 7143 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 7144 return performDexOptTraced(packageName, instructionSet, false /* checkProfiles */, 7145 getFullCompilerFilter(), false /* force */); 7146 } 7147 7148 @Override 7149 public boolean performDexOpt(String packageName, String instructionSet, 7150 boolean checkProfiles, int compileReason, boolean force) { 7151 return performDexOptTraced(packageName, instructionSet, checkProfiles, 7152 getCompilerFilterForReason(compileReason), force); 7153 } 7154 7155 @Override 7156 public boolean performDexOptMode(String packageName, String instructionSet, 7157 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7158 return performDexOptTraced(packageName, instructionSet, checkProfiles, 7159 targetCompilerFilter, force); 7160 } 7161 7162 private boolean performDexOptTraced(String packageName, String instructionSet, 7163 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7164 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7165 try { 7166 return performDexOptInternal(packageName, instructionSet, checkProfiles, 7167 targetCompilerFilter, force); 7168 } finally { 7169 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7170 } 7171 } 7172 7173 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 7174 // if the package can now be considered up to date for the given filter. 7175 private boolean performDexOptInternal(String packageName, String instructionSet, 7176 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7177 PackageParser.Package p; 7178 final String targetInstructionSet; 7179 synchronized (mPackages) { 7180 p = mPackages.get(packageName); 7181 if (p == null) { 7182 return false; 7183 } 7184 mPackageUsage.write(false); 7185 7186 targetInstructionSet = instructionSet != null ? instructionSet : 7187 getPrimaryInstructionSet(p.applicationInfo); 7188 } 7189 long callingId = Binder.clearCallingIdentity(); 7190 try { 7191 synchronized (mInstallLock) { 7192 final String[] instructionSets = new String[] { targetInstructionSet }; 7193 int result = performDexOptInternalWithDependenciesLI(p, instructionSets, 7194 checkProfiles, targetCompilerFilter, force); 7195 return result != PackageDexOptimizer.DEX_OPT_FAILED; 7196 } 7197 } finally { 7198 Binder.restoreCallingIdentity(callingId); 7199 } 7200 } 7201 7202 public ArraySet<String> getOptimizablePackages() { 7203 ArraySet<String> pkgs = new ArraySet<String>(); 7204 synchronized (mPackages) { 7205 for (PackageParser.Package p : mPackages.values()) { 7206 if (PackageDexOptimizer.canOptimizePackage(p)) { 7207 pkgs.add(p.packageName); 7208 } 7209 } 7210 } 7211 return pkgs; 7212 } 7213 7214 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7215 String instructionSets[], boolean checkProfiles, String targetCompilerFilter, 7216 boolean force) { 7217 // Select the dex optimizer based on the force parameter. 7218 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7219 // allocate an object here. 7220 PackageDexOptimizer pdo = force 7221 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7222 : mPackageDexOptimizer; 7223 7224 // Optimize all dependencies first. Note: we ignore the return value and march on 7225 // on errors. 7226 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7227 if (!deps.isEmpty()) { 7228 for (PackageParser.Package depPackage : deps) { 7229 // TODO: Analyze and investigate if we (should) profile libraries. 7230 // Currently this will do a full compilation of the library by default. 7231 pdo.performDexOpt(depPackage, instructionSets, false /* checkProfiles */, 7232 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY)); 7233 } 7234 } 7235 7236 return pdo.performDexOpt(p, instructionSets, checkProfiles, targetCompilerFilter); 7237 } 7238 7239 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7240 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7241 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7242 Set<String> collectedNames = new HashSet<>(); 7243 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7244 7245 retValue.remove(p); 7246 7247 return retValue; 7248 } else { 7249 return Collections.emptyList(); 7250 } 7251 } 7252 7253 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7254 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7255 if (!collectedNames.contains(p.packageName)) { 7256 collectedNames.add(p.packageName); 7257 collected.add(p); 7258 7259 if (p.usesLibraries != null) { 7260 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7261 } 7262 if (p.usesOptionalLibraries != null) { 7263 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7264 collectedNames); 7265 } 7266 } 7267 } 7268 7269 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7270 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7271 for (String libName : libs) { 7272 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7273 if (libPkg != null) { 7274 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7275 } 7276 } 7277 } 7278 7279 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7280 synchronized (mPackages) { 7281 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7282 if (lib != null && lib.apk != null) { 7283 return mPackages.get(lib.apk); 7284 } 7285 } 7286 return null; 7287 } 7288 7289 public void shutdown() { 7290 mPackageUsage.write(true); 7291 } 7292 7293 @Override 7294 public void forceDexOpt(String packageName) { 7295 enforceSystemOrRoot("forceDexOpt"); 7296 7297 PackageParser.Package pkg; 7298 synchronized (mPackages) { 7299 pkg = mPackages.get(packageName); 7300 if (pkg == null) { 7301 throw new IllegalArgumentException("Unknown package: " + packageName); 7302 } 7303 } 7304 7305 synchronized (mInstallLock) { 7306 final String[] instructionSets = new String[] { 7307 getPrimaryInstructionSet(pkg.applicationInfo) }; 7308 7309 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7310 7311 // Whoever is calling forceDexOpt wants a fully compiled package. 7312 // Don't use profiles since that may cause compilation to be skipped. 7313 final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets, 7314 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7315 true /* force */); 7316 7317 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7318 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7319 throw new IllegalStateException("Failed to dexopt: " + res); 7320 } 7321 } 7322 } 7323 7324 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7325 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7326 Slog.w(TAG, "Unable to update from " + oldPkg.name 7327 + " to " + newPkg.packageName 7328 + ": old package not in system partition"); 7329 return false; 7330 } else if (mPackages.get(oldPkg.name) != null) { 7331 Slog.w(TAG, "Unable to update from " + oldPkg.name 7332 + " to " + newPkg.packageName 7333 + ": old package still exists"); 7334 return false; 7335 } 7336 return true; 7337 } 7338 7339 void removeCodePathLI(File codePath) { 7340 if (codePath.isDirectory()) { 7341 try { 7342 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7343 } catch (InstallerException e) { 7344 Slog.w(TAG, "Failed to remove code path", e); 7345 } 7346 } else { 7347 codePath.delete(); 7348 } 7349 } 7350 7351 private int[] resolveUserIds(int userId) { 7352 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 7353 } 7354 7355 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7356 if (pkg == null) { 7357 Slog.wtf(TAG, "Package was null!", new Throwable()); 7358 return; 7359 } 7360 clearAppDataLeafLIF(pkg, userId, flags); 7361 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7362 for (int i = 0; i < childCount; i++) { 7363 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7364 } 7365 } 7366 7367 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7368 final PackageSetting ps; 7369 synchronized (mPackages) { 7370 ps = mSettings.mPackages.get(pkg.packageName); 7371 } 7372 for (int realUserId : resolveUserIds(userId)) { 7373 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7374 try { 7375 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7376 ceDataInode); 7377 } catch (InstallerException e) { 7378 Slog.w(TAG, String.valueOf(e)); 7379 } 7380 } 7381 } 7382 7383 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7384 if (pkg == null) { 7385 Slog.wtf(TAG, "Package was null!", new Throwable()); 7386 return; 7387 } 7388 destroyAppDataLeafLIF(pkg, userId, flags); 7389 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7390 for (int i = 0; i < childCount; i++) { 7391 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7392 } 7393 } 7394 7395 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7396 final PackageSetting ps; 7397 synchronized (mPackages) { 7398 ps = mSettings.mPackages.get(pkg.packageName); 7399 } 7400 for (int realUserId : resolveUserIds(userId)) { 7401 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7402 try { 7403 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7404 ceDataInode); 7405 } catch (InstallerException e) { 7406 Slog.w(TAG, String.valueOf(e)); 7407 } 7408 } 7409 } 7410 7411 private void destroyAppProfilesLIF(PackageParser.Package pkg) { 7412 if (pkg == null) { 7413 Slog.wtf(TAG, "Package was null!", new Throwable()); 7414 return; 7415 } 7416 destroyAppProfilesLeafLIF(pkg); 7417 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7418 for (int i = 0; i < childCount; i++) { 7419 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 7420 } 7421 } 7422 7423 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 7424 try { 7425 mInstaller.destroyAppProfiles(pkg.packageName); 7426 } catch (InstallerException e) { 7427 Slog.w(TAG, String.valueOf(e)); 7428 } 7429 } 7430 7431 private void clearAppProfilesLIF(PackageParser.Package pkg) { 7432 if (pkg == null) { 7433 Slog.wtf(TAG, "Package was null!", new Throwable()); 7434 return; 7435 } 7436 clearAppProfilesLeafLIF(pkg); 7437 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7438 for (int i = 0; i < childCount; i++) { 7439 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 7440 } 7441 } 7442 7443 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 7444 try { 7445 mInstaller.clearAppProfiles(pkg.packageName); 7446 } catch (InstallerException e) { 7447 Slog.w(TAG, String.valueOf(e)); 7448 } 7449 } 7450 7451 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7452 long lastUpdateTime) { 7453 // Set parent install/update time 7454 PackageSetting ps = (PackageSetting) pkg.mExtras; 7455 if (ps != null) { 7456 ps.firstInstallTime = firstInstallTime; 7457 ps.lastUpdateTime = lastUpdateTime; 7458 } 7459 // Set children install/update time 7460 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7461 for (int i = 0; i < childCount; i++) { 7462 PackageParser.Package childPkg = pkg.childPackages.get(i); 7463 ps = (PackageSetting) childPkg.mExtras; 7464 if (ps != null) { 7465 ps.firstInstallTime = firstInstallTime; 7466 ps.lastUpdateTime = lastUpdateTime; 7467 } 7468 } 7469 } 7470 7471 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7472 PackageParser.Package changingLib) { 7473 if (file.path != null) { 7474 usesLibraryFiles.add(file.path); 7475 return; 7476 } 7477 PackageParser.Package p = mPackages.get(file.apk); 7478 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7479 // If we are doing this while in the middle of updating a library apk, 7480 // then we need to make sure to use that new apk for determining the 7481 // dependencies here. (We haven't yet finished committing the new apk 7482 // to the package manager state.) 7483 if (p == null || p.packageName.equals(changingLib.packageName)) { 7484 p = changingLib; 7485 } 7486 } 7487 if (p != null) { 7488 usesLibraryFiles.addAll(p.getAllCodePaths()); 7489 } 7490 } 7491 7492 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7493 PackageParser.Package changingLib) throws PackageManagerException { 7494 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7495 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7496 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7497 for (int i=0; i<N; i++) { 7498 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7499 if (file == null) { 7500 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7501 "Package " + pkg.packageName + " requires unavailable shared library " 7502 + pkg.usesLibraries.get(i) + "; failing!"); 7503 } 7504 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7505 } 7506 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7507 for (int i=0; i<N; i++) { 7508 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7509 if (file == null) { 7510 Slog.w(TAG, "Package " + pkg.packageName 7511 + " desires unavailable shared library " 7512 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7513 } else { 7514 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7515 } 7516 } 7517 N = usesLibraryFiles.size(); 7518 if (N > 0) { 7519 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7520 } else { 7521 pkg.usesLibraryFiles = null; 7522 } 7523 } 7524 } 7525 7526 private static boolean hasString(List<String> list, List<String> which) { 7527 if (list == null) { 7528 return false; 7529 } 7530 for (int i=list.size()-1; i>=0; i--) { 7531 for (int j=which.size()-1; j>=0; j--) { 7532 if (which.get(j).equals(list.get(i))) { 7533 return true; 7534 } 7535 } 7536 } 7537 return false; 7538 } 7539 7540 private void updateAllSharedLibrariesLPw() { 7541 for (PackageParser.Package pkg : mPackages.values()) { 7542 try { 7543 updateSharedLibrariesLPw(pkg, null); 7544 } catch (PackageManagerException e) { 7545 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7546 } 7547 } 7548 } 7549 7550 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7551 PackageParser.Package changingPkg) { 7552 ArrayList<PackageParser.Package> res = null; 7553 for (PackageParser.Package pkg : mPackages.values()) { 7554 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7555 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7556 if (res == null) { 7557 res = new ArrayList<PackageParser.Package>(); 7558 } 7559 res.add(pkg); 7560 try { 7561 updateSharedLibrariesLPw(pkg, changingPkg); 7562 } catch (PackageManagerException e) { 7563 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7564 } 7565 } 7566 } 7567 return res; 7568 } 7569 7570 /** 7571 * Derive the value of the {@code cpuAbiOverride} based on the provided 7572 * value and an optional stored value from the package settings. 7573 */ 7574 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7575 String cpuAbiOverride = null; 7576 7577 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7578 cpuAbiOverride = null; 7579 } else if (abiOverride != null) { 7580 cpuAbiOverride = abiOverride; 7581 } else if (settings != null) { 7582 cpuAbiOverride = settings.cpuAbiOverrideString; 7583 } 7584 7585 return cpuAbiOverride; 7586 } 7587 7588 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags, 7589 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7590 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7591 // If the package has children and this is the first dive in the function 7592 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7593 // whether all packages (parent and children) would be successfully scanned 7594 // before the actual scan since scanning mutates internal state and we want 7595 // to atomically install the package and its children. 7596 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7597 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7598 scanFlags |= SCAN_CHECK_ONLY; 7599 } 7600 } else { 7601 scanFlags &= ~SCAN_CHECK_ONLY; 7602 } 7603 7604 final PackageParser.Package scannedPkg; 7605 try { 7606 // Scan the parent 7607 scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user); 7608 // Scan the children 7609 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7610 for (int i = 0; i < childCount; i++) { 7611 PackageParser.Package childPkg = pkg.childPackages.get(i); 7612 scanPackageLI(childPkg, parseFlags, 7613 scanFlags, currentTime, user); 7614 } 7615 } finally { 7616 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7617 } 7618 7619 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7620 return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user); 7621 } 7622 7623 return scannedPkg; 7624 } 7625 7626 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 7627 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7628 boolean success = false; 7629 try { 7630 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 7631 currentTime, user); 7632 success = true; 7633 return res; 7634 } finally { 7635 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 7636 // DELETE_DATA_ON_FAILURES is only used by frozen paths 7637 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 7638 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 7639 destroyAppProfilesLIF(pkg); 7640 } 7641 } 7642 } 7643 7644 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 7645 int scanFlags, long currentTime, UserHandle user) 7646 throws PackageManagerException { 7647 final File scanFile = new File(pkg.codePath); 7648 if (pkg.applicationInfo.getCodePath() == null || 7649 pkg.applicationInfo.getResourcePath() == null) { 7650 // Bail out. The resource and code paths haven't been set. 7651 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7652 "Code and resource paths haven't been set correctly"); 7653 } 7654 7655 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 7656 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 7657 } else { 7658 // Only allow system apps to be flagged as core apps. 7659 pkg.coreApp = false; 7660 } 7661 7662 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 7663 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7664 } 7665 7666 if (mCustomResolverComponentName != null && 7667 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 7668 setUpCustomResolverActivity(pkg); 7669 } 7670 7671 if (pkg.packageName.equals("android")) { 7672 synchronized (mPackages) { 7673 if (mAndroidApplication != null) { 7674 Slog.w(TAG, "*************************************************"); 7675 Slog.w(TAG, "Core android package being redefined. Skipping."); 7676 Slog.w(TAG, " file=" + scanFile); 7677 Slog.w(TAG, "*************************************************"); 7678 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7679 "Core android package being redefined. Skipping."); 7680 } 7681 7682 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7683 // Set up information for our fall-back user intent resolution activity. 7684 mPlatformPackage = pkg; 7685 pkg.mVersionCode = mSdkVersion; 7686 mAndroidApplication = pkg.applicationInfo; 7687 7688 if (!mResolverReplaced) { 7689 mResolveActivity.applicationInfo = mAndroidApplication; 7690 mResolveActivity.name = ResolverActivity.class.getName(); 7691 mResolveActivity.packageName = mAndroidApplication.packageName; 7692 mResolveActivity.processName = "system:ui"; 7693 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7694 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 7695 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 7696 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 7697 mResolveActivity.exported = true; 7698 mResolveActivity.enabled = true; 7699 mResolveInfo.activityInfo = mResolveActivity; 7700 mResolveInfo.priority = 0; 7701 mResolveInfo.preferredOrder = 0; 7702 mResolveInfo.match = 0; 7703 mResolveComponentName = new ComponentName( 7704 mAndroidApplication.packageName, mResolveActivity.name); 7705 } 7706 } 7707 } 7708 } 7709 7710 if (DEBUG_PACKAGE_SCANNING) { 7711 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7712 Log.d(TAG, "Scanning package " + pkg.packageName); 7713 } 7714 7715 synchronized (mPackages) { 7716 if (mPackages.containsKey(pkg.packageName) 7717 || mSharedLibraries.containsKey(pkg.packageName)) { 7718 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7719 "Application package " + pkg.packageName 7720 + " already installed. Skipping duplicate."); 7721 } 7722 7723 // If we're only installing presumed-existing packages, require that the 7724 // scanned APK is both already known and at the path previously established 7725 // for it. Previously unknown packages we pick up normally, but if we have an 7726 // a priori expectation about this package's install presence, enforce it. 7727 // With a singular exception for new system packages. When an OTA contains 7728 // a new system package, we allow the codepath to change from a system location 7729 // to the user-installed location. If we don't allow this change, any newer, 7730 // user-installed version of the application will be ignored. 7731 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 7732 if (mExpectingBetter.containsKey(pkg.packageName)) { 7733 logCriticalInfo(Log.WARN, 7734 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 7735 } else { 7736 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 7737 if (known != null) { 7738 if (DEBUG_PACKAGE_SCANNING) { 7739 Log.d(TAG, "Examining " + pkg.codePath 7740 + " and requiring known paths " + known.codePathString 7741 + " & " + known.resourcePathString); 7742 } 7743 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 7744 || !pkg.applicationInfo.getResourcePath().equals( 7745 known.resourcePathString)) { 7746 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 7747 "Application package " + pkg.packageName 7748 + " found at " + pkg.applicationInfo.getCodePath() 7749 + " but expected at " + known.codePathString 7750 + "; ignoring."); 7751 } 7752 } 7753 } 7754 } 7755 } 7756 7757 // Initialize package source and resource directories 7758 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 7759 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 7760 7761 SharedUserSetting suid = null; 7762 PackageSetting pkgSetting = null; 7763 7764 if (!isSystemApp(pkg)) { 7765 // Only system apps can use these features. 7766 pkg.mOriginalPackages = null; 7767 pkg.mRealPackage = null; 7768 pkg.mAdoptPermissions = null; 7769 } 7770 7771 // Getting the package setting may have a side-effect, so if we 7772 // are only checking if scan would succeed, stash a copy of the 7773 // old setting to restore at the end. 7774 PackageSetting nonMutatedPs = null; 7775 7776 // writer 7777 synchronized (mPackages) { 7778 if (pkg.mSharedUserId != null) { 7779 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 7780 if (suid == null) { 7781 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7782 "Creating application package " + pkg.packageName 7783 + " for shared user failed"); 7784 } 7785 if (DEBUG_PACKAGE_SCANNING) { 7786 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7787 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 7788 + "): packages=" + suid.packages); 7789 } 7790 } 7791 7792 // Check if we are renaming from an original package name. 7793 PackageSetting origPackage = null; 7794 String realName = null; 7795 if (pkg.mOriginalPackages != null) { 7796 // This package may need to be renamed to a previously 7797 // installed name. Let's check on that... 7798 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 7799 if (pkg.mOriginalPackages.contains(renamed)) { 7800 // This package had originally been installed as the 7801 // original name, and we have already taken care of 7802 // transitioning to the new one. Just update the new 7803 // one to continue using the old name. 7804 realName = pkg.mRealPackage; 7805 if (!pkg.packageName.equals(renamed)) { 7806 // Callers into this function may have already taken 7807 // care of renaming the package; only do it here if 7808 // it is not already done. 7809 pkg.setPackageName(renamed); 7810 } 7811 7812 } else { 7813 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 7814 if ((origPackage = mSettings.peekPackageLPr( 7815 pkg.mOriginalPackages.get(i))) != null) { 7816 // We do have the package already installed under its 7817 // original name... should we use it? 7818 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 7819 // New package is not compatible with original. 7820 origPackage = null; 7821 continue; 7822 } else if (origPackage.sharedUser != null) { 7823 // Make sure uid is compatible between packages. 7824 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 7825 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 7826 + " to " + pkg.packageName + ": old uid " 7827 + origPackage.sharedUser.name 7828 + " differs from " + pkg.mSharedUserId); 7829 origPackage = null; 7830 continue; 7831 } 7832 } else { 7833 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 7834 + pkg.packageName + " to old name " + origPackage.name); 7835 } 7836 break; 7837 } 7838 } 7839 } 7840 } 7841 7842 if (mTransferedPackages.contains(pkg.packageName)) { 7843 Slog.w(TAG, "Package " + pkg.packageName 7844 + " was transferred to another, but its .apk remains"); 7845 } 7846 7847 // See comments in nonMutatedPs declaration 7848 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7849 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 7850 if (foundPs != null) { 7851 nonMutatedPs = new PackageSetting(foundPs); 7852 } 7853 } 7854 7855 // Just create the setting, don't add it yet. For already existing packages 7856 // the PkgSetting exists already and doesn't have to be created. 7857 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 7858 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 7859 pkg.applicationInfo.primaryCpuAbi, 7860 pkg.applicationInfo.secondaryCpuAbi, 7861 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 7862 user, false); 7863 if (pkgSetting == null) { 7864 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7865 "Creating application package " + pkg.packageName + " failed"); 7866 } 7867 7868 if (pkgSetting.origPackage != null) { 7869 // If we are first transitioning from an original package, 7870 // fix up the new package's name now. We need to do this after 7871 // looking up the package under its new name, so getPackageLP 7872 // can take care of fiddling things correctly. 7873 pkg.setPackageName(origPackage.name); 7874 7875 // File a report about this. 7876 String msg = "New package " + pkgSetting.realName 7877 + " renamed to replace old package " + pkgSetting.name; 7878 reportSettingsProblem(Log.WARN, msg); 7879 7880 // Make a note of it. 7881 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7882 mTransferedPackages.add(origPackage.name); 7883 } 7884 7885 // No longer need to retain this. 7886 pkgSetting.origPackage = null; 7887 } 7888 7889 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 7890 // Make a note of it. 7891 mTransferedPackages.add(pkg.packageName); 7892 } 7893 7894 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 7895 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 7896 } 7897 7898 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7899 // Check all shared libraries and map to their actual file path. 7900 // We only do this here for apps not on a system dir, because those 7901 // are the only ones that can fail an install due to this. We 7902 // will take care of the system apps by updating all of their 7903 // library paths after the scan is done. 7904 updateSharedLibrariesLPw(pkg, null); 7905 } 7906 7907 if (mFoundPolicyFile) { 7908 SELinuxMMAC.assignSeinfoValue(pkg); 7909 } 7910 7911 pkg.applicationInfo.uid = pkgSetting.appId; 7912 pkg.mExtras = pkgSetting; 7913 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 7914 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 7915 // We just determined the app is signed correctly, so bring 7916 // over the latest parsed certs. 7917 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7918 } else { 7919 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7920 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7921 "Package " + pkg.packageName + " upgrade keys do not match the " 7922 + "previously installed version"); 7923 } else { 7924 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7925 String msg = "System package " + pkg.packageName 7926 + " signature changed; retaining data."; 7927 reportSettingsProblem(Log.WARN, msg); 7928 } 7929 } 7930 } else { 7931 try { 7932 verifySignaturesLP(pkgSetting, pkg); 7933 // We just determined the app is signed correctly, so bring 7934 // over the latest parsed certs. 7935 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7936 } catch (PackageManagerException e) { 7937 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7938 throw e; 7939 } 7940 // The signature has changed, but this package is in the system 7941 // image... let's recover! 7942 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7943 // However... if this package is part of a shared user, but it 7944 // doesn't match the signature of the shared user, let's fail. 7945 // What this means is that you can't change the signatures 7946 // associated with an overall shared user, which doesn't seem all 7947 // that unreasonable. 7948 if (pkgSetting.sharedUser != null) { 7949 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7950 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 7951 throw new PackageManagerException( 7952 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 7953 "Signature mismatch for shared user: " 7954 + pkgSetting.sharedUser); 7955 } 7956 } 7957 // File a report about this. 7958 String msg = "System package " + pkg.packageName 7959 + " signature changed; retaining data."; 7960 reportSettingsProblem(Log.WARN, msg); 7961 } 7962 } 7963 // Verify that this new package doesn't have any content providers 7964 // that conflict with existing packages. Only do this if the 7965 // package isn't already installed, since we don't want to break 7966 // things that are installed. 7967 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 7968 final int N = pkg.providers.size(); 7969 int i; 7970 for (i=0; i<N; i++) { 7971 PackageParser.Provider p = pkg.providers.get(i); 7972 if (p.info.authority != null) { 7973 String names[] = p.info.authority.split(";"); 7974 for (int j = 0; j < names.length; j++) { 7975 if (mProvidersByAuthority.containsKey(names[j])) { 7976 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7977 final String otherPackageName = 7978 ((other != null && other.getComponentName() != null) ? 7979 other.getComponentName().getPackageName() : "?"); 7980 throw new PackageManagerException( 7981 INSTALL_FAILED_CONFLICTING_PROVIDER, 7982 "Can't install because provider name " + names[j] 7983 + " (in package " + pkg.applicationInfo.packageName 7984 + ") is already used by " + otherPackageName); 7985 } 7986 } 7987 } 7988 } 7989 } 7990 7991 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 7992 // This package wants to adopt ownership of permissions from 7993 // another package. 7994 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 7995 final String origName = pkg.mAdoptPermissions.get(i); 7996 final PackageSetting orig = mSettings.peekPackageLPr(origName); 7997 if (orig != null) { 7998 if (verifyPackageUpdateLPr(orig, pkg)) { 7999 Slog.i(TAG, "Adopting permissions from " + origName + " to " 8000 + pkg.packageName); 8001 mSettings.transferPermissionsLPw(origName, pkg.packageName); 8002 } 8003 } 8004 } 8005 } 8006 } 8007 8008 final String pkgName = pkg.packageName; 8009 8010 final long scanFileTime = scanFile.lastModified(); 8011 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 8012 pkg.applicationInfo.processName = fixProcessName( 8013 pkg.applicationInfo.packageName, 8014 pkg.applicationInfo.processName, 8015 pkg.applicationInfo.uid); 8016 8017 if (pkg != mPlatformPackage) { 8018 // Get all of our default paths setup 8019 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 8020 } 8021 8022 final String path = scanFile.getPath(); 8023 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 8024 8025 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 8026 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 8027 8028 // Some system apps still use directory structure for native libraries 8029 // in which case we might end up not detecting abi solely based on apk 8030 // structure. Try to detect abi based on directory structure. 8031 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 8032 pkg.applicationInfo.primaryCpuAbi == null) { 8033 setBundledAppAbisAndRoots(pkg, pkgSetting); 8034 setNativeLibraryPaths(pkg); 8035 } 8036 8037 } else { 8038 if ((scanFlags & SCAN_MOVE) != 0) { 8039 // We haven't run dex-opt for this move (since we've moved the compiled output too) 8040 // but we already have this packages package info in the PackageSetting. We just 8041 // use that and derive the native library path based on the new codepath. 8042 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 8043 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 8044 } 8045 8046 // Set native library paths again. For moves, the path will be updated based on the 8047 // ABIs we've determined above. For non-moves, the path will be updated based on the 8048 // ABIs we determined during compilation, but the path will depend on the final 8049 // package path (after the rename away from the stage path). 8050 setNativeLibraryPaths(pkg); 8051 } 8052 8053 // This is a special case for the "system" package, where the ABI is 8054 // dictated by the zygote configuration (and init.rc). We should keep track 8055 // of this ABI so that we can deal with "normal" applications that run under 8056 // the same UID correctly. 8057 if (mPlatformPackage == pkg) { 8058 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 8059 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 8060 } 8061 8062 // If there's a mismatch between the abi-override in the package setting 8063 // and the abiOverride specified for the install. Warn about this because we 8064 // would've already compiled the app without taking the package setting into 8065 // account. 8066 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 8067 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 8068 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 8069 " for package " + pkg.packageName); 8070 } 8071 } 8072 8073 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8074 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8075 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 8076 8077 // Copy the derived override back to the parsed package, so that we can 8078 // update the package settings accordingly. 8079 pkg.cpuAbiOverride = cpuAbiOverride; 8080 8081 if (DEBUG_ABI_SELECTION) { 8082 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 8083 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 8084 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 8085 } 8086 8087 // Push the derived path down into PackageSettings so we know what to 8088 // clean up at uninstall time. 8089 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 8090 8091 if (DEBUG_ABI_SELECTION) { 8092 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 8093 " primary=" + pkg.applicationInfo.primaryCpuAbi + 8094 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 8095 } 8096 8097 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 8098 // We don't do this here during boot because we can do it all 8099 // at once after scanning all existing packages. 8100 // 8101 // We also do this *before* we perform dexopt on this package, so that 8102 // we can avoid redundant dexopts, and also to make sure we've got the 8103 // code and package path correct. 8104 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 8105 pkg, true /* boot complete */); 8106 } 8107 8108 if (mFactoryTest && pkg.requestedPermissions.contains( 8109 android.Manifest.permission.FACTORY_TEST)) { 8110 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 8111 } 8112 8113 ArrayList<PackageParser.Package> clientLibPkgs = null; 8114 8115 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8116 if (nonMutatedPs != null) { 8117 synchronized (mPackages) { 8118 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 8119 } 8120 } 8121 return pkg; 8122 } 8123 8124 // Only privileged apps and updated privileged apps can add child packages. 8125 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 8126 if ((parseFlags & PARSE_IS_PRIVILEGED) == 0) { 8127 throw new PackageManagerException("Only privileged apps and updated " 8128 + "privileged apps can add child packages. Ignoring package " 8129 + pkg.packageName); 8130 } 8131 final int childCount = pkg.childPackages.size(); 8132 for (int i = 0; i < childCount; i++) { 8133 PackageParser.Package childPkg = pkg.childPackages.get(i); 8134 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 8135 childPkg.packageName)) { 8136 throw new PackageManagerException("Cannot override a child package of " 8137 + "another disabled system app. Ignoring package " + pkg.packageName); 8138 } 8139 } 8140 } 8141 8142 // writer 8143 synchronized (mPackages) { 8144 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8145 // Only system apps can add new shared libraries. 8146 if (pkg.libraryNames != null) { 8147 for (int i=0; i<pkg.libraryNames.size(); i++) { 8148 String name = pkg.libraryNames.get(i); 8149 boolean allowed = false; 8150 if (pkg.isUpdatedSystemApp()) { 8151 // New library entries can only be added through the 8152 // system image. This is important to get rid of a lot 8153 // of nasty edge cases: for example if we allowed a non- 8154 // system update of the app to add a library, then uninstalling 8155 // the update would make the library go away, and assumptions 8156 // we made such as through app install filtering would now 8157 // have allowed apps on the device which aren't compatible 8158 // with it. Better to just have the restriction here, be 8159 // conservative, and create many fewer cases that can negatively 8160 // impact the user experience. 8161 final PackageSetting sysPs = mSettings 8162 .getDisabledSystemPkgLPr(pkg.packageName); 8163 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 8164 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 8165 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 8166 allowed = true; 8167 break; 8168 } 8169 } 8170 } 8171 } else { 8172 allowed = true; 8173 } 8174 if (allowed) { 8175 if (!mSharedLibraries.containsKey(name)) { 8176 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 8177 } else if (!name.equals(pkg.packageName)) { 8178 Slog.w(TAG, "Package " + pkg.packageName + " library " 8179 + name + " already exists; skipping"); 8180 } 8181 } else { 8182 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 8183 + name + " that is not declared on system image; skipping"); 8184 } 8185 } 8186 if ((scanFlags & SCAN_BOOTING) == 0) { 8187 // If we are not booting, we need to update any applications 8188 // that are clients of our shared library. If we are booting, 8189 // this will all be done once the scan is complete. 8190 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 8191 } 8192 } 8193 } 8194 } 8195 8196 if ((scanFlags & SCAN_BOOTING) != 0) { 8197 // No apps can run during boot scan, so they don't need to be frozen 8198 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 8199 // Caller asked to not kill app, so it's probably not frozen 8200 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 8201 // Caller asked us to ignore frozen check for some reason; they 8202 // probably didn't know the package name 8203 } else { 8204 // We're doing major surgery on this package, so it better be frozen 8205 // right now to keep it from launching 8206 checkPackageFrozen(pkgName); 8207 } 8208 8209 // Also need to kill any apps that are dependent on the library. 8210 if (clientLibPkgs != null) { 8211 for (int i=0; i<clientLibPkgs.size(); i++) { 8212 PackageParser.Package clientPkg = clientLibPkgs.get(i); 8213 killApplication(clientPkg.applicationInfo.packageName, 8214 clientPkg.applicationInfo.uid, "update lib"); 8215 } 8216 } 8217 8218 // Make sure we're not adding any bogus keyset info 8219 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8220 ksms.assertScannedPackageValid(pkg); 8221 8222 // writer 8223 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 8224 8225 boolean createIdmapFailed = false; 8226 synchronized (mPackages) { 8227 // We don't expect installation to fail beyond this point 8228 8229 // Add the new setting to mSettings 8230 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 8231 // Add the new setting to mPackages 8232 mPackages.put(pkg.applicationInfo.packageName, pkg); 8233 // Make sure we don't accidentally delete its data. 8234 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 8235 while (iter.hasNext()) { 8236 PackageCleanItem item = iter.next(); 8237 if (pkgName.equals(item.packageName)) { 8238 iter.remove(); 8239 } 8240 } 8241 8242 // Take care of first install / last update times. 8243 if (currentTime != 0) { 8244 if (pkgSetting.firstInstallTime == 0) { 8245 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8246 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 8247 pkgSetting.lastUpdateTime = currentTime; 8248 } 8249 } else if (pkgSetting.firstInstallTime == 0) { 8250 // We need *something*. Take time time stamp of the file. 8251 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8252 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8253 if (scanFileTime != pkgSetting.timeStamp) { 8254 // A package on the system image has changed; consider this 8255 // to be an update. 8256 pkgSetting.lastUpdateTime = scanFileTime; 8257 } 8258 } 8259 8260 // Add the package's KeySets to the global KeySetManagerService 8261 ksms.addScannedPackageLPw(pkg); 8262 8263 int N = pkg.providers.size(); 8264 StringBuilder r = null; 8265 int i; 8266 for (i=0; i<N; i++) { 8267 PackageParser.Provider p = pkg.providers.get(i); 8268 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 8269 p.info.processName, pkg.applicationInfo.uid); 8270 mProviders.addProvider(p); 8271 p.syncable = p.info.isSyncable; 8272 if (p.info.authority != null) { 8273 String names[] = p.info.authority.split(";"); 8274 p.info.authority = null; 8275 for (int j = 0; j < names.length; j++) { 8276 if (j == 1 && p.syncable) { 8277 // We only want the first authority for a provider to possibly be 8278 // syncable, so if we already added this provider using a different 8279 // authority clear the syncable flag. We copy the provider before 8280 // changing it because the mProviders object contains a reference 8281 // to a provider that we don't want to change. 8282 // Only do this for the second authority since the resulting provider 8283 // object can be the same for all future authorities for this provider. 8284 p = new PackageParser.Provider(p); 8285 p.syncable = false; 8286 } 8287 if (!mProvidersByAuthority.containsKey(names[j])) { 8288 mProvidersByAuthority.put(names[j], p); 8289 if (p.info.authority == null) { 8290 p.info.authority = names[j]; 8291 } else { 8292 p.info.authority = p.info.authority + ";" + names[j]; 8293 } 8294 if (DEBUG_PACKAGE_SCANNING) { 8295 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 8296 Log.d(TAG, "Registered content provider: " + names[j] 8297 + ", className = " + p.info.name + ", isSyncable = " 8298 + p.info.isSyncable); 8299 } 8300 } else { 8301 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8302 Slog.w(TAG, "Skipping provider name " + names[j] + 8303 " (in package " + pkg.applicationInfo.packageName + 8304 "): name already used by " 8305 + ((other != null && other.getComponentName() != null) 8306 ? other.getComponentName().getPackageName() : "?")); 8307 } 8308 } 8309 } 8310 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8311 if (r == null) { 8312 r = new StringBuilder(256); 8313 } else { 8314 r.append(' '); 8315 } 8316 r.append(p.info.name); 8317 } 8318 } 8319 if (r != null) { 8320 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8321 } 8322 8323 N = pkg.services.size(); 8324 r = null; 8325 for (i=0; i<N; i++) { 8326 PackageParser.Service s = pkg.services.get(i); 8327 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8328 s.info.processName, pkg.applicationInfo.uid); 8329 mServices.addService(s); 8330 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8331 if (r == null) { 8332 r = new StringBuilder(256); 8333 } else { 8334 r.append(' '); 8335 } 8336 r.append(s.info.name); 8337 } 8338 } 8339 if (r != null) { 8340 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8341 } 8342 8343 N = pkg.receivers.size(); 8344 r = null; 8345 for (i=0; i<N; i++) { 8346 PackageParser.Activity a = pkg.receivers.get(i); 8347 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8348 a.info.processName, pkg.applicationInfo.uid); 8349 mReceivers.addActivity(a, "receiver"); 8350 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8351 if (r == null) { 8352 r = new StringBuilder(256); 8353 } else { 8354 r.append(' '); 8355 } 8356 r.append(a.info.name); 8357 } 8358 } 8359 if (r != null) { 8360 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8361 } 8362 8363 N = pkg.activities.size(); 8364 r = null; 8365 for (i=0; i<N; i++) { 8366 PackageParser.Activity a = pkg.activities.get(i); 8367 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8368 a.info.processName, pkg.applicationInfo.uid); 8369 mActivities.addActivity(a, "activity"); 8370 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8371 if (r == null) { 8372 r = new StringBuilder(256); 8373 } else { 8374 r.append(' '); 8375 } 8376 r.append(a.info.name); 8377 } 8378 } 8379 if (r != null) { 8380 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8381 } 8382 8383 N = pkg.permissionGroups.size(); 8384 r = null; 8385 for (i=0; i<N; i++) { 8386 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8387 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8388 if (cur == null) { 8389 mPermissionGroups.put(pg.info.name, pg); 8390 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8391 if (r == null) { 8392 r = new StringBuilder(256); 8393 } else { 8394 r.append(' '); 8395 } 8396 r.append(pg.info.name); 8397 } 8398 } else { 8399 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8400 + pg.info.packageName + " ignored: original from " 8401 + cur.info.packageName); 8402 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8403 if (r == null) { 8404 r = new StringBuilder(256); 8405 } else { 8406 r.append(' '); 8407 } 8408 r.append("DUP:"); 8409 r.append(pg.info.name); 8410 } 8411 } 8412 } 8413 if (r != null) { 8414 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8415 } 8416 8417 N = pkg.permissions.size(); 8418 r = null; 8419 for (i=0; i<N; i++) { 8420 PackageParser.Permission p = pkg.permissions.get(i); 8421 8422 // Assume by default that we did not install this permission into the system. 8423 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8424 8425 // Now that permission groups have a special meaning, we ignore permission 8426 // groups for legacy apps to prevent unexpected behavior. In particular, 8427 // permissions for one app being granted to someone just becase they happen 8428 // to be in a group defined by another app (before this had no implications). 8429 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8430 p.group = mPermissionGroups.get(p.info.group); 8431 // Warn for a permission in an unknown group. 8432 if (p.info.group != null && p.group == null) { 8433 Slog.w(TAG, "Permission " + p.info.name + " from package " 8434 + p.info.packageName + " in an unknown group " + p.info.group); 8435 } 8436 } 8437 8438 ArrayMap<String, BasePermission> permissionMap = 8439 p.tree ? mSettings.mPermissionTrees 8440 : mSettings.mPermissions; 8441 BasePermission bp = permissionMap.get(p.info.name); 8442 8443 // Allow system apps to redefine non-system permissions 8444 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8445 final boolean currentOwnerIsSystem = (bp.perm != null 8446 && isSystemApp(bp.perm.owner)); 8447 if (isSystemApp(p.owner)) { 8448 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8449 // It's a built-in permission and no owner, take ownership now 8450 bp.packageSetting = pkgSetting; 8451 bp.perm = p; 8452 bp.uid = pkg.applicationInfo.uid; 8453 bp.sourcePackage = p.info.packageName; 8454 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8455 } else if (!currentOwnerIsSystem) { 8456 String msg = "New decl " + p.owner + " of permission " 8457 + p.info.name + " is system; overriding " + bp.sourcePackage; 8458 reportSettingsProblem(Log.WARN, msg); 8459 bp = null; 8460 } 8461 } 8462 } 8463 8464 if (bp == null) { 8465 bp = new BasePermission(p.info.name, p.info.packageName, 8466 BasePermission.TYPE_NORMAL); 8467 permissionMap.put(p.info.name, bp); 8468 } 8469 8470 if (bp.perm == null) { 8471 if (bp.sourcePackage == null 8472 || bp.sourcePackage.equals(p.info.packageName)) { 8473 BasePermission tree = findPermissionTreeLP(p.info.name); 8474 if (tree == null 8475 || tree.sourcePackage.equals(p.info.packageName)) { 8476 bp.packageSetting = pkgSetting; 8477 bp.perm = p; 8478 bp.uid = pkg.applicationInfo.uid; 8479 bp.sourcePackage = p.info.packageName; 8480 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8481 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8482 if (r == null) { 8483 r = new StringBuilder(256); 8484 } else { 8485 r.append(' '); 8486 } 8487 r.append(p.info.name); 8488 } 8489 } else { 8490 Slog.w(TAG, "Permission " + p.info.name + " from package " 8491 + p.info.packageName + " ignored: base tree " 8492 + tree.name + " is from package " 8493 + tree.sourcePackage); 8494 } 8495 } else { 8496 Slog.w(TAG, "Permission " + p.info.name + " from package " 8497 + p.info.packageName + " ignored: original from " 8498 + bp.sourcePackage); 8499 } 8500 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8501 if (r == null) { 8502 r = new StringBuilder(256); 8503 } else { 8504 r.append(' '); 8505 } 8506 r.append("DUP:"); 8507 r.append(p.info.name); 8508 } 8509 if (bp.perm == p) { 8510 bp.protectionLevel = p.info.protectionLevel; 8511 } 8512 } 8513 8514 if (r != null) { 8515 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 8516 } 8517 8518 N = pkg.instrumentation.size(); 8519 r = null; 8520 for (i=0; i<N; i++) { 8521 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8522 a.info.packageName = pkg.applicationInfo.packageName; 8523 a.info.sourceDir = pkg.applicationInfo.sourceDir; 8524 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 8525 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 8526 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 8527 a.info.dataDir = pkg.applicationInfo.dataDir; 8528 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 8529 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 8530 8531 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 8532 // need other information about the application, like the ABI and what not ? 8533 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 8534 mInstrumentation.put(a.getComponentName(), a); 8535 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8536 if (r == null) { 8537 r = new StringBuilder(256); 8538 } else { 8539 r.append(' '); 8540 } 8541 r.append(a.info.name); 8542 } 8543 } 8544 if (r != null) { 8545 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 8546 } 8547 8548 if (pkg.protectedBroadcasts != null) { 8549 N = pkg.protectedBroadcasts.size(); 8550 for (i=0; i<N; i++) { 8551 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 8552 } 8553 } 8554 8555 pkgSetting.setTimeStamp(scanFileTime); 8556 8557 // Create idmap files for pairs of (packages, overlay packages). 8558 // Note: "android", ie framework-res.apk, is handled by native layers. 8559 if (pkg.mOverlayTarget != null) { 8560 // This is an overlay package. 8561 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 8562 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 8563 mOverlays.put(pkg.mOverlayTarget, 8564 new ArrayMap<String, PackageParser.Package>()); 8565 } 8566 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 8567 map.put(pkg.packageName, pkg); 8568 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 8569 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 8570 createIdmapFailed = true; 8571 } 8572 } 8573 } else if (mOverlays.containsKey(pkg.packageName) && 8574 !pkg.packageName.equals("android")) { 8575 // This is a regular package, with one or more known overlay packages. 8576 createIdmapsForPackageLI(pkg); 8577 } 8578 } 8579 8580 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8581 8582 if (createIdmapFailed) { 8583 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8584 "scanPackageLI failed to createIdmap"); 8585 } 8586 return pkg; 8587 } 8588 8589 /** 8590 * Derive the ABI of a non-system package located at {@code scanFile}. This information 8591 * is derived purely on the basis of the contents of {@code scanFile} and 8592 * {@code cpuAbiOverride}. 8593 * 8594 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 8595 */ 8596 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 8597 String cpuAbiOverride, boolean extractLibs) 8598 throws PackageManagerException { 8599 // TODO: We can probably be smarter about this stuff. For installed apps, 8600 // we can calculate this information at install time once and for all. For 8601 // system apps, we can probably assume that this information doesn't change 8602 // after the first boot scan. As things stand, we do lots of unnecessary work. 8603 8604 // Give ourselves some initial paths; we'll come back for another 8605 // pass once we've determined ABI below. 8606 setNativeLibraryPaths(pkg); 8607 8608 // We would never need to extract libs for forward-locked and external packages, 8609 // since the container service will do it for us. We shouldn't attempt to 8610 // extract libs from system app when it was not updated. 8611 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 8612 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 8613 extractLibs = false; 8614 } 8615 8616 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 8617 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 8618 8619 NativeLibraryHelper.Handle handle = null; 8620 try { 8621 handle = NativeLibraryHelper.Handle.create(pkg); 8622 // TODO(multiArch): This can be null for apps that didn't go through the 8623 // usual installation process. We can calculate it again, like we 8624 // do during install time. 8625 // 8626 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 8627 // unnecessary. 8628 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 8629 8630 // Null out the abis so that they can be recalculated. 8631 pkg.applicationInfo.primaryCpuAbi = null; 8632 pkg.applicationInfo.secondaryCpuAbi = null; 8633 if (isMultiArch(pkg.applicationInfo)) { 8634 // Warn if we've set an abiOverride for multi-lib packages.. 8635 // By definition, we need to copy both 32 and 64 bit libraries for 8636 // such packages. 8637 if (pkg.cpuAbiOverride != null 8638 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 8639 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 8640 } 8641 8642 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 8643 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 8644 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 8645 if (extractLibs) { 8646 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8647 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 8648 useIsaSpecificSubdirs); 8649 } else { 8650 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 8651 } 8652 } 8653 8654 maybeThrowExceptionForMultiArchCopy( 8655 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 8656 8657 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 8658 if (extractLibs) { 8659 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8660 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 8661 useIsaSpecificSubdirs); 8662 } else { 8663 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 8664 } 8665 } 8666 8667 maybeThrowExceptionForMultiArchCopy( 8668 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 8669 8670 if (abi64 >= 0) { 8671 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 8672 } 8673 8674 if (abi32 >= 0) { 8675 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 8676 if (abi64 >= 0) { 8677 if (pkg.use32bitAbi) { 8678 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 8679 pkg.applicationInfo.primaryCpuAbi = abi; 8680 } else { 8681 pkg.applicationInfo.secondaryCpuAbi = abi; 8682 } 8683 } else { 8684 pkg.applicationInfo.primaryCpuAbi = abi; 8685 } 8686 } 8687 8688 } else { 8689 String[] abiList = (cpuAbiOverride != null) ? 8690 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 8691 8692 // Enable gross and lame hacks for apps that are built with old 8693 // SDK tools. We must scan their APKs for renderscript bitcode and 8694 // not launch them if it's present. Don't bother checking on devices 8695 // that don't have 64 bit support. 8696 boolean needsRenderScriptOverride = false; 8697 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 8698 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 8699 abiList = Build.SUPPORTED_32_BIT_ABIS; 8700 needsRenderScriptOverride = true; 8701 } 8702 8703 final int copyRet; 8704 if (extractLibs) { 8705 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8706 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 8707 } else { 8708 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 8709 } 8710 8711 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 8712 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 8713 "Error unpackaging native libs for app, errorCode=" + copyRet); 8714 } 8715 8716 if (copyRet >= 0) { 8717 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 8718 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 8719 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 8720 } else if (needsRenderScriptOverride) { 8721 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 8722 } 8723 } 8724 } catch (IOException ioe) { 8725 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 8726 } finally { 8727 IoUtils.closeQuietly(handle); 8728 } 8729 8730 // Now that we've calculated the ABIs and determined if it's an internal app, 8731 // we will go ahead and populate the nativeLibraryPath. 8732 setNativeLibraryPaths(pkg); 8733 } 8734 8735 /** 8736 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 8737 * i.e, so that all packages can be run inside a single process if required. 8738 * 8739 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 8740 * this function will either try and make the ABI for all packages in {@code packagesForUser} 8741 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 8742 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 8743 * updating a package that belongs to a shared user. 8744 * 8745 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 8746 * adds unnecessary complexity. 8747 */ 8748 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 8749 PackageParser.Package scannedPackage, boolean bootComplete) { 8750 String requiredInstructionSet = null; 8751 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 8752 requiredInstructionSet = VMRuntime.getInstructionSet( 8753 scannedPackage.applicationInfo.primaryCpuAbi); 8754 } 8755 8756 PackageSetting requirer = null; 8757 for (PackageSetting ps : packagesForUser) { 8758 // If packagesForUser contains scannedPackage, we skip it. This will happen 8759 // when scannedPackage is an update of an existing package. Without this check, 8760 // we will never be able to change the ABI of any package belonging to a shared 8761 // user, even if it's compatible with other packages. 8762 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8763 if (ps.primaryCpuAbiString == null) { 8764 continue; 8765 } 8766 8767 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 8768 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 8769 // We have a mismatch between instruction sets (say arm vs arm64) warn about 8770 // this but there's not much we can do. 8771 String errorMessage = "Instruction set mismatch, " 8772 + ((requirer == null) ? "[caller]" : requirer) 8773 + " requires " + requiredInstructionSet + " whereas " + ps 8774 + " requires " + instructionSet; 8775 Slog.w(TAG, errorMessage); 8776 } 8777 8778 if (requiredInstructionSet == null) { 8779 requiredInstructionSet = instructionSet; 8780 requirer = ps; 8781 } 8782 } 8783 } 8784 8785 if (requiredInstructionSet != null) { 8786 String adjustedAbi; 8787 if (requirer != null) { 8788 // requirer != null implies that either scannedPackage was null or that scannedPackage 8789 // did not require an ABI, in which case we have to adjust scannedPackage to match 8790 // the ABI of the set (which is the same as requirer's ABI) 8791 adjustedAbi = requirer.primaryCpuAbiString; 8792 if (scannedPackage != null) { 8793 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 8794 } 8795 } else { 8796 // requirer == null implies that we're updating all ABIs in the set to 8797 // match scannedPackage. 8798 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 8799 } 8800 8801 for (PackageSetting ps : packagesForUser) { 8802 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8803 if (ps.primaryCpuAbiString != null) { 8804 continue; 8805 } 8806 8807 ps.primaryCpuAbiString = adjustedAbi; 8808 if (ps.pkg != null && ps.pkg.applicationInfo != null && 8809 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 8810 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 8811 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 8812 + " (requirer=" 8813 + (requirer == null ? "null" : requirer.pkg.packageName) 8814 + ", scannedPackage=" 8815 + (scannedPackage != null ? scannedPackage.packageName : "null") 8816 + ")"); 8817 try { 8818 mInstaller.rmdex(ps.codePathString, 8819 getDexCodeInstructionSet(getPreferredInstructionSet())); 8820 } catch (InstallerException ignored) { 8821 } 8822 } 8823 } 8824 } 8825 } 8826 } 8827 8828 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 8829 synchronized (mPackages) { 8830 mResolverReplaced = true; 8831 // Set up information for custom user intent resolution activity. 8832 mResolveActivity.applicationInfo = pkg.applicationInfo; 8833 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 8834 mResolveActivity.packageName = pkg.applicationInfo.packageName; 8835 mResolveActivity.processName = pkg.applicationInfo.packageName; 8836 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8837 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8838 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8839 mResolveActivity.theme = 0; 8840 mResolveActivity.exported = true; 8841 mResolveActivity.enabled = true; 8842 mResolveInfo.activityInfo = mResolveActivity; 8843 mResolveInfo.priority = 0; 8844 mResolveInfo.preferredOrder = 0; 8845 mResolveInfo.match = 0; 8846 mResolveComponentName = mCustomResolverComponentName; 8847 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 8848 mResolveComponentName); 8849 } 8850 } 8851 8852 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 8853 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 8854 8855 // Set up information for ephemeral installer activity 8856 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 8857 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 8858 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 8859 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 8860 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8861 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8862 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8863 mEphemeralInstallerActivity.theme = 0; 8864 mEphemeralInstallerActivity.exported = true; 8865 mEphemeralInstallerActivity.enabled = true; 8866 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 8867 mEphemeralInstallerInfo.priority = 0; 8868 mEphemeralInstallerInfo.preferredOrder = 0; 8869 mEphemeralInstallerInfo.match = 0; 8870 8871 if (DEBUG_EPHEMERAL) { 8872 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 8873 } 8874 } 8875 8876 private static String calculateBundledApkRoot(final String codePathString) { 8877 final File codePath = new File(codePathString); 8878 final File codeRoot; 8879 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 8880 codeRoot = Environment.getRootDirectory(); 8881 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 8882 codeRoot = Environment.getOemDirectory(); 8883 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 8884 codeRoot = Environment.getVendorDirectory(); 8885 } else { 8886 // Unrecognized code path; take its top real segment as the apk root: 8887 // e.g. /something/app/blah.apk => /something 8888 try { 8889 File f = codePath.getCanonicalFile(); 8890 File parent = f.getParentFile(); // non-null because codePath is a file 8891 File tmp; 8892 while ((tmp = parent.getParentFile()) != null) { 8893 f = parent; 8894 parent = tmp; 8895 } 8896 codeRoot = f; 8897 Slog.w(TAG, "Unrecognized code path " 8898 + codePath + " - using " + codeRoot); 8899 } catch (IOException e) { 8900 // Can't canonicalize the code path -- shenanigans? 8901 Slog.w(TAG, "Can't canonicalize code path " + codePath); 8902 return Environment.getRootDirectory().getPath(); 8903 } 8904 } 8905 return codeRoot.getPath(); 8906 } 8907 8908 /** 8909 * Derive and set the location of native libraries for the given package, 8910 * which varies depending on where and how the package was installed. 8911 */ 8912 private void setNativeLibraryPaths(PackageParser.Package pkg) { 8913 final ApplicationInfo info = pkg.applicationInfo; 8914 final String codePath = pkg.codePath; 8915 final File codeFile = new File(codePath); 8916 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 8917 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 8918 8919 info.nativeLibraryRootDir = null; 8920 info.nativeLibraryRootRequiresIsa = false; 8921 info.nativeLibraryDir = null; 8922 info.secondaryNativeLibraryDir = null; 8923 8924 if (isApkFile(codeFile)) { 8925 // Monolithic install 8926 if (bundledApp) { 8927 // If "/system/lib64/apkname" exists, assume that is the per-package 8928 // native library directory to use; otherwise use "/system/lib/apkname". 8929 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 8930 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 8931 getPrimaryInstructionSet(info)); 8932 8933 // This is a bundled system app so choose the path based on the ABI. 8934 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 8935 // is just the default path. 8936 final String apkName = deriveCodePathName(codePath); 8937 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 8938 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 8939 apkName).getAbsolutePath(); 8940 8941 if (info.secondaryCpuAbi != null) { 8942 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 8943 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 8944 secondaryLibDir, apkName).getAbsolutePath(); 8945 } 8946 } else if (asecApp) { 8947 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 8948 .getAbsolutePath(); 8949 } else { 8950 final String apkName = deriveCodePathName(codePath); 8951 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 8952 .getAbsolutePath(); 8953 } 8954 8955 info.nativeLibraryRootRequiresIsa = false; 8956 info.nativeLibraryDir = info.nativeLibraryRootDir; 8957 } else { 8958 // Cluster install 8959 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 8960 info.nativeLibraryRootRequiresIsa = true; 8961 8962 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 8963 getPrimaryInstructionSet(info)).getAbsolutePath(); 8964 8965 if (info.secondaryCpuAbi != null) { 8966 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 8967 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 8968 } 8969 } 8970 } 8971 8972 /** 8973 * Calculate the abis and roots for a bundled app. These can uniquely 8974 * be determined from the contents of the system partition, i.e whether 8975 * it contains 64 or 32 bit shared libraries etc. We do not validate any 8976 * of this information, and instead assume that the system was built 8977 * sensibly. 8978 */ 8979 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 8980 PackageSetting pkgSetting) { 8981 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 8982 8983 // If "/system/lib64/apkname" exists, assume that is the per-package 8984 // native library directory to use; otherwise use "/system/lib/apkname". 8985 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 8986 setBundledAppAbi(pkg, apkRoot, apkName); 8987 // pkgSetting might be null during rescan following uninstall of updates 8988 // to a bundled app, so accommodate that possibility. The settings in 8989 // that case will be established later from the parsed package. 8990 // 8991 // If the settings aren't null, sync them up with what we've just derived. 8992 // note that apkRoot isn't stored in the package settings. 8993 if (pkgSetting != null) { 8994 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8995 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8996 } 8997 } 8998 8999 /** 9000 * Deduces the ABI of a bundled app and sets the relevant fields on the 9001 * parsed pkg object. 9002 * 9003 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 9004 * under which system libraries are installed. 9005 * @param apkName the name of the installed package. 9006 */ 9007 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 9008 final File codeFile = new File(pkg.codePath); 9009 9010 final boolean has64BitLibs; 9011 final boolean has32BitLibs; 9012 if (isApkFile(codeFile)) { 9013 // Monolithic install 9014 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 9015 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 9016 } else { 9017 // Cluster install 9018 final File rootDir = new File(codeFile, LIB_DIR_NAME); 9019 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 9020 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 9021 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 9022 has64BitLibs = (new File(rootDir, isa)).exists(); 9023 } else { 9024 has64BitLibs = false; 9025 } 9026 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 9027 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 9028 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 9029 has32BitLibs = (new File(rootDir, isa)).exists(); 9030 } else { 9031 has32BitLibs = false; 9032 } 9033 } 9034 9035 if (has64BitLibs && !has32BitLibs) { 9036 // The package has 64 bit libs, but not 32 bit libs. Its primary 9037 // ABI should be 64 bit. We can safely assume here that the bundled 9038 // native libraries correspond to the most preferred ABI in the list. 9039 9040 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9041 pkg.applicationInfo.secondaryCpuAbi = null; 9042 } else if (has32BitLibs && !has64BitLibs) { 9043 // The package has 32 bit libs but not 64 bit libs. Its primary 9044 // ABI should be 32 bit. 9045 9046 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9047 pkg.applicationInfo.secondaryCpuAbi = null; 9048 } else if (has32BitLibs && has64BitLibs) { 9049 // The application has both 64 and 32 bit bundled libraries. We check 9050 // here that the app declares multiArch support, and warn if it doesn't. 9051 // 9052 // We will be lenient here and record both ABIs. The primary will be the 9053 // ABI that's higher on the list, i.e, a device that's configured to prefer 9054 // 64 bit apps will see a 64 bit primary ABI, 9055 9056 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 9057 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 9058 } 9059 9060 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 9061 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9062 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9063 } else { 9064 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9065 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9066 } 9067 } else { 9068 pkg.applicationInfo.primaryCpuAbi = null; 9069 pkg.applicationInfo.secondaryCpuAbi = null; 9070 } 9071 } 9072 9073 private void killApplication(String pkgName, int appId, String reason) { 9074 // Request the ActivityManager to kill the process(only for existing packages) 9075 // so that we do not end up in a confused state while the user is still using the older 9076 // version of the application while the new one gets installed. 9077 final long token = Binder.clearCallingIdentity(); 9078 try { 9079 IActivityManager am = ActivityManagerNative.getDefault(); 9080 if (am != null) { 9081 try { 9082 am.killApplicationWithAppId(pkgName, appId, reason); 9083 } catch (RemoteException e) { 9084 } 9085 } 9086 } finally { 9087 Binder.restoreCallingIdentity(token); 9088 } 9089 } 9090 9091 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 9092 // Remove the parent package setting 9093 PackageSetting ps = (PackageSetting) pkg.mExtras; 9094 if (ps != null) { 9095 removePackageLI(ps, chatty); 9096 } 9097 // Remove the child package setting 9098 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9099 for (int i = 0; i < childCount; i++) { 9100 PackageParser.Package childPkg = pkg.childPackages.get(i); 9101 ps = (PackageSetting) childPkg.mExtras; 9102 if (ps != null) { 9103 removePackageLI(ps, chatty); 9104 } 9105 } 9106 } 9107 9108 void removePackageLI(PackageSetting ps, boolean chatty) { 9109 if (DEBUG_INSTALL) { 9110 if (chatty) 9111 Log.d(TAG, "Removing package " + ps.name); 9112 } 9113 9114 // writer 9115 synchronized (mPackages) { 9116 mPackages.remove(ps.name); 9117 final PackageParser.Package pkg = ps.pkg; 9118 if (pkg != null) { 9119 cleanPackageDataStructuresLILPw(pkg, chatty); 9120 } 9121 } 9122 } 9123 9124 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 9125 if (DEBUG_INSTALL) { 9126 if (chatty) 9127 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 9128 } 9129 9130 // writer 9131 synchronized (mPackages) { 9132 // Remove the parent package 9133 mPackages.remove(pkg.applicationInfo.packageName); 9134 cleanPackageDataStructuresLILPw(pkg, chatty); 9135 9136 // Remove the child packages 9137 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9138 for (int i = 0; i < childCount; i++) { 9139 PackageParser.Package childPkg = pkg.childPackages.get(i); 9140 mPackages.remove(childPkg.applicationInfo.packageName); 9141 cleanPackageDataStructuresLILPw(childPkg, chatty); 9142 } 9143 } 9144 } 9145 9146 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 9147 int N = pkg.providers.size(); 9148 StringBuilder r = null; 9149 int i; 9150 for (i=0; i<N; i++) { 9151 PackageParser.Provider p = pkg.providers.get(i); 9152 mProviders.removeProvider(p); 9153 if (p.info.authority == null) { 9154 9155 /* There was another ContentProvider with this authority when 9156 * this app was installed so this authority is null, 9157 * Ignore it as we don't have to unregister the provider. 9158 */ 9159 continue; 9160 } 9161 String names[] = p.info.authority.split(";"); 9162 for (int j = 0; j < names.length; j++) { 9163 if (mProvidersByAuthority.get(names[j]) == p) { 9164 mProvidersByAuthority.remove(names[j]); 9165 if (DEBUG_REMOVE) { 9166 if (chatty) 9167 Log.d(TAG, "Unregistered content provider: " + names[j] 9168 + ", className = " + p.info.name + ", isSyncable = " 9169 + p.info.isSyncable); 9170 } 9171 } 9172 } 9173 if (DEBUG_REMOVE && chatty) { 9174 if (r == null) { 9175 r = new StringBuilder(256); 9176 } else { 9177 r.append(' '); 9178 } 9179 r.append(p.info.name); 9180 } 9181 } 9182 if (r != null) { 9183 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 9184 } 9185 9186 N = pkg.services.size(); 9187 r = null; 9188 for (i=0; i<N; i++) { 9189 PackageParser.Service s = pkg.services.get(i); 9190 mServices.removeService(s); 9191 if (chatty) { 9192 if (r == null) { 9193 r = new StringBuilder(256); 9194 } else { 9195 r.append(' '); 9196 } 9197 r.append(s.info.name); 9198 } 9199 } 9200 if (r != null) { 9201 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 9202 } 9203 9204 N = pkg.receivers.size(); 9205 r = null; 9206 for (i=0; i<N; i++) { 9207 PackageParser.Activity a = pkg.receivers.get(i); 9208 mReceivers.removeActivity(a, "receiver"); 9209 if (DEBUG_REMOVE && chatty) { 9210 if (r == null) { 9211 r = new StringBuilder(256); 9212 } else { 9213 r.append(' '); 9214 } 9215 r.append(a.info.name); 9216 } 9217 } 9218 if (r != null) { 9219 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 9220 } 9221 9222 N = pkg.activities.size(); 9223 r = null; 9224 for (i=0; i<N; i++) { 9225 PackageParser.Activity a = pkg.activities.get(i); 9226 mActivities.removeActivity(a, "activity"); 9227 if (DEBUG_REMOVE && chatty) { 9228 if (r == null) { 9229 r = new StringBuilder(256); 9230 } else { 9231 r.append(' '); 9232 } 9233 r.append(a.info.name); 9234 } 9235 } 9236 if (r != null) { 9237 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 9238 } 9239 9240 N = pkg.permissions.size(); 9241 r = null; 9242 for (i=0; i<N; i++) { 9243 PackageParser.Permission p = pkg.permissions.get(i); 9244 BasePermission bp = mSettings.mPermissions.get(p.info.name); 9245 if (bp == null) { 9246 bp = mSettings.mPermissionTrees.get(p.info.name); 9247 } 9248 if (bp != null && bp.perm == p) { 9249 bp.perm = null; 9250 if (DEBUG_REMOVE && chatty) { 9251 if (r == null) { 9252 r = new StringBuilder(256); 9253 } else { 9254 r.append(' '); 9255 } 9256 r.append(p.info.name); 9257 } 9258 } 9259 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9260 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 9261 if (appOpPkgs != null) { 9262 appOpPkgs.remove(pkg.packageName); 9263 } 9264 } 9265 } 9266 if (r != null) { 9267 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9268 } 9269 9270 N = pkg.requestedPermissions.size(); 9271 r = null; 9272 for (i=0; i<N; i++) { 9273 String perm = pkg.requestedPermissions.get(i); 9274 BasePermission bp = mSettings.mPermissions.get(perm); 9275 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9276 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 9277 if (appOpPkgs != null) { 9278 appOpPkgs.remove(pkg.packageName); 9279 if (appOpPkgs.isEmpty()) { 9280 mAppOpPermissionPackages.remove(perm); 9281 } 9282 } 9283 } 9284 } 9285 if (r != null) { 9286 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9287 } 9288 9289 N = pkg.instrumentation.size(); 9290 r = null; 9291 for (i=0; i<N; i++) { 9292 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9293 mInstrumentation.remove(a.getComponentName()); 9294 if (DEBUG_REMOVE && chatty) { 9295 if (r == null) { 9296 r = new StringBuilder(256); 9297 } else { 9298 r.append(' '); 9299 } 9300 r.append(a.info.name); 9301 } 9302 } 9303 if (r != null) { 9304 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9305 } 9306 9307 r = null; 9308 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9309 // Only system apps can hold shared libraries. 9310 if (pkg.libraryNames != null) { 9311 for (i=0; i<pkg.libraryNames.size(); i++) { 9312 String name = pkg.libraryNames.get(i); 9313 SharedLibraryEntry cur = mSharedLibraries.get(name); 9314 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9315 mSharedLibraries.remove(name); 9316 if (DEBUG_REMOVE && chatty) { 9317 if (r == null) { 9318 r = new StringBuilder(256); 9319 } else { 9320 r.append(' '); 9321 } 9322 r.append(name); 9323 } 9324 } 9325 } 9326 } 9327 } 9328 if (r != null) { 9329 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9330 } 9331 } 9332 9333 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9334 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9335 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9336 return true; 9337 } 9338 } 9339 return false; 9340 } 9341 9342 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9343 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9344 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9345 9346 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9347 // Update the parent permissions 9348 updatePermissionsLPw(pkg.packageName, pkg, flags); 9349 // Update the child permissions 9350 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9351 for (int i = 0; i < childCount; i++) { 9352 PackageParser.Package childPkg = pkg.childPackages.get(i); 9353 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9354 } 9355 } 9356 9357 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9358 int flags) { 9359 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9360 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9361 } 9362 9363 private void updatePermissionsLPw(String changingPkg, 9364 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9365 // Make sure there are no dangling permission trees. 9366 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9367 while (it.hasNext()) { 9368 final BasePermission bp = it.next(); 9369 if (bp.packageSetting == null) { 9370 // We may not yet have parsed the package, so just see if 9371 // we still know about its settings. 9372 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9373 } 9374 if (bp.packageSetting == null) { 9375 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9376 + " from package " + bp.sourcePackage); 9377 it.remove(); 9378 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9379 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9380 Slog.i(TAG, "Removing old permission tree: " + bp.name 9381 + " from package " + bp.sourcePackage); 9382 flags |= UPDATE_PERMISSIONS_ALL; 9383 it.remove(); 9384 } 9385 } 9386 } 9387 9388 // Make sure all dynamic permissions have been assigned to a package, 9389 // and make sure there are no dangling permissions. 9390 it = mSettings.mPermissions.values().iterator(); 9391 while (it.hasNext()) { 9392 final BasePermission bp = it.next(); 9393 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9394 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9395 + bp.name + " pkg=" + bp.sourcePackage 9396 + " info=" + bp.pendingInfo); 9397 if (bp.packageSetting == null && bp.pendingInfo != null) { 9398 final BasePermission tree = findPermissionTreeLP(bp.name); 9399 if (tree != null && tree.perm != null) { 9400 bp.packageSetting = tree.packageSetting; 9401 bp.perm = new PackageParser.Permission(tree.perm.owner, 9402 new PermissionInfo(bp.pendingInfo)); 9403 bp.perm.info.packageName = tree.perm.info.packageName; 9404 bp.perm.info.name = bp.name; 9405 bp.uid = tree.uid; 9406 } 9407 } 9408 } 9409 if (bp.packageSetting == null) { 9410 // We may not yet have parsed the package, so just see if 9411 // we still know about its settings. 9412 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9413 } 9414 if (bp.packageSetting == null) { 9415 Slog.w(TAG, "Removing dangling permission: " + bp.name 9416 + " from package " + bp.sourcePackage); 9417 it.remove(); 9418 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9419 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9420 Slog.i(TAG, "Removing old permission: " + bp.name 9421 + " from package " + bp.sourcePackage); 9422 flags |= UPDATE_PERMISSIONS_ALL; 9423 it.remove(); 9424 } 9425 } 9426 } 9427 9428 // Now update the permissions for all packages, in particular 9429 // replace the granted permissions of the system packages. 9430 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9431 for (PackageParser.Package pkg : mPackages.values()) { 9432 if (pkg != pkgInfo) { 9433 // Only replace for packages on requested volume 9434 final String volumeUuid = getVolumeUuidForPackage(pkg); 9435 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9436 && Objects.equals(replaceVolumeUuid, volumeUuid); 9437 grantPermissionsLPw(pkg, replace, changingPkg); 9438 } 9439 } 9440 } 9441 9442 if (pkgInfo != null) { 9443 // Only replace for packages on requested volume 9444 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9445 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9446 && Objects.equals(replaceVolumeUuid, volumeUuid); 9447 grantPermissionsLPw(pkgInfo, replace, changingPkg); 9448 } 9449 } 9450 9451 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 9452 String packageOfInterest) { 9453 // IMPORTANT: There are two types of permissions: install and runtime. 9454 // Install time permissions are granted when the app is installed to 9455 // all device users and users added in the future. Runtime permissions 9456 // are granted at runtime explicitly to specific users. Normal and signature 9457 // protected permissions are install time permissions. Dangerous permissions 9458 // are install permissions if the app's target SDK is Lollipop MR1 or older, 9459 // otherwise they are runtime permissions. This function does not manage 9460 // runtime permissions except for the case an app targeting Lollipop MR1 9461 // being upgraded to target a newer SDK, in which case dangerous permissions 9462 // are transformed from install time to runtime ones. 9463 9464 final PackageSetting ps = (PackageSetting) pkg.mExtras; 9465 if (ps == null) { 9466 return; 9467 } 9468 9469 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 9470 9471 PermissionsState permissionsState = ps.getPermissionsState(); 9472 PermissionsState origPermissions = permissionsState; 9473 9474 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 9475 9476 boolean runtimePermissionsRevoked = false; 9477 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 9478 9479 boolean changedInstallPermission = false; 9480 9481 if (replace) { 9482 ps.installPermissionsFixed = false; 9483 if (!ps.isSharedUser()) { 9484 origPermissions = new PermissionsState(permissionsState); 9485 permissionsState.reset(); 9486 } else { 9487 // We need to know only about runtime permission changes since the 9488 // calling code always writes the install permissions state but 9489 // the runtime ones are written only if changed. The only cases of 9490 // changed runtime permissions here are promotion of an install to 9491 // runtime and revocation of a runtime from a shared user. 9492 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 9493 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 9494 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 9495 runtimePermissionsRevoked = true; 9496 } 9497 } 9498 } 9499 9500 permissionsState.setGlobalGids(mGlobalGids); 9501 9502 final int N = pkg.requestedPermissions.size(); 9503 for (int i=0; i<N; i++) { 9504 final String name = pkg.requestedPermissions.get(i); 9505 final BasePermission bp = mSettings.mPermissions.get(name); 9506 9507 if (DEBUG_INSTALL) { 9508 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 9509 } 9510 9511 if (bp == null || bp.packageSetting == null) { 9512 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9513 Slog.w(TAG, "Unknown permission " + name 9514 + " in package " + pkg.packageName); 9515 } 9516 continue; 9517 } 9518 9519 final String perm = bp.name; 9520 boolean allowedSig = false; 9521 int grant = GRANT_DENIED; 9522 9523 // Keep track of app op permissions. 9524 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9525 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 9526 if (pkgs == null) { 9527 pkgs = new ArraySet<>(); 9528 mAppOpPermissionPackages.put(bp.name, pkgs); 9529 } 9530 pkgs.add(pkg.packageName); 9531 } 9532 9533 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 9534 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 9535 >= Build.VERSION_CODES.M; 9536 switch (level) { 9537 case PermissionInfo.PROTECTION_NORMAL: { 9538 // For all apps normal permissions are install time ones. 9539 grant = GRANT_INSTALL; 9540 } break; 9541 9542 case PermissionInfo.PROTECTION_DANGEROUS: { 9543 // If a permission review is required for legacy apps we represent 9544 // their permissions as always granted runtime ones since we need 9545 // to keep the review required permission flag per user while an 9546 // install permission's state is shared across all users. 9547 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 9548 // For legacy apps dangerous permissions are install time ones. 9549 grant = GRANT_INSTALL; 9550 } else if (origPermissions.hasInstallPermission(bp.name)) { 9551 // For legacy apps that became modern, install becomes runtime. 9552 grant = GRANT_UPGRADE; 9553 } else if (mPromoteSystemApps 9554 && isSystemApp(ps) 9555 && mExistingSystemPackages.contains(ps.name)) { 9556 // For legacy system apps, install becomes runtime. 9557 // We cannot check hasInstallPermission() for system apps since those 9558 // permissions were granted implicitly and not persisted pre-M. 9559 grant = GRANT_UPGRADE; 9560 } else { 9561 // For modern apps keep runtime permissions unchanged. 9562 grant = GRANT_RUNTIME; 9563 } 9564 } break; 9565 9566 case PermissionInfo.PROTECTION_SIGNATURE: { 9567 // For all apps signature permissions are install time ones. 9568 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 9569 if (allowedSig) { 9570 grant = GRANT_INSTALL; 9571 } 9572 } break; 9573 } 9574 9575 if (DEBUG_INSTALL) { 9576 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 9577 } 9578 9579 if (grant != GRANT_DENIED) { 9580 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 9581 // If this is an existing, non-system package, then 9582 // we can't add any new permissions to it. 9583 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 9584 // Except... if this is a permission that was added 9585 // to the platform (note: need to only do this when 9586 // updating the platform). 9587 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 9588 grant = GRANT_DENIED; 9589 } 9590 } 9591 } 9592 9593 switch (grant) { 9594 case GRANT_INSTALL: { 9595 // Revoke this as runtime permission to handle the case of 9596 // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps 9597 for (int userId : UserManagerService.getInstance().getUserIds()) { 9598 if (origPermissions.getRuntimePermissionState( 9599 bp.name, userId) != null) { 9600 // Revoke the runtime permission and clear the flags. 9601 origPermissions.revokeRuntimePermission(bp, userId); 9602 origPermissions.updatePermissionFlags(bp, userId, 9603 PackageManager.MASK_PERMISSION_FLAGS, 0); 9604 // If we revoked a permission permission, we have to write. 9605 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9606 changedRuntimePermissionUserIds, userId); 9607 } 9608 } 9609 // Grant an install permission. 9610 if (permissionsState.grantInstallPermission(bp) != 9611 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9612 changedInstallPermission = true; 9613 } 9614 } break; 9615 9616 case GRANT_RUNTIME: { 9617 // Grant previously granted runtime permissions. 9618 for (int userId : UserManagerService.getInstance().getUserIds()) { 9619 PermissionState permissionState = origPermissions 9620 .getRuntimePermissionState(bp.name, userId); 9621 int flags = permissionState != null 9622 ? permissionState.getFlags() : 0; 9623 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 9624 if (permissionsState.grantRuntimePermission(bp, userId) == 9625 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9626 // If we cannot put the permission as it was, we have to write. 9627 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9628 changedRuntimePermissionUserIds, userId); 9629 } 9630 // If the app supports runtime permissions no need for a review. 9631 if (Build.PERMISSIONS_REVIEW_REQUIRED 9632 && appSupportsRuntimePermissions 9633 && (flags & PackageManager 9634 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 9635 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 9636 // Since we changed the flags, we have to write. 9637 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9638 changedRuntimePermissionUserIds, userId); 9639 } 9640 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 9641 && !appSupportsRuntimePermissions) { 9642 // For legacy apps that need a permission review, every new 9643 // runtime permission is granted but it is pending a review. 9644 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 9645 permissionsState.grantRuntimePermission(bp, userId); 9646 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 9647 // We changed the permission and flags, hence have to write. 9648 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9649 changedRuntimePermissionUserIds, userId); 9650 } 9651 } 9652 // Propagate the permission flags. 9653 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 9654 } 9655 } break; 9656 9657 case GRANT_UPGRADE: { 9658 // Grant runtime permissions for a previously held install permission. 9659 PermissionState permissionState = origPermissions 9660 .getInstallPermissionState(bp.name); 9661 final int flags = permissionState != null ? permissionState.getFlags() : 0; 9662 9663 if (origPermissions.revokeInstallPermission(bp) 9664 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 9665 // We will be transferring the permission flags, so clear them. 9666 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 9667 PackageManager.MASK_PERMISSION_FLAGS, 0); 9668 changedInstallPermission = true; 9669 } 9670 9671 // If the permission is not to be promoted to runtime we ignore it and 9672 // also its other flags as they are not applicable to install permissions. 9673 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 9674 for (int userId : currentUserIds) { 9675 if (permissionsState.grantRuntimePermission(bp, userId) != 9676 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9677 // Transfer the permission flags. 9678 permissionsState.updatePermissionFlags(bp, userId, 9679 flags, flags); 9680 // If we granted the permission, we have to write. 9681 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9682 changedRuntimePermissionUserIds, userId); 9683 } 9684 } 9685 } 9686 } break; 9687 9688 default: { 9689 if (packageOfInterest == null 9690 || packageOfInterest.equals(pkg.packageName)) { 9691 Slog.w(TAG, "Not granting permission " + perm 9692 + " to package " + pkg.packageName 9693 + " because it was previously installed without"); 9694 } 9695 } break; 9696 } 9697 } else { 9698 if (permissionsState.revokeInstallPermission(bp) != 9699 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9700 // Also drop the permission flags. 9701 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 9702 PackageManager.MASK_PERMISSION_FLAGS, 0); 9703 changedInstallPermission = true; 9704 Slog.i(TAG, "Un-granting permission " + perm 9705 + " from package " + pkg.packageName 9706 + " (protectionLevel=" + bp.protectionLevel 9707 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9708 + ")"); 9709 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 9710 // Don't print warning for app op permissions, since it is fine for them 9711 // not to be granted, there is a UI for the user to decide. 9712 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9713 Slog.w(TAG, "Not granting permission " + perm 9714 + " to package " + pkg.packageName 9715 + " (protectionLevel=" + bp.protectionLevel 9716 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9717 + ")"); 9718 } 9719 } 9720 } 9721 } 9722 9723 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 9724 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 9725 // This is the first that we have heard about this package, so the 9726 // permissions we have now selected are fixed until explicitly 9727 // changed. 9728 ps.installPermissionsFixed = true; 9729 } 9730 9731 // Persist the runtime permissions state for users with changes. If permissions 9732 // were revoked because no app in the shared user declares them we have to 9733 // write synchronously to avoid losing runtime permissions state. 9734 for (int userId : changedRuntimePermissionUserIds) { 9735 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 9736 } 9737 9738 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9739 } 9740 9741 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 9742 boolean allowed = false; 9743 final int NP = PackageParser.NEW_PERMISSIONS.length; 9744 for (int ip=0; ip<NP; ip++) { 9745 final PackageParser.NewPermissionInfo npi 9746 = PackageParser.NEW_PERMISSIONS[ip]; 9747 if (npi.name.equals(perm) 9748 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 9749 allowed = true; 9750 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 9751 + pkg.packageName); 9752 break; 9753 } 9754 } 9755 return allowed; 9756 } 9757 9758 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 9759 BasePermission bp, PermissionsState origPermissions) { 9760 boolean allowed; 9761 allowed = (compareSignatures( 9762 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 9763 == PackageManager.SIGNATURE_MATCH) 9764 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 9765 == PackageManager.SIGNATURE_MATCH); 9766 if (!allowed && (bp.protectionLevel 9767 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 9768 if (isSystemApp(pkg)) { 9769 // For updated system applications, a system permission 9770 // is granted only if it had been defined by the original application. 9771 if (pkg.isUpdatedSystemApp()) { 9772 final PackageSetting sysPs = mSettings 9773 .getDisabledSystemPkgLPr(pkg.packageName); 9774 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 9775 // If the original was granted this permission, we take 9776 // that grant decision as read and propagate it to the 9777 // update. 9778 if (sysPs.isPrivileged()) { 9779 allowed = true; 9780 } 9781 } else { 9782 // The system apk may have been updated with an older 9783 // version of the one on the data partition, but which 9784 // granted a new system permission that it didn't have 9785 // before. In this case we do want to allow the app to 9786 // now get the new permission if the ancestral apk is 9787 // privileged to get it. 9788 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 9789 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 9790 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 9791 allowed = true; 9792 break; 9793 } 9794 } 9795 } 9796 // Also if a privileged parent package on the system image or any of 9797 // its children requested a privileged permission, the updated child 9798 // packages can also get the permission. 9799 if (pkg.parentPackage != null) { 9800 final PackageSetting disabledSysParentPs = mSettings 9801 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 9802 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 9803 && disabledSysParentPs.isPrivileged()) { 9804 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 9805 allowed = true; 9806 } else if (disabledSysParentPs.pkg.childPackages != null) { 9807 final int count = disabledSysParentPs.pkg.childPackages.size(); 9808 for (int i = 0; i < count; i++) { 9809 PackageParser.Package disabledSysChildPkg = 9810 disabledSysParentPs.pkg.childPackages.get(i); 9811 if (isPackageRequestingPermission(disabledSysChildPkg, 9812 perm)) { 9813 allowed = true; 9814 break; 9815 } 9816 } 9817 } 9818 } 9819 } 9820 } 9821 } else { 9822 allowed = isPrivilegedApp(pkg); 9823 } 9824 } 9825 } 9826 if (!allowed) { 9827 if (!allowed && (bp.protectionLevel 9828 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 9829 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 9830 // If this was a previously normal/dangerous permission that got moved 9831 // to a system permission as part of the runtime permission redesign, then 9832 // we still want to blindly grant it to old apps. 9833 allowed = true; 9834 } 9835 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 9836 && pkg.packageName.equals(mRequiredInstallerPackage)) { 9837 // If this permission is to be granted to the system installer and 9838 // this app is an installer, then it gets the permission. 9839 allowed = true; 9840 } 9841 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 9842 && pkg.packageName.equals(mRequiredVerifierPackage)) { 9843 // If this permission is to be granted to the system verifier and 9844 // this app is a verifier, then it gets the permission. 9845 allowed = true; 9846 } 9847 if (!allowed && (bp.protectionLevel 9848 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 9849 && isSystemApp(pkg)) { 9850 // Any pre-installed system app is allowed to get this permission. 9851 allowed = true; 9852 } 9853 if (!allowed && (bp.protectionLevel 9854 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 9855 // For development permissions, a development permission 9856 // is granted only if it was already granted. 9857 allowed = origPermissions.hasInstallPermission(perm); 9858 } 9859 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 9860 && pkg.packageName.equals(mSetupWizardPackage)) { 9861 // If this permission is to be granted to the system setup wizard and 9862 // this app is a setup wizard, then it gets the permission. 9863 allowed = true; 9864 } 9865 } 9866 return allowed; 9867 } 9868 9869 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 9870 final int permCount = pkg.requestedPermissions.size(); 9871 for (int j = 0; j < permCount; j++) { 9872 String requestedPermission = pkg.requestedPermissions.get(j); 9873 if (permission.equals(requestedPermission)) { 9874 return true; 9875 } 9876 } 9877 return false; 9878 } 9879 9880 final class ActivityIntentResolver 9881 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 9882 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9883 boolean defaultOnly, int userId) { 9884 if (!sUserManager.exists(userId)) return null; 9885 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9886 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9887 } 9888 9889 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9890 int userId) { 9891 if (!sUserManager.exists(userId)) return null; 9892 mFlags = flags; 9893 return super.queryIntent(intent, resolvedType, 9894 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9895 } 9896 9897 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9898 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 9899 if (!sUserManager.exists(userId)) return null; 9900 if (packageActivities == null) { 9901 return null; 9902 } 9903 mFlags = flags; 9904 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9905 final int N = packageActivities.size(); 9906 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 9907 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 9908 9909 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 9910 for (int i = 0; i < N; ++i) { 9911 intentFilters = packageActivities.get(i).intents; 9912 if (intentFilters != null && intentFilters.size() > 0) { 9913 PackageParser.ActivityIntentInfo[] array = 9914 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 9915 intentFilters.toArray(array); 9916 listCut.add(array); 9917 } 9918 } 9919 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9920 } 9921 9922 /** 9923 * Finds a privileged activity that matches the specified activity names. 9924 */ 9925 private PackageParser.Activity findMatchingActivity( 9926 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 9927 for (PackageParser.Activity sysActivity : activityList) { 9928 if (sysActivity.info.name.equals(activityInfo.name)) { 9929 return sysActivity; 9930 } 9931 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 9932 return sysActivity; 9933 } 9934 if (sysActivity.info.targetActivity != null) { 9935 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 9936 return sysActivity; 9937 } 9938 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 9939 return sysActivity; 9940 } 9941 } 9942 } 9943 return null; 9944 } 9945 9946 public class IterGenerator<E> { 9947 public Iterator<E> generate(ActivityIntentInfo info) { 9948 return null; 9949 } 9950 } 9951 9952 public class ActionIterGenerator extends IterGenerator<String> { 9953 @Override 9954 public Iterator<String> generate(ActivityIntentInfo info) { 9955 return info.actionsIterator(); 9956 } 9957 } 9958 9959 public class CategoriesIterGenerator extends IterGenerator<String> { 9960 @Override 9961 public Iterator<String> generate(ActivityIntentInfo info) { 9962 return info.categoriesIterator(); 9963 } 9964 } 9965 9966 public class SchemesIterGenerator extends IterGenerator<String> { 9967 @Override 9968 public Iterator<String> generate(ActivityIntentInfo info) { 9969 return info.schemesIterator(); 9970 } 9971 } 9972 9973 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 9974 @Override 9975 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 9976 return info.authoritiesIterator(); 9977 } 9978 } 9979 9980 /** 9981 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 9982 * MODIFIED. Do not pass in a list that should not be changed. 9983 */ 9984 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 9985 IterGenerator<T> generator, Iterator<T> searchIterator) { 9986 // loop through the set of actions; every one must be found in the intent filter 9987 while (searchIterator.hasNext()) { 9988 // we must have at least one filter in the list to consider a match 9989 if (intentList.size() == 0) { 9990 break; 9991 } 9992 9993 final T searchAction = searchIterator.next(); 9994 9995 // loop through the set of intent filters 9996 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 9997 while (intentIter.hasNext()) { 9998 final ActivityIntentInfo intentInfo = intentIter.next(); 9999 boolean selectionFound = false; 10000 10001 // loop through the intent filter's selection criteria; at least one 10002 // of them must match the searched criteria 10003 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 10004 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 10005 final T intentSelection = intentSelectionIter.next(); 10006 if (intentSelection != null && intentSelection.equals(searchAction)) { 10007 selectionFound = true; 10008 break; 10009 } 10010 } 10011 10012 // the selection criteria wasn't found in this filter's set; this filter 10013 // is not a potential match 10014 if (!selectionFound) { 10015 intentIter.remove(); 10016 } 10017 } 10018 } 10019 } 10020 10021 private boolean isProtectedAction(ActivityIntentInfo filter) { 10022 final Iterator<String> actionsIter = filter.actionsIterator(); 10023 while (actionsIter != null && actionsIter.hasNext()) { 10024 final String filterAction = actionsIter.next(); 10025 if (PROTECTED_ACTIONS.contains(filterAction)) { 10026 return true; 10027 } 10028 } 10029 return false; 10030 } 10031 10032 /** 10033 * Adjusts the priority of the given intent filter according to policy. 10034 * <p> 10035 * <ul> 10036 * <li>The priority for non privileged applications is capped to '0'</li> 10037 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 10038 * <li>The priority for unbundled updates to privileged applications is capped to the 10039 * priority defined on the system partition</li> 10040 * </ul> 10041 * <p> 10042 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 10043 * allowed to obtain any priority on any action. 10044 */ 10045 private void adjustPriority( 10046 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 10047 // nothing to do; priority is fine as-is 10048 if (intent.getPriority() <= 0) { 10049 return; 10050 } 10051 10052 final ActivityInfo activityInfo = intent.activity.info; 10053 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 10054 10055 final boolean privilegedApp = 10056 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 10057 if (!privilegedApp) { 10058 // non-privileged applications can never define a priority >0 10059 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 10060 + " package: " + applicationInfo.packageName 10061 + " activity: " + intent.activity.className 10062 + " origPrio: " + intent.getPriority()); 10063 intent.setPriority(0); 10064 return; 10065 } 10066 10067 if (systemActivities == null) { 10068 // the system package is not disabled; we're parsing the system partition 10069 if (isProtectedAction(intent)) { 10070 if (mDeferProtectedFilters) { 10071 // We can't deal with these just yet. No component should ever obtain a 10072 // >0 priority for a protected actions, with ONE exception -- the setup 10073 // wizard. The setup wizard, however, cannot be known until we're able to 10074 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 10075 // until all intent filters have been processed. Chicken, meet egg. 10076 // Let the filter temporarily have a high priority and rectify the 10077 // priorities after all system packages have been scanned. 10078 mProtectedFilters.add(intent); 10079 if (DEBUG_FILTERS) { 10080 Slog.i(TAG, "Protected action; save for later;" 10081 + " package: " + applicationInfo.packageName 10082 + " activity: " + intent.activity.className 10083 + " origPrio: " + intent.getPriority()); 10084 } 10085 return; 10086 } else { 10087 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 10088 Slog.i(TAG, "No setup wizard;" 10089 + " All protected intents capped to priority 0"); 10090 } 10091 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 10092 if (DEBUG_FILTERS) { 10093 Slog.i(TAG, "Found setup wizard;" 10094 + " allow priority " + intent.getPriority() + ";" 10095 + " package: " + intent.activity.info.packageName 10096 + " activity: " + intent.activity.className 10097 + " priority: " + intent.getPriority()); 10098 } 10099 // setup wizard gets whatever it wants 10100 return; 10101 } 10102 Slog.w(TAG, "Protected action; cap priority to 0;" 10103 + " package: " + intent.activity.info.packageName 10104 + " activity: " + intent.activity.className 10105 + " origPrio: " + intent.getPriority()); 10106 intent.setPriority(0); 10107 return; 10108 } 10109 } 10110 // privileged apps on the system image get whatever priority they request 10111 return; 10112 } 10113 10114 // privileged app unbundled update ... try to find the same activity 10115 final PackageParser.Activity foundActivity = 10116 findMatchingActivity(systemActivities, activityInfo); 10117 if (foundActivity == null) { 10118 // this is a new activity; it cannot obtain >0 priority 10119 if (DEBUG_FILTERS) { 10120 Slog.i(TAG, "New activity; cap priority to 0;" 10121 + " package: " + applicationInfo.packageName 10122 + " activity: " + intent.activity.className 10123 + " origPrio: " + intent.getPriority()); 10124 } 10125 intent.setPriority(0); 10126 return; 10127 } 10128 10129 // found activity, now check for filter equivalence 10130 10131 // a shallow copy is enough; we modify the list, not its contents 10132 final List<ActivityIntentInfo> intentListCopy = 10133 new ArrayList<>(foundActivity.intents); 10134 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 10135 10136 // find matching action subsets 10137 final Iterator<String> actionsIterator = intent.actionsIterator(); 10138 if (actionsIterator != null) { 10139 getIntentListSubset( 10140 intentListCopy, new ActionIterGenerator(), actionsIterator); 10141 if (intentListCopy.size() == 0) { 10142 // no more intents to match; we're not equivalent 10143 if (DEBUG_FILTERS) { 10144 Slog.i(TAG, "Mismatched action; cap priority to 0;" 10145 + " package: " + applicationInfo.packageName 10146 + " activity: " + intent.activity.className 10147 + " origPrio: " + intent.getPriority()); 10148 } 10149 intent.setPriority(0); 10150 return; 10151 } 10152 } 10153 10154 // find matching category subsets 10155 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 10156 if (categoriesIterator != null) { 10157 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 10158 categoriesIterator); 10159 if (intentListCopy.size() == 0) { 10160 // no more intents to match; we're not equivalent 10161 if (DEBUG_FILTERS) { 10162 Slog.i(TAG, "Mismatched category; cap priority to 0;" 10163 + " package: " + applicationInfo.packageName 10164 + " activity: " + intent.activity.className 10165 + " origPrio: " + intent.getPriority()); 10166 } 10167 intent.setPriority(0); 10168 return; 10169 } 10170 } 10171 10172 // find matching schemes subsets 10173 final Iterator<String> schemesIterator = intent.schemesIterator(); 10174 if (schemesIterator != null) { 10175 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 10176 schemesIterator); 10177 if (intentListCopy.size() == 0) { 10178 // no more intents to match; we're not equivalent 10179 if (DEBUG_FILTERS) { 10180 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 10181 + " package: " + applicationInfo.packageName 10182 + " activity: " + intent.activity.className 10183 + " origPrio: " + intent.getPriority()); 10184 } 10185 intent.setPriority(0); 10186 return; 10187 } 10188 } 10189 10190 // find matching authorities subsets 10191 final Iterator<IntentFilter.AuthorityEntry> 10192 authoritiesIterator = intent.authoritiesIterator(); 10193 if (authoritiesIterator != null) { 10194 getIntentListSubset(intentListCopy, 10195 new AuthoritiesIterGenerator(), 10196 authoritiesIterator); 10197 if (intentListCopy.size() == 0) { 10198 // no more intents to match; we're not equivalent 10199 if (DEBUG_FILTERS) { 10200 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 10201 + " package: " + applicationInfo.packageName 10202 + " activity: " + intent.activity.className 10203 + " origPrio: " + intent.getPriority()); 10204 } 10205 intent.setPriority(0); 10206 return; 10207 } 10208 } 10209 10210 // we found matching filter(s); app gets the max priority of all intents 10211 int cappedPriority = 0; 10212 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 10213 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 10214 } 10215 if (intent.getPriority() > cappedPriority) { 10216 if (DEBUG_FILTERS) { 10217 Slog.i(TAG, "Found matching filter(s);" 10218 + " cap priority to " + cappedPriority + ";" 10219 + " package: " + applicationInfo.packageName 10220 + " activity: " + intent.activity.className 10221 + " origPrio: " + intent.getPriority()); 10222 } 10223 intent.setPriority(cappedPriority); 10224 return; 10225 } 10226 // all this for nothing; the requested priority was <= what was on the system 10227 } 10228 10229 public final void addActivity(PackageParser.Activity a, String type) { 10230 mActivities.put(a.getComponentName(), a); 10231 if (DEBUG_SHOW_INFO) 10232 Log.v( 10233 TAG, " " + type + " " + 10234 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 10235 if (DEBUG_SHOW_INFO) 10236 Log.v(TAG, " Class=" + a.info.name); 10237 final int NI = a.intents.size(); 10238 for (int j=0; j<NI; j++) { 10239 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10240 if ("activity".equals(type)) { 10241 final PackageSetting ps = 10242 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 10243 final List<PackageParser.Activity> systemActivities = 10244 ps != null && ps.pkg != null ? ps.pkg.activities : null; 10245 adjustPriority(systemActivities, intent); 10246 } 10247 if (DEBUG_SHOW_INFO) { 10248 Log.v(TAG, " IntentFilter:"); 10249 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10250 } 10251 if (!intent.debugCheck()) { 10252 Log.w(TAG, "==> For Activity " + a.info.name); 10253 } 10254 addFilter(intent); 10255 } 10256 } 10257 10258 public final void removeActivity(PackageParser.Activity a, String type) { 10259 mActivities.remove(a.getComponentName()); 10260 if (DEBUG_SHOW_INFO) { 10261 Log.v(TAG, " " + type + " " 10262 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 10263 : a.info.name) + ":"); 10264 Log.v(TAG, " Class=" + a.info.name); 10265 } 10266 final int NI = a.intents.size(); 10267 for (int j=0; j<NI; j++) { 10268 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10269 if (DEBUG_SHOW_INFO) { 10270 Log.v(TAG, " IntentFilter:"); 10271 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10272 } 10273 removeFilter(intent); 10274 } 10275 } 10276 10277 @Override 10278 protected boolean allowFilterResult( 10279 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 10280 ActivityInfo filterAi = filter.activity.info; 10281 for (int i=dest.size()-1; i>=0; i--) { 10282 ActivityInfo destAi = dest.get(i).activityInfo; 10283 if (destAi.name == filterAi.name 10284 && destAi.packageName == filterAi.packageName) { 10285 return false; 10286 } 10287 } 10288 return true; 10289 } 10290 10291 @Override 10292 protected ActivityIntentInfo[] newArray(int size) { 10293 return new ActivityIntentInfo[size]; 10294 } 10295 10296 @Override 10297 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 10298 if (!sUserManager.exists(userId)) return true; 10299 PackageParser.Package p = filter.activity.owner; 10300 if (p != null) { 10301 PackageSetting ps = (PackageSetting)p.mExtras; 10302 if (ps != null) { 10303 // System apps are never considered stopped for purposes of 10304 // filtering, because there may be no way for the user to 10305 // actually re-launch them. 10306 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 10307 && ps.getStopped(userId); 10308 } 10309 } 10310 return false; 10311 } 10312 10313 @Override 10314 protected boolean isPackageForFilter(String packageName, 10315 PackageParser.ActivityIntentInfo info) { 10316 return packageName.equals(info.activity.owner.packageName); 10317 } 10318 10319 @Override 10320 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 10321 int match, int userId) { 10322 if (!sUserManager.exists(userId)) return null; 10323 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 10324 return null; 10325 } 10326 final PackageParser.Activity activity = info.activity; 10327 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 10328 if (ps == null) { 10329 return null; 10330 } 10331 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 10332 ps.readUserState(userId), userId); 10333 if (ai == null) { 10334 return null; 10335 } 10336 final ResolveInfo res = new ResolveInfo(); 10337 res.activityInfo = ai; 10338 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10339 res.filter = info; 10340 } 10341 if (info != null) { 10342 res.handleAllWebDataURI = info.handleAllWebDataURI(); 10343 } 10344 res.priority = info.getPriority(); 10345 res.preferredOrder = activity.owner.mPreferredOrder; 10346 //System.out.println("Result: " + res.activityInfo.className + 10347 // " = " + res.priority); 10348 res.match = match; 10349 res.isDefault = info.hasDefault; 10350 res.labelRes = info.labelRes; 10351 res.nonLocalizedLabel = info.nonLocalizedLabel; 10352 if (userNeedsBadging(userId)) { 10353 res.noResourceId = true; 10354 } else { 10355 res.icon = info.icon; 10356 } 10357 res.iconResourceId = info.icon; 10358 res.system = res.activityInfo.applicationInfo.isSystemApp(); 10359 return res; 10360 } 10361 10362 @Override 10363 protected void sortResults(List<ResolveInfo> results) { 10364 Collections.sort(results, mResolvePrioritySorter); 10365 } 10366 10367 @Override 10368 protected void dumpFilter(PrintWriter out, String prefix, 10369 PackageParser.ActivityIntentInfo filter) { 10370 out.print(prefix); out.print( 10371 Integer.toHexString(System.identityHashCode(filter.activity))); 10372 out.print(' '); 10373 filter.activity.printComponentShortName(out); 10374 out.print(" filter "); 10375 out.println(Integer.toHexString(System.identityHashCode(filter))); 10376 } 10377 10378 @Override 10379 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 10380 return filter.activity; 10381 } 10382 10383 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10384 PackageParser.Activity activity = (PackageParser.Activity)label; 10385 out.print(prefix); out.print( 10386 Integer.toHexString(System.identityHashCode(activity))); 10387 out.print(' '); 10388 activity.printComponentShortName(out); 10389 if (count > 1) { 10390 out.print(" ("); out.print(count); out.print(" filters)"); 10391 } 10392 out.println(); 10393 } 10394 10395 // Keys are String (activity class name), values are Activity. 10396 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 10397 = new ArrayMap<ComponentName, PackageParser.Activity>(); 10398 private int mFlags; 10399 } 10400 10401 private final class ServiceIntentResolver 10402 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 10403 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10404 boolean defaultOnly, int userId) { 10405 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10406 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10407 } 10408 10409 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10410 int userId) { 10411 if (!sUserManager.exists(userId)) return null; 10412 mFlags = flags; 10413 return super.queryIntent(intent, resolvedType, 10414 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10415 } 10416 10417 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10418 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 10419 if (!sUserManager.exists(userId)) return null; 10420 if (packageServices == null) { 10421 return null; 10422 } 10423 mFlags = flags; 10424 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10425 final int N = packageServices.size(); 10426 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 10427 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 10428 10429 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 10430 for (int i = 0; i < N; ++i) { 10431 intentFilters = packageServices.get(i).intents; 10432 if (intentFilters != null && intentFilters.size() > 0) { 10433 PackageParser.ServiceIntentInfo[] array = 10434 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 10435 intentFilters.toArray(array); 10436 listCut.add(array); 10437 } 10438 } 10439 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10440 } 10441 10442 public final void addService(PackageParser.Service s) { 10443 mServices.put(s.getComponentName(), s); 10444 if (DEBUG_SHOW_INFO) { 10445 Log.v(TAG, " " 10446 + (s.info.nonLocalizedLabel != null 10447 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10448 Log.v(TAG, " Class=" + s.info.name); 10449 } 10450 final int NI = s.intents.size(); 10451 int j; 10452 for (j=0; j<NI; j++) { 10453 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10454 if (DEBUG_SHOW_INFO) { 10455 Log.v(TAG, " IntentFilter:"); 10456 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10457 } 10458 if (!intent.debugCheck()) { 10459 Log.w(TAG, "==> For Service " + s.info.name); 10460 } 10461 addFilter(intent); 10462 } 10463 } 10464 10465 public final void removeService(PackageParser.Service s) { 10466 mServices.remove(s.getComponentName()); 10467 if (DEBUG_SHOW_INFO) { 10468 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 10469 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10470 Log.v(TAG, " Class=" + s.info.name); 10471 } 10472 final int NI = s.intents.size(); 10473 int j; 10474 for (j=0; j<NI; j++) { 10475 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10476 if (DEBUG_SHOW_INFO) { 10477 Log.v(TAG, " IntentFilter:"); 10478 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10479 } 10480 removeFilter(intent); 10481 } 10482 } 10483 10484 @Override 10485 protected boolean allowFilterResult( 10486 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 10487 ServiceInfo filterSi = filter.service.info; 10488 for (int i=dest.size()-1; i>=0; i--) { 10489 ServiceInfo destAi = dest.get(i).serviceInfo; 10490 if (destAi.name == filterSi.name 10491 && destAi.packageName == filterSi.packageName) { 10492 return false; 10493 } 10494 } 10495 return true; 10496 } 10497 10498 @Override 10499 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 10500 return new PackageParser.ServiceIntentInfo[size]; 10501 } 10502 10503 @Override 10504 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 10505 if (!sUserManager.exists(userId)) return true; 10506 PackageParser.Package p = filter.service.owner; 10507 if (p != null) { 10508 PackageSetting ps = (PackageSetting)p.mExtras; 10509 if (ps != null) { 10510 // System apps are never considered stopped for purposes of 10511 // filtering, because there may be no way for the user to 10512 // actually re-launch them. 10513 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10514 && ps.getStopped(userId); 10515 } 10516 } 10517 return false; 10518 } 10519 10520 @Override 10521 protected boolean isPackageForFilter(String packageName, 10522 PackageParser.ServiceIntentInfo info) { 10523 return packageName.equals(info.service.owner.packageName); 10524 } 10525 10526 @Override 10527 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 10528 int match, int userId) { 10529 if (!sUserManager.exists(userId)) return null; 10530 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 10531 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 10532 return null; 10533 } 10534 final PackageParser.Service service = info.service; 10535 PackageSetting ps = (PackageSetting) service.owner.mExtras; 10536 if (ps == null) { 10537 return null; 10538 } 10539 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 10540 ps.readUserState(userId), userId); 10541 if (si == null) { 10542 return null; 10543 } 10544 final ResolveInfo res = new ResolveInfo(); 10545 res.serviceInfo = si; 10546 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10547 res.filter = filter; 10548 } 10549 res.priority = info.getPriority(); 10550 res.preferredOrder = service.owner.mPreferredOrder; 10551 res.match = match; 10552 res.isDefault = info.hasDefault; 10553 res.labelRes = info.labelRes; 10554 res.nonLocalizedLabel = info.nonLocalizedLabel; 10555 res.icon = info.icon; 10556 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 10557 return res; 10558 } 10559 10560 @Override 10561 protected void sortResults(List<ResolveInfo> results) { 10562 Collections.sort(results, mResolvePrioritySorter); 10563 } 10564 10565 @Override 10566 protected void dumpFilter(PrintWriter out, String prefix, 10567 PackageParser.ServiceIntentInfo filter) { 10568 out.print(prefix); out.print( 10569 Integer.toHexString(System.identityHashCode(filter.service))); 10570 out.print(' '); 10571 filter.service.printComponentShortName(out); 10572 out.print(" filter "); 10573 out.println(Integer.toHexString(System.identityHashCode(filter))); 10574 } 10575 10576 @Override 10577 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 10578 return filter.service; 10579 } 10580 10581 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10582 PackageParser.Service service = (PackageParser.Service)label; 10583 out.print(prefix); out.print( 10584 Integer.toHexString(System.identityHashCode(service))); 10585 out.print(' '); 10586 service.printComponentShortName(out); 10587 if (count > 1) { 10588 out.print(" ("); out.print(count); out.print(" filters)"); 10589 } 10590 out.println(); 10591 } 10592 10593// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 10594// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 10595// final List<ResolveInfo> retList = Lists.newArrayList(); 10596// while (i.hasNext()) { 10597// final ResolveInfo resolveInfo = (ResolveInfo) i; 10598// if (isEnabledLP(resolveInfo.serviceInfo)) { 10599// retList.add(resolveInfo); 10600// } 10601// } 10602// return retList; 10603// } 10604 10605 // Keys are String (activity class name), values are Activity. 10606 private final ArrayMap<ComponentName, PackageParser.Service> mServices 10607 = new ArrayMap<ComponentName, PackageParser.Service>(); 10608 private int mFlags; 10609 }; 10610 10611 private final class ProviderIntentResolver 10612 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 10613 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10614 boolean defaultOnly, int userId) { 10615 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10616 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10617 } 10618 10619 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10620 int userId) { 10621 if (!sUserManager.exists(userId)) 10622 return null; 10623 mFlags = flags; 10624 return super.queryIntent(intent, resolvedType, 10625 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10626 } 10627 10628 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10629 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 10630 if (!sUserManager.exists(userId)) 10631 return null; 10632 if (packageProviders == null) { 10633 return null; 10634 } 10635 mFlags = flags; 10636 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 10637 final int N = packageProviders.size(); 10638 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 10639 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 10640 10641 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 10642 for (int i = 0; i < N; ++i) { 10643 intentFilters = packageProviders.get(i).intents; 10644 if (intentFilters != null && intentFilters.size() > 0) { 10645 PackageParser.ProviderIntentInfo[] array = 10646 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 10647 intentFilters.toArray(array); 10648 listCut.add(array); 10649 } 10650 } 10651 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10652 } 10653 10654 public final void addProvider(PackageParser.Provider p) { 10655 if (mProviders.containsKey(p.getComponentName())) { 10656 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 10657 return; 10658 } 10659 10660 mProviders.put(p.getComponentName(), p); 10661 if (DEBUG_SHOW_INFO) { 10662 Log.v(TAG, " " 10663 + (p.info.nonLocalizedLabel != null 10664 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10665 Log.v(TAG, " Class=" + p.info.name); 10666 } 10667 final int NI = p.intents.size(); 10668 int j; 10669 for (j = 0; j < NI; j++) { 10670 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10671 if (DEBUG_SHOW_INFO) { 10672 Log.v(TAG, " IntentFilter:"); 10673 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10674 } 10675 if (!intent.debugCheck()) { 10676 Log.w(TAG, "==> For Provider " + p.info.name); 10677 } 10678 addFilter(intent); 10679 } 10680 } 10681 10682 public final void removeProvider(PackageParser.Provider p) { 10683 mProviders.remove(p.getComponentName()); 10684 if (DEBUG_SHOW_INFO) { 10685 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 10686 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10687 Log.v(TAG, " Class=" + p.info.name); 10688 } 10689 final int NI = p.intents.size(); 10690 int j; 10691 for (j = 0; j < NI; j++) { 10692 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10693 if (DEBUG_SHOW_INFO) { 10694 Log.v(TAG, " IntentFilter:"); 10695 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10696 } 10697 removeFilter(intent); 10698 } 10699 } 10700 10701 @Override 10702 protected boolean allowFilterResult( 10703 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 10704 ProviderInfo filterPi = filter.provider.info; 10705 for (int i = dest.size() - 1; i >= 0; i--) { 10706 ProviderInfo destPi = dest.get(i).providerInfo; 10707 if (destPi.name == filterPi.name 10708 && destPi.packageName == filterPi.packageName) { 10709 return false; 10710 } 10711 } 10712 return true; 10713 } 10714 10715 @Override 10716 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 10717 return new PackageParser.ProviderIntentInfo[size]; 10718 } 10719 10720 @Override 10721 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 10722 if (!sUserManager.exists(userId)) 10723 return true; 10724 PackageParser.Package p = filter.provider.owner; 10725 if (p != null) { 10726 PackageSetting ps = (PackageSetting) p.mExtras; 10727 if (ps != null) { 10728 // System apps are never considered stopped for purposes of 10729 // filtering, because there may be no way for the user to 10730 // actually re-launch them. 10731 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10732 && ps.getStopped(userId); 10733 } 10734 } 10735 return false; 10736 } 10737 10738 @Override 10739 protected boolean isPackageForFilter(String packageName, 10740 PackageParser.ProviderIntentInfo info) { 10741 return packageName.equals(info.provider.owner.packageName); 10742 } 10743 10744 @Override 10745 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 10746 int match, int userId) { 10747 if (!sUserManager.exists(userId)) 10748 return null; 10749 final PackageParser.ProviderIntentInfo info = filter; 10750 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 10751 return null; 10752 } 10753 final PackageParser.Provider provider = info.provider; 10754 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 10755 if (ps == null) { 10756 return null; 10757 } 10758 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 10759 ps.readUserState(userId), userId); 10760 if (pi == null) { 10761 return null; 10762 } 10763 final ResolveInfo res = new ResolveInfo(); 10764 res.providerInfo = pi; 10765 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 10766 res.filter = filter; 10767 } 10768 res.priority = info.getPriority(); 10769 res.preferredOrder = provider.owner.mPreferredOrder; 10770 res.match = match; 10771 res.isDefault = info.hasDefault; 10772 res.labelRes = info.labelRes; 10773 res.nonLocalizedLabel = info.nonLocalizedLabel; 10774 res.icon = info.icon; 10775 res.system = res.providerInfo.applicationInfo.isSystemApp(); 10776 return res; 10777 } 10778 10779 @Override 10780 protected void sortResults(List<ResolveInfo> results) { 10781 Collections.sort(results, mResolvePrioritySorter); 10782 } 10783 10784 @Override 10785 protected void dumpFilter(PrintWriter out, String prefix, 10786 PackageParser.ProviderIntentInfo filter) { 10787 out.print(prefix); 10788 out.print( 10789 Integer.toHexString(System.identityHashCode(filter.provider))); 10790 out.print(' '); 10791 filter.provider.printComponentShortName(out); 10792 out.print(" filter "); 10793 out.println(Integer.toHexString(System.identityHashCode(filter))); 10794 } 10795 10796 @Override 10797 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 10798 return filter.provider; 10799 } 10800 10801 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10802 PackageParser.Provider provider = (PackageParser.Provider)label; 10803 out.print(prefix); out.print( 10804 Integer.toHexString(System.identityHashCode(provider))); 10805 out.print(' '); 10806 provider.printComponentShortName(out); 10807 if (count > 1) { 10808 out.print(" ("); out.print(count); out.print(" filters)"); 10809 } 10810 out.println(); 10811 } 10812 10813 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 10814 = new ArrayMap<ComponentName, PackageParser.Provider>(); 10815 private int mFlags; 10816 } 10817 10818 private static final class EphemeralIntentResolver 10819 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 10820 @Override 10821 protected EphemeralResolveIntentInfo[] newArray(int size) { 10822 return new EphemeralResolveIntentInfo[size]; 10823 } 10824 10825 @Override 10826 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 10827 return true; 10828 } 10829 10830 @Override 10831 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 10832 int userId) { 10833 if (!sUserManager.exists(userId)) { 10834 return null; 10835 } 10836 return info.getEphemeralResolveInfo(); 10837 } 10838 } 10839 10840 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 10841 new Comparator<ResolveInfo>() { 10842 public int compare(ResolveInfo r1, ResolveInfo r2) { 10843 int v1 = r1.priority; 10844 int v2 = r2.priority; 10845 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 10846 if (v1 != v2) { 10847 return (v1 > v2) ? -1 : 1; 10848 } 10849 v1 = r1.preferredOrder; 10850 v2 = r2.preferredOrder; 10851 if (v1 != v2) { 10852 return (v1 > v2) ? -1 : 1; 10853 } 10854 if (r1.isDefault != r2.isDefault) { 10855 return r1.isDefault ? -1 : 1; 10856 } 10857 v1 = r1.match; 10858 v2 = r2.match; 10859 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 10860 if (v1 != v2) { 10861 return (v1 > v2) ? -1 : 1; 10862 } 10863 if (r1.system != r2.system) { 10864 return r1.system ? -1 : 1; 10865 } 10866 if (r1.activityInfo != null) { 10867 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 10868 } 10869 if (r1.serviceInfo != null) { 10870 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 10871 } 10872 if (r1.providerInfo != null) { 10873 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 10874 } 10875 return 0; 10876 } 10877 }; 10878 10879 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 10880 new Comparator<ProviderInfo>() { 10881 public int compare(ProviderInfo p1, ProviderInfo p2) { 10882 final int v1 = p1.initOrder; 10883 final int v2 = p2.initOrder; 10884 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 10885 } 10886 }; 10887 10888 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 10889 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 10890 final int[] userIds) { 10891 mHandler.post(new Runnable() { 10892 @Override 10893 public void run() { 10894 try { 10895 final IActivityManager am = ActivityManagerNative.getDefault(); 10896 if (am == null) return; 10897 final int[] resolvedUserIds; 10898 if (userIds == null) { 10899 resolvedUserIds = am.getRunningUserIds(); 10900 } else { 10901 resolvedUserIds = userIds; 10902 } 10903 for (int id : resolvedUserIds) { 10904 final Intent intent = new Intent(action, 10905 pkg != null ? Uri.fromParts("package", pkg, null) : null); 10906 if (extras != null) { 10907 intent.putExtras(extras); 10908 } 10909 if (targetPkg != null) { 10910 intent.setPackage(targetPkg); 10911 } 10912 // Modify the UID when posting to other users 10913 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 10914 if (uid > 0 && UserHandle.getUserId(uid) != id) { 10915 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 10916 intent.putExtra(Intent.EXTRA_UID, uid); 10917 } 10918 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 10919 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 10920 if (DEBUG_BROADCASTS) { 10921 RuntimeException here = new RuntimeException("here"); 10922 here.fillInStackTrace(); 10923 Slog.d(TAG, "Sending to user " + id + ": " 10924 + intent.toShortString(false, true, false, false) 10925 + " " + intent.getExtras(), here); 10926 } 10927 am.broadcastIntent(null, intent, null, finishedReceiver, 10928 0, null, null, null, android.app.AppOpsManager.OP_NONE, 10929 null, finishedReceiver != null, false, id); 10930 } 10931 } catch (RemoteException ex) { 10932 } 10933 } 10934 }); 10935 } 10936 10937 /** 10938 * Check if the external storage media is available. This is true if there 10939 * is a mounted external storage medium or if the external storage is 10940 * emulated. 10941 */ 10942 private boolean isExternalMediaAvailable() { 10943 return mMediaMounted || Environment.isExternalStorageEmulated(); 10944 } 10945 10946 @Override 10947 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 10948 // writer 10949 synchronized (mPackages) { 10950 if (!isExternalMediaAvailable()) { 10951 // If the external storage is no longer mounted at this point, 10952 // the caller may not have been able to delete all of this 10953 // packages files and can not delete any more. Bail. 10954 return null; 10955 } 10956 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 10957 if (lastPackage != null) { 10958 pkgs.remove(lastPackage); 10959 } 10960 if (pkgs.size() > 0) { 10961 return pkgs.get(0); 10962 } 10963 } 10964 return null; 10965 } 10966 10967 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 10968 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 10969 userId, andCode ? 1 : 0, packageName); 10970 if (mSystemReady) { 10971 msg.sendToTarget(); 10972 } else { 10973 if (mPostSystemReadyMessages == null) { 10974 mPostSystemReadyMessages = new ArrayList<>(); 10975 } 10976 mPostSystemReadyMessages.add(msg); 10977 } 10978 } 10979 10980 void startCleaningPackages() { 10981 // reader 10982 if (!isExternalMediaAvailable()) { 10983 return; 10984 } 10985 synchronized (mPackages) { 10986 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 10987 return; 10988 } 10989 } 10990 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 10991 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 10992 IActivityManager am = ActivityManagerNative.getDefault(); 10993 if (am != null) { 10994 try { 10995 am.startService(null, intent, null, mContext.getOpPackageName(), 10996 UserHandle.USER_SYSTEM); 10997 } catch (RemoteException e) { 10998 } 10999 } 11000 } 11001 11002 @Override 11003 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 11004 int installFlags, String installerPackageName, int userId) { 11005 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 11006 11007 final int callingUid = Binder.getCallingUid(); 11008 enforceCrossUserPermission(callingUid, userId, 11009 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 11010 11011 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11012 try { 11013 if (observer != null) { 11014 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 11015 } 11016 } catch (RemoteException re) { 11017 } 11018 return; 11019 } 11020 11021 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 11022 installFlags |= PackageManager.INSTALL_FROM_ADB; 11023 11024 } else { 11025 // Caller holds INSTALL_PACKAGES permission, so we're less strict 11026 // about installerPackageName. 11027 11028 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 11029 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 11030 } 11031 11032 UserHandle user; 11033 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 11034 user = UserHandle.ALL; 11035 } else { 11036 user = new UserHandle(userId); 11037 } 11038 11039 // Only system components can circumvent runtime permissions when installing. 11040 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 11041 && mContext.checkCallingOrSelfPermission(Manifest.permission 11042 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 11043 throw new SecurityException("You need the " 11044 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 11045 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 11046 } 11047 11048 final File originFile = new File(originPath); 11049 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 11050 11051 final Message msg = mHandler.obtainMessage(INIT_COPY); 11052 final VerificationInfo verificationInfo = new VerificationInfo( 11053 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 11054 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 11055 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 11056 null /*packageAbiOverride*/, null /*grantedPermissions*/, 11057 null /*certificates*/); 11058 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 11059 msg.obj = params; 11060 11061 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 11062 System.identityHashCode(msg.obj)); 11063 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11064 System.identityHashCode(msg.obj)); 11065 11066 mHandler.sendMessage(msg); 11067 } 11068 11069 void installStage(String packageName, File stagedDir, String stagedCid, 11070 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 11071 String installerPackageName, int installerUid, UserHandle user, 11072 Certificate[][] certificates) { 11073 if (DEBUG_EPHEMERAL) { 11074 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11075 Slog.d(TAG, "Ephemeral install of " + packageName); 11076 } 11077 } 11078 final VerificationInfo verificationInfo = new VerificationInfo( 11079 sessionParams.originatingUri, sessionParams.referrerUri, 11080 sessionParams.originatingUid, installerUid); 11081 11082 final OriginInfo origin; 11083 if (stagedDir != null) { 11084 origin = OriginInfo.fromStagedFile(stagedDir); 11085 } else { 11086 origin = OriginInfo.fromStagedContainer(stagedCid); 11087 } 11088 11089 final Message msg = mHandler.obtainMessage(INIT_COPY); 11090 final InstallParams params = new InstallParams(origin, null, observer, 11091 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 11092 verificationInfo, user, sessionParams.abiOverride, 11093 sessionParams.grantedRuntimePermissions, certificates); 11094 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 11095 msg.obj = params; 11096 11097 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 11098 System.identityHashCode(msg.obj)); 11099 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11100 System.identityHashCode(msg.obj)); 11101 11102 mHandler.sendMessage(msg); 11103 } 11104 11105 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 11106 int userId) { 11107 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 11108 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId); 11109 } 11110 11111 private void sendPackageAddedForUser(String packageName, boolean isSystem, 11112 int appId, int userId) { 11113 Bundle extras = new Bundle(1); 11114 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId)); 11115 11116 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 11117 packageName, extras, 0, null, null, new int[] {userId}); 11118 try { 11119 IActivityManager am = ActivityManagerNative.getDefault(); 11120 if (isSystem && am.isUserRunning(userId, 0)) { 11121 // The just-installed/enabled app is bundled on the system, so presumed 11122 // to be able to run automatically without needing an explicit launch. 11123 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 11124 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 11125 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 11126 .setPackage(packageName); 11127 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 11128 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 11129 } 11130 } catch (RemoteException e) { 11131 // shouldn't happen 11132 Slog.w(TAG, "Unable to bootstrap installed package", e); 11133 } 11134 } 11135 11136 @Override 11137 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 11138 int userId) { 11139 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11140 PackageSetting pkgSetting; 11141 final int uid = Binder.getCallingUid(); 11142 enforceCrossUserPermission(uid, userId, 11143 true /* requireFullPermission */, true /* checkShell */, 11144 "setApplicationHiddenSetting for user " + userId); 11145 11146 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 11147 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 11148 return false; 11149 } 11150 11151 long callingId = Binder.clearCallingIdentity(); 11152 try { 11153 boolean sendAdded = false; 11154 boolean sendRemoved = false; 11155 // writer 11156 synchronized (mPackages) { 11157 pkgSetting = mSettings.mPackages.get(packageName); 11158 if (pkgSetting == null) { 11159 return false; 11160 } 11161 if (pkgSetting.getHidden(userId) != hidden) { 11162 pkgSetting.setHidden(hidden, userId); 11163 mSettings.writePackageRestrictionsLPr(userId); 11164 if (hidden) { 11165 sendRemoved = true; 11166 } else { 11167 sendAdded = true; 11168 } 11169 } 11170 } 11171 if (sendAdded) { 11172 sendPackageAddedForUser(packageName, pkgSetting, userId); 11173 return true; 11174 } 11175 if (sendRemoved) { 11176 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 11177 "hiding pkg"); 11178 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 11179 return true; 11180 } 11181 } finally { 11182 Binder.restoreCallingIdentity(callingId); 11183 } 11184 return false; 11185 } 11186 11187 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 11188 int userId) { 11189 final PackageRemovedInfo info = new PackageRemovedInfo(); 11190 info.removedPackage = packageName; 11191 info.removedUsers = new int[] {userId}; 11192 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 11193 info.sendPackageRemovedBroadcasts(true /*killApp*/); 11194 } 11195 11196 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 11197 if (pkgList.length > 0) { 11198 Bundle extras = new Bundle(1); 11199 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 11200 11201 sendPackageBroadcast( 11202 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 11203 : Intent.ACTION_PACKAGES_UNSUSPENDED, 11204 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 11205 new int[] {userId}); 11206 } 11207 } 11208 11209 /** 11210 * Returns true if application is not found or there was an error. Otherwise it returns 11211 * the hidden state of the package for the given user. 11212 */ 11213 @Override 11214 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 11215 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11216 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11217 true /* requireFullPermission */, false /* checkShell */, 11218 "getApplicationHidden for user " + userId); 11219 PackageSetting pkgSetting; 11220 long callingId = Binder.clearCallingIdentity(); 11221 try { 11222 // writer 11223 synchronized (mPackages) { 11224 pkgSetting = mSettings.mPackages.get(packageName); 11225 if (pkgSetting == null) { 11226 return true; 11227 } 11228 return pkgSetting.getHidden(userId); 11229 } 11230 } finally { 11231 Binder.restoreCallingIdentity(callingId); 11232 } 11233 } 11234 11235 /** 11236 * @hide 11237 */ 11238 @Override 11239 public int installExistingPackageAsUser(String packageName, int userId) { 11240 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 11241 null); 11242 PackageSetting pkgSetting; 11243 final int uid = Binder.getCallingUid(); 11244 enforceCrossUserPermission(uid, userId, 11245 true /* requireFullPermission */, true /* checkShell */, 11246 "installExistingPackage for user " + userId); 11247 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11248 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 11249 } 11250 11251 long callingId = Binder.clearCallingIdentity(); 11252 try { 11253 boolean installed = false; 11254 11255 // writer 11256 synchronized (mPackages) { 11257 pkgSetting = mSettings.mPackages.get(packageName); 11258 if (pkgSetting == null) { 11259 return PackageManager.INSTALL_FAILED_INVALID_URI; 11260 } 11261 if (!pkgSetting.getInstalled(userId)) { 11262 pkgSetting.setInstalled(true, userId); 11263 pkgSetting.setHidden(false, userId); 11264 mSettings.writePackageRestrictionsLPr(userId); 11265 installed = true; 11266 } 11267 } 11268 11269 if (installed) { 11270 if (pkgSetting.pkg != null) { 11271 synchronized (mInstallLock) { 11272 // We don't need to freeze for a brand new install 11273 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 11274 } 11275 } 11276 sendPackageAddedForUser(packageName, pkgSetting, userId); 11277 } 11278 } finally { 11279 Binder.restoreCallingIdentity(callingId); 11280 } 11281 11282 return PackageManager.INSTALL_SUCCEEDED; 11283 } 11284 11285 boolean isUserRestricted(int userId, String restrictionKey) { 11286 Bundle restrictions = sUserManager.getUserRestrictions(userId); 11287 if (restrictions.getBoolean(restrictionKey, false)) { 11288 Log.w(TAG, "User is restricted: " + restrictionKey); 11289 return true; 11290 } 11291 return false; 11292 } 11293 11294 @Override 11295 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 11296 int userId) { 11297 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11298 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11299 true /* requireFullPermission */, true /* checkShell */, 11300 "setPackagesSuspended for user " + userId); 11301 11302 if (ArrayUtils.isEmpty(packageNames)) { 11303 return packageNames; 11304 } 11305 11306 // List of package names for whom the suspended state has changed. 11307 List<String> changedPackages = new ArrayList<>(packageNames.length); 11308 // List of package names for whom the suspended state is not set as requested in this 11309 // method. 11310 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 11311 for (int i = 0; i < packageNames.length; i++) { 11312 String packageName = packageNames[i]; 11313 long callingId = Binder.clearCallingIdentity(); 11314 try { 11315 boolean changed = false; 11316 final int appId; 11317 synchronized (mPackages) { 11318 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11319 if (pkgSetting == null) { 11320 Slog.w(TAG, "Could not find package setting for package \"" + packageName 11321 + "\". Skipping suspending/un-suspending."); 11322 unactionedPackages.add(packageName); 11323 continue; 11324 } 11325 appId = pkgSetting.appId; 11326 if (pkgSetting.getSuspended(userId) != suspended) { 11327 if (!canSuspendPackageForUserLocked(packageName, userId)) { 11328 unactionedPackages.add(packageName); 11329 continue; 11330 } 11331 pkgSetting.setSuspended(suspended, userId); 11332 mSettings.writePackageRestrictionsLPr(userId); 11333 changed = true; 11334 changedPackages.add(packageName); 11335 } 11336 } 11337 11338 if (changed && suspended) { 11339 killApplication(packageName, UserHandle.getUid(userId, appId), 11340 "suspending package"); 11341 } 11342 } finally { 11343 Binder.restoreCallingIdentity(callingId); 11344 } 11345 } 11346 11347 if (!changedPackages.isEmpty()) { 11348 sendPackagesSuspendedForUser(changedPackages.toArray( 11349 new String[changedPackages.size()]), userId, suspended); 11350 } 11351 11352 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 11353 } 11354 11355 @Override 11356 public boolean isPackageSuspendedForUser(String packageName, int userId) { 11357 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11358 true /* requireFullPermission */, false /* checkShell */, 11359 "isPackageSuspendedForUser for user " + userId); 11360 synchronized (mPackages) { 11361 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11362 if (pkgSetting == null) { 11363 throw new IllegalArgumentException("Unknown target package: " + packageName); 11364 } 11365 return pkgSetting.getSuspended(userId); 11366 } 11367 } 11368 11369 /** 11370 * TODO: cache and disallow blocking the active dialer. 11371 * 11372 * @see also DefaultPermissionGrantPolicy#grantDefaultSystemHandlerPermissions 11373 */ 11374 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 11375 if (isPackageDeviceAdmin(packageName, userId)) { 11376 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11377 + "\": has an active device admin"); 11378 return false; 11379 } 11380 11381 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 11382 if (packageName.equals(activeLauncherPackageName)) { 11383 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11384 + "\": contains the active launcher"); 11385 return false; 11386 } 11387 11388 if (packageName.equals(mRequiredInstallerPackage)) { 11389 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11390 + "\": required for package installation"); 11391 return false; 11392 } 11393 11394 if (packageName.equals(mRequiredVerifierPackage)) { 11395 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11396 + "\": required for package verification"); 11397 return false; 11398 } 11399 11400 final PackageParser.Package pkg = mPackages.get(packageName); 11401 if (pkg != null && isPrivilegedApp(pkg)) { 11402 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11403 + "\": is a privileged app"); 11404 return false; 11405 } 11406 11407 return true; 11408 } 11409 11410 private String getActiveLauncherPackageName(int userId) { 11411 Intent intent = new Intent(Intent.ACTION_MAIN); 11412 intent.addCategory(Intent.CATEGORY_HOME); 11413 ResolveInfo resolveInfo = resolveIntent( 11414 intent, 11415 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 11416 PackageManager.MATCH_DEFAULT_ONLY, 11417 userId); 11418 11419 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 11420 } 11421 11422 @Override 11423 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 11424 mContext.enforceCallingOrSelfPermission( 11425 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11426 "Only package verification agents can verify applications"); 11427 11428 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11429 final PackageVerificationResponse response = new PackageVerificationResponse( 11430 verificationCode, Binder.getCallingUid()); 11431 msg.arg1 = id; 11432 msg.obj = response; 11433 mHandler.sendMessage(msg); 11434 } 11435 11436 @Override 11437 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 11438 long millisecondsToDelay) { 11439 mContext.enforceCallingOrSelfPermission( 11440 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11441 "Only package verification agents can extend verification timeouts"); 11442 11443 final PackageVerificationState state = mPendingVerification.get(id); 11444 final PackageVerificationResponse response = new PackageVerificationResponse( 11445 verificationCodeAtTimeout, Binder.getCallingUid()); 11446 11447 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 11448 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 11449 } 11450 if (millisecondsToDelay < 0) { 11451 millisecondsToDelay = 0; 11452 } 11453 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 11454 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 11455 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 11456 } 11457 11458 if ((state != null) && !state.timeoutExtended()) { 11459 state.extendTimeout(); 11460 11461 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11462 msg.arg1 = id; 11463 msg.obj = response; 11464 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 11465 } 11466 } 11467 11468 private void broadcastPackageVerified(int verificationId, Uri packageUri, 11469 int verificationCode, UserHandle user) { 11470 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 11471 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 11472 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11473 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11474 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 11475 11476 mContext.sendBroadcastAsUser(intent, user, 11477 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 11478 } 11479 11480 private ComponentName matchComponentForVerifier(String packageName, 11481 List<ResolveInfo> receivers) { 11482 ActivityInfo targetReceiver = null; 11483 11484 final int NR = receivers.size(); 11485 for (int i = 0; i < NR; i++) { 11486 final ResolveInfo info = receivers.get(i); 11487 if (info.activityInfo == null) { 11488 continue; 11489 } 11490 11491 if (packageName.equals(info.activityInfo.packageName)) { 11492 targetReceiver = info.activityInfo; 11493 break; 11494 } 11495 } 11496 11497 if (targetReceiver == null) { 11498 return null; 11499 } 11500 11501 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 11502 } 11503 11504 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 11505 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 11506 if (pkgInfo.verifiers.length == 0) { 11507 return null; 11508 } 11509 11510 final int N = pkgInfo.verifiers.length; 11511 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 11512 for (int i = 0; i < N; i++) { 11513 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 11514 11515 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 11516 receivers); 11517 if (comp == null) { 11518 continue; 11519 } 11520 11521 final int verifierUid = getUidForVerifier(verifierInfo); 11522 if (verifierUid == -1) { 11523 continue; 11524 } 11525 11526 if (DEBUG_VERIFY) { 11527 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 11528 + " with the correct signature"); 11529 } 11530 sufficientVerifiers.add(comp); 11531 verificationState.addSufficientVerifier(verifierUid); 11532 } 11533 11534 return sufficientVerifiers; 11535 } 11536 11537 private int getUidForVerifier(VerifierInfo verifierInfo) { 11538 synchronized (mPackages) { 11539 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 11540 if (pkg == null) { 11541 return -1; 11542 } else if (pkg.mSignatures.length != 1) { 11543 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11544 + " has more than one signature; ignoring"); 11545 return -1; 11546 } 11547 11548 /* 11549 * If the public key of the package's signature does not match 11550 * our expected public key, then this is a different package and 11551 * we should skip. 11552 */ 11553 11554 final byte[] expectedPublicKey; 11555 try { 11556 final Signature verifierSig = pkg.mSignatures[0]; 11557 final PublicKey publicKey = verifierSig.getPublicKey(); 11558 expectedPublicKey = publicKey.getEncoded(); 11559 } catch (CertificateException e) { 11560 return -1; 11561 } 11562 11563 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 11564 11565 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 11566 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11567 + " does not have the expected public key; ignoring"); 11568 return -1; 11569 } 11570 11571 return pkg.applicationInfo.uid; 11572 } 11573 } 11574 11575 @Override 11576 public void finishPackageInstall(int token) { 11577 enforceSystemOrRoot("Only the system is allowed to finish installs"); 11578 11579 if (DEBUG_INSTALL) { 11580 Slog.v(TAG, "BM finishing package install for " + token); 11581 } 11582 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 11583 11584 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 11585 mHandler.sendMessage(msg); 11586 } 11587 11588 /** 11589 * Get the verification agent timeout. 11590 * 11591 * @return verification timeout in milliseconds 11592 */ 11593 private long getVerificationTimeout() { 11594 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 11595 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 11596 DEFAULT_VERIFICATION_TIMEOUT); 11597 } 11598 11599 /** 11600 * Get the default verification agent response code. 11601 * 11602 * @return default verification response code 11603 */ 11604 private int getDefaultVerificationResponse() { 11605 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11606 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 11607 DEFAULT_VERIFICATION_RESPONSE); 11608 } 11609 11610 /** 11611 * Check whether or not package verification has been enabled. 11612 * 11613 * @return true if verification should be performed 11614 */ 11615 private boolean isVerificationEnabled(int userId, int installFlags) { 11616 if (!DEFAULT_VERIFY_ENABLE) { 11617 return false; 11618 } 11619 // Ephemeral apps don't get the full verification treatment 11620 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11621 if (DEBUG_EPHEMERAL) { 11622 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 11623 } 11624 return false; 11625 } 11626 11627 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 11628 11629 // Check if installing from ADB 11630 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 11631 // Do not run verification in a test harness environment 11632 if (ActivityManager.isRunningInTestHarness()) { 11633 return false; 11634 } 11635 if (ensureVerifyAppsEnabled) { 11636 return true; 11637 } 11638 // Check if the developer does not want package verification for ADB installs 11639 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11640 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 11641 return false; 11642 } 11643 } 11644 11645 if (ensureVerifyAppsEnabled) { 11646 return true; 11647 } 11648 11649 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11650 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 11651 } 11652 11653 @Override 11654 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 11655 throws RemoteException { 11656 mContext.enforceCallingOrSelfPermission( 11657 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 11658 "Only intentfilter verification agents can verify applications"); 11659 11660 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 11661 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 11662 Binder.getCallingUid(), verificationCode, failedDomains); 11663 msg.arg1 = id; 11664 msg.obj = response; 11665 mHandler.sendMessage(msg); 11666 } 11667 11668 @Override 11669 public int getIntentVerificationStatus(String packageName, int userId) { 11670 synchronized (mPackages) { 11671 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 11672 } 11673 } 11674 11675 @Override 11676 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 11677 mContext.enforceCallingOrSelfPermission( 11678 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11679 11680 boolean result = false; 11681 synchronized (mPackages) { 11682 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 11683 } 11684 if (result) { 11685 scheduleWritePackageRestrictionsLocked(userId); 11686 } 11687 return result; 11688 } 11689 11690 @Override 11691 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 11692 String packageName) { 11693 synchronized (mPackages) { 11694 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 11695 } 11696 } 11697 11698 @Override 11699 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 11700 if (TextUtils.isEmpty(packageName)) { 11701 return ParceledListSlice.emptyList(); 11702 } 11703 synchronized (mPackages) { 11704 PackageParser.Package pkg = mPackages.get(packageName); 11705 if (pkg == null || pkg.activities == null) { 11706 return ParceledListSlice.emptyList(); 11707 } 11708 final int count = pkg.activities.size(); 11709 ArrayList<IntentFilter> result = new ArrayList<>(); 11710 for (int n=0; n<count; n++) { 11711 PackageParser.Activity activity = pkg.activities.get(n); 11712 if (activity.intents != null && activity.intents.size() > 0) { 11713 result.addAll(activity.intents); 11714 } 11715 } 11716 return new ParceledListSlice<>(result); 11717 } 11718 } 11719 11720 @Override 11721 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 11722 mContext.enforceCallingOrSelfPermission( 11723 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11724 11725 synchronized (mPackages) { 11726 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 11727 if (packageName != null) { 11728 result |= updateIntentVerificationStatus(packageName, 11729 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 11730 userId); 11731 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 11732 packageName, userId); 11733 } 11734 return result; 11735 } 11736 } 11737 11738 @Override 11739 public String getDefaultBrowserPackageName(int userId) { 11740 synchronized (mPackages) { 11741 return mSettings.getDefaultBrowserPackageNameLPw(userId); 11742 } 11743 } 11744 11745 /** 11746 * Get the "allow unknown sources" setting. 11747 * 11748 * @return the current "allow unknown sources" setting 11749 */ 11750 private int getUnknownSourcesSettings() { 11751 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 11752 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 11753 -1); 11754 } 11755 11756 @Override 11757 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 11758 final int uid = Binder.getCallingUid(); 11759 // writer 11760 synchronized (mPackages) { 11761 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 11762 if (targetPackageSetting == null) { 11763 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 11764 } 11765 11766 PackageSetting installerPackageSetting; 11767 if (installerPackageName != null) { 11768 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 11769 if (installerPackageSetting == null) { 11770 throw new IllegalArgumentException("Unknown installer package: " 11771 + installerPackageName); 11772 } 11773 } else { 11774 installerPackageSetting = null; 11775 } 11776 11777 Signature[] callerSignature; 11778 Object obj = mSettings.getUserIdLPr(uid); 11779 if (obj != null) { 11780 if (obj instanceof SharedUserSetting) { 11781 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 11782 } else if (obj instanceof PackageSetting) { 11783 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 11784 } else { 11785 throw new SecurityException("Bad object " + obj + " for uid " + uid); 11786 } 11787 } else { 11788 throw new SecurityException("Unknown calling UID: " + uid); 11789 } 11790 11791 // Verify: can't set installerPackageName to a package that is 11792 // not signed with the same cert as the caller. 11793 if (installerPackageSetting != null) { 11794 if (compareSignatures(callerSignature, 11795 installerPackageSetting.signatures.mSignatures) 11796 != PackageManager.SIGNATURE_MATCH) { 11797 throw new SecurityException( 11798 "Caller does not have same cert as new installer package " 11799 + installerPackageName); 11800 } 11801 } 11802 11803 // Verify: if target already has an installer package, it must 11804 // be signed with the same cert as the caller. 11805 if (targetPackageSetting.installerPackageName != null) { 11806 PackageSetting setting = mSettings.mPackages.get( 11807 targetPackageSetting.installerPackageName); 11808 // If the currently set package isn't valid, then it's always 11809 // okay to change it. 11810 if (setting != null) { 11811 if (compareSignatures(callerSignature, 11812 setting.signatures.mSignatures) 11813 != PackageManager.SIGNATURE_MATCH) { 11814 throw new SecurityException( 11815 "Caller does not have same cert as old installer package " 11816 + targetPackageSetting.installerPackageName); 11817 } 11818 } 11819 } 11820 11821 // Okay! 11822 targetPackageSetting.installerPackageName = installerPackageName; 11823 if (installerPackageName != null) { 11824 mSettings.mInstallerPackages.add(installerPackageName); 11825 } 11826 scheduleWriteSettingsLocked(); 11827 } 11828 } 11829 11830 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 11831 // Queue up an async operation since the package installation may take a little while. 11832 mHandler.post(new Runnable() { 11833 public void run() { 11834 mHandler.removeCallbacks(this); 11835 // Result object to be returned 11836 PackageInstalledInfo res = new PackageInstalledInfo(); 11837 res.setReturnCode(currentStatus); 11838 res.uid = -1; 11839 res.pkg = null; 11840 res.removedInfo = null; 11841 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11842 args.doPreInstall(res.returnCode); 11843 synchronized (mInstallLock) { 11844 installPackageTracedLI(args, res); 11845 } 11846 args.doPostInstall(res.returnCode, res.uid); 11847 } 11848 11849 // A restore should be performed at this point if (a) the install 11850 // succeeded, (b) the operation is not an update, and (c) the new 11851 // package has not opted out of backup participation. 11852 final boolean update = res.removedInfo != null 11853 && res.removedInfo.removedPackage != null; 11854 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 11855 boolean doRestore = !update 11856 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 11857 11858 // Set up the post-install work request bookkeeping. This will be used 11859 // and cleaned up by the post-install event handling regardless of whether 11860 // there's a restore pass performed. Token values are >= 1. 11861 int token; 11862 if (mNextInstallToken < 0) mNextInstallToken = 1; 11863 token = mNextInstallToken++; 11864 11865 PostInstallData data = new PostInstallData(args, res); 11866 mRunningInstalls.put(token, data); 11867 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 11868 11869 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 11870 // Pass responsibility to the Backup Manager. It will perform a 11871 // restore if appropriate, then pass responsibility back to the 11872 // Package Manager to run the post-install observer callbacks 11873 // and broadcasts. 11874 IBackupManager bm = IBackupManager.Stub.asInterface( 11875 ServiceManager.getService(Context.BACKUP_SERVICE)); 11876 if (bm != null) { 11877 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 11878 + " to BM for possible restore"); 11879 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 11880 try { 11881 // TODO: http://b/22388012 11882 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 11883 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 11884 } else { 11885 doRestore = false; 11886 } 11887 } catch (RemoteException e) { 11888 // can't happen; the backup manager is local 11889 } catch (Exception e) { 11890 Slog.e(TAG, "Exception trying to enqueue restore", e); 11891 doRestore = false; 11892 } 11893 } else { 11894 Slog.e(TAG, "Backup Manager not found!"); 11895 doRestore = false; 11896 } 11897 } 11898 11899 if (!doRestore) { 11900 // No restore possible, or the Backup Manager was mysteriously not 11901 // available -- just fire the post-install work request directly. 11902 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 11903 11904 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 11905 11906 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 11907 mHandler.sendMessage(msg); 11908 } 11909 } 11910 }); 11911 } 11912 11913 private abstract class HandlerParams { 11914 private static final int MAX_RETRIES = 4; 11915 11916 /** 11917 * Number of times startCopy() has been attempted and had a non-fatal 11918 * error. 11919 */ 11920 private int mRetries = 0; 11921 11922 /** User handle for the user requesting the information or installation. */ 11923 private final UserHandle mUser; 11924 String traceMethod; 11925 int traceCookie; 11926 11927 HandlerParams(UserHandle user) { 11928 mUser = user; 11929 } 11930 11931 UserHandle getUser() { 11932 return mUser; 11933 } 11934 11935 HandlerParams setTraceMethod(String traceMethod) { 11936 this.traceMethod = traceMethod; 11937 return this; 11938 } 11939 11940 HandlerParams setTraceCookie(int traceCookie) { 11941 this.traceCookie = traceCookie; 11942 return this; 11943 } 11944 11945 final boolean startCopy() { 11946 boolean res; 11947 try { 11948 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 11949 11950 if (++mRetries > MAX_RETRIES) { 11951 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 11952 mHandler.sendEmptyMessage(MCS_GIVE_UP); 11953 handleServiceError(); 11954 return false; 11955 } else { 11956 handleStartCopy(); 11957 res = true; 11958 } 11959 } catch (RemoteException e) { 11960 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 11961 mHandler.sendEmptyMessage(MCS_RECONNECT); 11962 res = false; 11963 } 11964 handleReturnCode(); 11965 return res; 11966 } 11967 11968 final void serviceError() { 11969 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 11970 handleServiceError(); 11971 handleReturnCode(); 11972 } 11973 11974 abstract void handleStartCopy() throws RemoteException; 11975 abstract void handleServiceError(); 11976 abstract void handleReturnCode(); 11977 } 11978 11979 class MeasureParams extends HandlerParams { 11980 private final PackageStats mStats; 11981 private boolean mSuccess; 11982 11983 private final IPackageStatsObserver mObserver; 11984 11985 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 11986 super(new UserHandle(stats.userHandle)); 11987 mObserver = observer; 11988 mStats = stats; 11989 } 11990 11991 @Override 11992 public String toString() { 11993 return "MeasureParams{" 11994 + Integer.toHexString(System.identityHashCode(this)) 11995 + " " + mStats.packageName + "}"; 11996 } 11997 11998 @Override 11999 void handleStartCopy() throws RemoteException { 12000 synchronized (mInstallLock) { 12001 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 12002 } 12003 12004 if (mSuccess) { 12005 final boolean mounted; 12006 if (Environment.isExternalStorageEmulated()) { 12007 mounted = true; 12008 } else { 12009 final String status = Environment.getExternalStorageState(); 12010 mounted = (Environment.MEDIA_MOUNTED.equals(status) 12011 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 12012 } 12013 12014 if (mounted) { 12015 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 12016 12017 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 12018 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 12019 12020 mStats.externalDataSize = calculateDirectorySize(mContainerService, 12021 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 12022 12023 // Always subtract cache size, since it's a subdirectory 12024 mStats.externalDataSize -= mStats.externalCacheSize; 12025 12026 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 12027 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 12028 12029 mStats.externalObbSize = calculateDirectorySize(mContainerService, 12030 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 12031 } 12032 } 12033 } 12034 12035 @Override 12036 void handleReturnCode() { 12037 if (mObserver != null) { 12038 try { 12039 mObserver.onGetStatsCompleted(mStats, mSuccess); 12040 } catch (RemoteException e) { 12041 Slog.i(TAG, "Observer no longer exists."); 12042 } 12043 } 12044 } 12045 12046 @Override 12047 void handleServiceError() { 12048 Slog.e(TAG, "Could not measure application " + mStats.packageName 12049 + " external storage"); 12050 } 12051 } 12052 12053 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 12054 throws RemoteException { 12055 long result = 0; 12056 for (File path : paths) { 12057 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 12058 } 12059 return result; 12060 } 12061 12062 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 12063 for (File path : paths) { 12064 try { 12065 mcs.clearDirectory(path.getAbsolutePath()); 12066 } catch (RemoteException e) { 12067 } 12068 } 12069 } 12070 12071 static class OriginInfo { 12072 /** 12073 * Location where install is coming from, before it has been 12074 * copied/renamed into place. This could be a single monolithic APK 12075 * file, or a cluster directory. This location may be untrusted. 12076 */ 12077 final File file; 12078 final String cid; 12079 12080 /** 12081 * Flag indicating that {@link #file} or {@link #cid} has already been 12082 * staged, meaning downstream users don't need to defensively copy the 12083 * contents. 12084 */ 12085 final boolean staged; 12086 12087 /** 12088 * Flag indicating that {@link #file} or {@link #cid} is an already 12089 * installed app that is being moved. 12090 */ 12091 final boolean existing; 12092 12093 final String resolvedPath; 12094 final File resolvedFile; 12095 12096 static OriginInfo fromNothing() { 12097 return new OriginInfo(null, null, false, false); 12098 } 12099 12100 static OriginInfo fromUntrustedFile(File file) { 12101 return new OriginInfo(file, null, false, false); 12102 } 12103 12104 static OriginInfo fromExistingFile(File file) { 12105 return new OriginInfo(file, null, false, true); 12106 } 12107 12108 static OriginInfo fromStagedFile(File file) { 12109 return new OriginInfo(file, null, true, false); 12110 } 12111 12112 static OriginInfo fromStagedContainer(String cid) { 12113 return new OriginInfo(null, cid, true, false); 12114 } 12115 12116 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 12117 this.file = file; 12118 this.cid = cid; 12119 this.staged = staged; 12120 this.existing = existing; 12121 12122 if (cid != null) { 12123 resolvedPath = PackageHelper.getSdDir(cid); 12124 resolvedFile = new File(resolvedPath); 12125 } else if (file != null) { 12126 resolvedPath = file.getAbsolutePath(); 12127 resolvedFile = file; 12128 } else { 12129 resolvedPath = null; 12130 resolvedFile = null; 12131 } 12132 } 12133 } 12134 12135 static class MoveInfo { 12136 final int moveId; 12137 final String fromUuid; 12138 final String toUuid; 12139 final String packageName; 12140 final String dataAppName; 12141 final int appId; 12142 final String seinfo; 12143 final int targetSdkVersion; 12144 12145 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 12146 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 12147 this.moveId = moveId; 12148 this.fromUuid = fromUuid; 12149 this.toUuid = toUuid; 12150 this.packageName = packageName; 12151 this.dataAppName = dataAppName; 12152 this.appId = appId; 12153 this.seinfo = seinfo; 12154 this.targetSdkVersion = targetSdkVersion; 12155 } 12156 } 12157 12158 static class VerificationInfo { 12159 /** A constant used to indicate that a uid value is not present. */ 12160 public static final int NO_UID = -1; 12161 12162 /** URI referencing where the package was downloaded from. */ 12163 final Uri originatingUri; 12164 12165 /** HTTP referrer URI associated with the originatingURI. */ 12166 final Uri referrer; 12167 12168 /** UID of the application that the install request originated from. */ 12169 final int originatingUid; 12170 12171 /** UID of application requesting the install */ 12172 final int installerUid; 12173 12174 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 12175 this.originatingUri = originatingUri; 12176 this.referrer = referrer; 12177 this.originatingUid = originatingUid; 12178 this.installerUid = installerUid; 12179 } 12180 } 12181 12182 class InstallParams extends HandlerParams { 12183 final OriginInfo origin; 12184 final MoveInfo move; 12185 final IPackageInstallObserver2 observer; 12186 int installFlags; 12187 final String installerPackageName; 12188 final String volumeUuid; 12189 private InstallArgs mArgs; 12190 private int mRet; 12191 final String packageAbiOverride; 12192 final String[] grantedRuntimePermissions; 12193 final VerificationInfo verificationInfo; 12194 final Certificate[][] certificates; 12195 12196 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12197 int installFlags, String installerPackageName, String volumeUuid, 12198 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 12199 String[] grantedPermissions, Certificate[][] certificates) { 12200 super(user); 12201 this.origin = origin; 12202 this.move = move; 12203 this.observer = observer; 12204 this.installFlags = installFlags; 12205 this.installerPackageName = installerPackageName; 12206 this.volumeUuid = volumeUuid; 12207 this.verificationInfo = verificationInfo; 12208 this.packageAbiOverride = packageAbiOverride; 12209 this.grantedRuntimePermissions = grantedPermissions; 12210 this.certificates = certificates; 12211 } 12212 12213 @Override 12214 public String toString() { 12215 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 12216 + " file=" + origin.file + " cid=" + origin.cid + "}"; 12217 } 12218 12219 private int installLocationPolicy(PackageInfoLite pkgLite) { 12220 String packageName = pkgLite.packageName; 12221 int installLocation = pkgLite.installLocation; 12222 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12223 // reader 12224 synchronized (mPackages) { 12225 // Currently installed package which the new package is attempting to replace or 12226 // null if no such package is installed. 12227 PackageParser.Package installedPkg = mPackages.get(packageName); 12228 // Package which currently owns the data which the new package will own if installed. 12229 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 12230 // will be null whereas dataOwnerPkg will contain information about the package 12231 // which was uninstalled while keeping its data. 12232 PackageParser.Package dataOwnerPkg = installedPkg; 12233 if (dataOwnerPkg == null) { 12234 PackageSetting ps = mSettings.mPackages.get(packageName); 12235 if (ps != null) { 12236 dataOwnerPkg = ps.pkg; 12237 } 12238 } 12239 12240 if (dataOwnerPkg != null) { 12241 // If installed, the package will get access to data left on the device by its 12242 // predecessor. As a security measure, this is permited only if this is not a 12243 // version downgrade or if the predecessor package is marked as debuggable and 12244 // a downgrade is explicitly requested. 12245 // 12246 // On debuggable platform builds, downgrades are permitted even for 12247 // non-debuggable packages to make testing easier. Debuggable platform builds do 12248 // not offer security guarantees and thus it's OK to disable some security 12249 // mechanisms to make debugging/testing easier on those builds. However, even on 12250 // debuggable builds downgrades of packages are permitted only if requested via 12251 // installFlags. This is because we aim to keep the behavior of debuggable 12252 // platform builds as close as possible to the behavior of non-debuggable 12253 // platform builds. 12254 final boolean downgradeRequested = 12255 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 12256 final boolean packageDebuggable = 12257 (dataOwnerPkg.applicationInfo.flags 12258 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 12259 final boolean downgradePermitted = 12260 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 12261 if (!downgradePermitted) { 12262 try { 12263 checkDowngrade(dataOwnerPkg, pkgLite); 12264 } catch (PackageManagerException e) { 12265 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 12266 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 12267 } 12268 } 12269 } 12270 12271 if (installedPkg != null) { 12272 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12273 // Check for updated system application. 12274 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 12275 if (onSd) { 12276 Slog.w(TAG, "Cannot install update to system app on sdcard"); 12277 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 12278 } 12279 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12280 } else { 12281 if (onSd) { 12282 // Install flag overrides everything. 12283 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12284 } 12285 // If current upgrade specifies particular preference 12286 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 12287 // Application explicitly specified internal. 12288 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12289 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 12290 // App explictly prefers external. Let policy decide 12291 } else { 12292 // Prefer previous location 12293 if (isExternal(installedPkg)) { 12294 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12295 } 12296 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12297 } 12298 } 12299 } else { 12300 // Invalid install. Return error code 12301 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 12302 } 12303 } 12304 } 12305 // All the special cases have been taken care of. 12306 // Return result based on recommended install location. 12307 if (onSd) { 12308 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12309 } 12310 return pkgLite.recommendedInstallLocation; 12311 } 12312 12313 /* 12314 * Invoke remote method to get package information and install 12315 * location values. Override install location based on default 12316 * policy if needed and then create install arguments based 12317 * on the install location. 12318 */ 12319 public void handleStartCopy() throws RemoteException { 12320 int ret = PackageManager.INSTALL_SUCCEEDED; 12321 12322 // If we're already staged, we've firmly committed to an install location 12323 if (origin.staged) { 12324 if (origin.file != null) { 12325 installFlags |= PackageManager.INSTALL_INTERNAL; 12326 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12327 } else if (origin.cid != null) { 12328 installFlags |= PackageManager.INSTALL_EXTERNAL; 12329 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12330 } else { 12331 throw new IllegalStateException("Invalid stage location"); 12332 } 12333 } 12334 12335 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12336 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 12337 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12338 PackageInfoLite pkgLite = null; 12339 12340 if (onInt && onSd) { 12341 // Check if both bits are set. 12342 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 12343 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12344 } else if (onSd && ephemeral) { 12345 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 12346 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12347 } else { 12348 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 12349 packageAbiOverride); 12350 12351 if (DEBUG_EPHEMERAL && ephemeral) { 12352 Slog.v(TAG, "pkgLite for install: " + pkgLite); 12353 } 12354 12355 /* 12356 * If we have too little free space, try to free cache 12357 * before giving up. 12358 */ 12359 if (!origin.staged && pkgLite.recommendedInstallLocation 12360 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12361 // TODO: focus freeing disk space on the target device 12362 final StorageManager storage = StorageManager.from(mContext); 12363 final long lowThreshold = storage.getStorageLowBytes( 12364 Environment.getDataDirectory()); 12365 12366 final long sizeBytes = mContainerService.calculateInstalledSize( 12367 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 12368 12369 try { 12370 mInstaller.freeCache(null, sizeBytes + lowThreshold); 12371 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 12372 installFlags, packageAbiOverride); 12373 } catch (InstallerException e) { 12374 Slog.w(TAG, "Failed to free cache", e); 12375 } 12376 12377 /* 12378 * The cache free must have deleted the file we 12379 * downloaded to install. 12380 * 12381 * TODO: fix the "freeCache" call to not delete 12382 * the file we care about. 12383 */ 12384 if (pkgLite.recommendedInstallLocation 12385 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12386 pkgLite.recommendedInstallLocation 12387 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 12388 } 12389 } 12390 } 12391 12392 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12393 int loc = pkgLite.recommendedInstallLocation; 12394 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 12395 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12396 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 12397 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 12398 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12399 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12400 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 12401 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 12402 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12403 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 12404 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 12405 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 12406 } else { 12407 // Override with defaults if needed. 12408 loc = installLocationPolicy(pkgLite); 12409 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 12410 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 12411 } else if (!onSd && !onInt) { 12412 // Override install location with flags 12413 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 12414 // Set the flag to install on external media. 12415 installFlags |= PackageManager.INSTALL_EXTERNAL; 12416 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12417 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 12418 if (DEBUG_EPHEMERAL) { 12419 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 12420 } 12421 installFlags |= PackageManager.INSTALL_EPHEMERAL; 12422 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 12423 |PackageManager.INSTALL_INTERNAL); 12424 } else { 12425 // Make sure the flag for installing on external 12426 // media is unset 12427 installFlags |= PackageManager.INSTALL_INTERNAL; 12428 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12429 } 12430 } 12431 } 12432 } 12433 12434 final InstallArgs args = createInstallArgs(this); 12435 mArgs = args; 12436 12437 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12438 // TODO: http://b/22976637 12439 // Apps installed for "all" users use the device owner to verify the app 12440 UserHandle verifierUser = getUser(); 12441 if (verifierUser == UserHandle.ALL) { 12442 verifierUser = UserHandle.SYSTEM; 12443 } 12444 12445 /* 12446 * Determine if we have any installed package verifiers. If we 12447 * do, then we'll defer to them to verify the packages. 12448 */ 12449 final int requiredUid = mRequiredVerifierPackage == null ? -1 12450 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 12451 verifierUser.getIdentifier()); 12452 if (!origin.existing && requiredUid != -1 12453 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 12454 final Intent verification = new Intent( 12455 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 12456 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 12457 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 12458 PACKAGE_MIME_TYPE); 12459 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 12460 12461 // Query all live verifiers based on current user state 12462 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 12463 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 12464 12465 if (DEBUG_VERIFY) { 12466 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 12467 + verification.toString() + " with " + pkgLite.verifiers.length 12468 + " optional verifiers"); 12469 } 12470 12471 final int verificationId = mPendingVerificationToken++; 12472 12473 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 12474 12475 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 12476 installerPackageName); 12477 12478 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 12479 installFlags); 12480 12481 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 12482 pkgLite.packageName); 12483 12484 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 12485 pkgLite.versionCode); 12486 12487 if (verificationInfo != null) { 12488 if (verificationInfo.originatingUri != null) { 12489 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 12490 verificationInfo.originatingUri); 12491 } 12492 if (verificationInfo.referrer != null) { 12493 verification.putExtra(Intent.EXTRA_REFERRER, 12494 verificationInfo.referrer); 12495 } 12496 if (verificationInfo.originatingUid >= 0) { 12497 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 12498 verificationInfo.originatingUid); 12499 } 12500 if (verificationInfo.installerUid >= 0) { 12501 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 12502 verificationInfo.installerUid); 12503 } 12504 } 12505 12506 final PackageVerificationState verificationState = new PackageVerificationState( 12507 requiredUid, args); 12508 12509 mPendingVerification.append(verificationId, verificationState); 12510 12511 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 12512 receivers, verificationState); 12513 12514 /* 12515 * If any sufficient verifiers were listed in the package 12516 * manifest, attempt to ask them. 12517 */ 12518 if (sufficientVerifiers != null) { 12519 final int N = sufficientVerifiers.size(); 12520 if (N == 0) { 12521 Slog.i(TAG, "Additional verifiers required, but none installed."); 12522 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 12523 } else { 12524 for (int i = 0; i < N; i++) { 12525 final ComponentName verifierComponent = sufficientVerifiers.get(i); 12526 12527 final Intent sufficientIntent = new Intent(verification); 12528 sufficientIntent.setComponent(verifierComponent); 12529 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 12530 } 12531 } 12532 } 12533 12534 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 12535 mRequiredVerifierPackage, receivers); 12536 if (ret == PackageManager.INSTALL_SUCCEEDED 12537 && mRequiredVerifierPackage != null) { 12538 Trace.asyncTraceBegin( 12539 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 12540 /* 12541 * Send the intent to the required verification agent, 12542 * but only start the verification timeout after the 12543 * target BroadcastReceivers have run. 12544 */ 12545 verification.setComponent(requiredVerifierComponent); 12546 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 12547 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12548 new BroadcastReceiver() { 12549 @Override 12550 public void onReceive(Context context, Intent intent) { 12551 final Message msg = mHandler 12552 .obtainMessage(CHECK_PENDING_VERIFICATION); 12553 msg.arg1 = verificationId; 12554 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 12555 } 12556 }, null, 0, null, null); 12557 12558 /* 12559 * We don't want the copy to proceed until verification 12560 * succeeds, so null out this field. 12561 */ 12562 mArgs = null; 12563 } 12564 } else { 12565 /* 12566 * No package verification is enabled, so immediately start 12567 * the remote call to initiate copy using temporary file. 12568 */ 12569 ret = args.copyApk(mContainerService, true); 12570 } 12571 } 12572 12573 mRet = ret; 12574 } 12575 12576 @Override 12577 void handleReturnCode() { 12578 // If mArgs is null, then MCS couldn't be reached. When it 12579 // reconnects, it will try again to install. At that point, this 12580 // will succeed. 12581 if (mArgs != null) { 12582 processPendingInstall(mArgs, mRet); 12583 } 12584 } 12585 12586 @Override 12587 void handleServiceError() { 12588 mArgs = createInstallArgs(this); 12589 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12590 } 12591 12592 public boolean isForwardLocked() { 12593 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12594 } 12595 } 12596 12597 /** 12598 * Used during creation of InstallArgs 12599 * 12600 * @param installFlags package installation flags 12601 * @return true if should be installed on external storage 12602 */ 12603 private static boolean installOnExternalAsec(int installFlags) { 12604 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 12605 return false; 12606 } 12607 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 12608 return true; 12609 } 12610 return false; 12611 } 12612 12613 /** 12614 * Used during creation of InstallArgs 12615 * 12616 * @param installFlags package installation flags 12617 * @return true if should be installed as forward locked 12618 */ 12619 private static boolean installForwardLocked(int installFlags) { 12620 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12621 } 12622 12623 private InstallArgs createInstallArgs(InstallParams params) { 12624 if (params.move != null) { 12625 return new MoveInstallArgs(params); 12626 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 12627 return new AsecInstallArgs(params); 12628 } else { 12629 return new FileInstallArgs(params); 12630 } 12631 } 12632 12633 /** 12634 * Create args that describe an existing installed package. Typically used 12635 * when cleaning up old installs, or used as a move source. 12636 */ 12637 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 12638 String resourcePath, String[] instructionSets) { 12639 final boolean isInAsec; 12640 if (installOnExternalAsec(installFlags)) { 12641 /* Apps on SD card are always in ASEC containers. */ 12642 isInAsec = true; 12643 } else if (installForwardLocked(installFlags) 12644 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 12645 /* 12646 * Forward-locked apps are only in ASEC containers if they're the 12647 * new style 12648 */ 12649 isInAsec = true; 12650 } else { 12651 isInAsec = false; 12652 } 12653 12654 if (isInAsec) { 12655 return new AsecInstallArgs(codePath, instructionSets, 12656 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 12657 } else { 12658 return new FileInstallArgs(codePath, resourcePath, instructionSets); 12659 } 12660 } 12661 12662 static abstract class InstallArgs { 12663 /** @see InstallParams#origin */ 12664 final OriginInfo origin; 12665 /** @see InstallParams#move */ 12666 final MoveInfo move; 12667 12668 final IPackageInstallObserver2 observer; 12669 // Always refers to PackageManager flags only 12670 final int installFlags; 12671 final String installerPackageName; 12672 final String volumeUuid; 12673 final UserHandle user; 12674 final String abiOverride; 12675 final String[] installGrantPermissions; 12676 /** If non-null, drop an async trace when the install completes */ 12677 final String traceMethod; 12678 final int traceCookie; 12679 final Certificate[][] certificates; 12680 12681 // The list of instruction sets supported by this app. This is currently 12682 // only used during the rmdex() phase to clean up resources. We can get rid of this 12683 // if we move dex files under the common app path. 12684 /* nullable */ String[] instructionSets; 12685 12686 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12687 int installFlags, String installerPackageName, String volumeUuid, 12688 UserHandle user, String[] instructionSets, 12689 String abiOverride, String[] installGrantPermissions, 12690 String traceMethod, int traceCookie, Certificate[][] certificates) { 12691 this.origin = origin; 12692 this.move = move; 12693 this.installFlags = installFlags; 12694 this.observer = observer; 12695 this.installerPackageName = installerPackageName; 12696 this.volumeUuid = volumeUuid; 12697 this.user = user; 12698 this.instructionSets = instructionSets; 12699 this.abiOverride = abiOverride; 12700 this.installGrantPermissions = installGrantPermissions; 12701 this.traceMethod = traceMethod; 12702 this.traceCookie = traceCookie; 12703 this.certificates = certificates; 12704 } 12705 12706 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 12707 abstract int doPreInstall(int status); 12708 12709 /** 12710 * Rename package into final resting place. All paths on the given 12711 * scanned package should be updated to reflect the rename. 12712 */ 12713 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 12714 abstract int doPostInstall(int status, int uid); 12715 12716 /** @see PackageSettingBase#codePathString */ 12717 abstract String getCodePath(); 12718 /** @see PackageSettingBase#resourcePathString */ 12719 abstract String getResourcePath(); 12720 12721 // Need installer lock especially for dex file removal. 12722 abstract void cleanUpResourcesLI(); 12723 abstract boolean doPostDeleteLI(boolean delete); 12724 12725 /** 12726 * Called before the source arguments are copied. This is used mostly 12727 * for MoveParams when it needs to read the source file to put it in the 12728 * destination. 12729 */ 12730 int doPreCopy() { 12731 return PackageManager.INSTALL_SUCCEEDED; 12732 } 12733 12734 /** 12735 * Called after the source arguments are copied. This is used mostly for 12736 * MoveParams when it needs to read the source file to put it in the 12737 * destination. 12738 */ 12739 int doPostCopy(int uid) { 12740 return PackageManager.INSTALL_SUCCEEDED; 12741 } 12742 12743 protected boolean isFwdLocked() { 12744 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12745 } 12746 12747 protected boolean isExternalAsec() { 12748 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12749 } 12750 12751 protected boolean isEphemeral() { 12752 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12753 } 12754 12755 UserHandle getUser() { 12756 return user; 12757 } 12758 } 12759 12760 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 12761 if (!allCodePaths.isEmpty()) { 12762 if (instructionSets == null) { 12763 throw new IllegalStateException("instructionSet == null"); 12764 } 12765 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 12766 for (String codePath : allCodePaths) { 12767 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 12768 try { 12769 mInstaller.rmdex(codePath, dexCodeInstructionSet); 12770 } catch (InstallerException ignored) { 12771 } 12772 } 12773 } 12774 } 12775 } 12776 12777 /** 12778 * Logic to handle installation of non-ASEC applications, including copying 12779 * and renaming logic. 12780 */ 12781 class FileInstallArgs extends InstallArgs { 12782 private File codeFile; 12783 private File resourceFile; 12784 12785 // Example topology: 12786 // /data/app/com.example/base.apk 12787 // /data/app/com.example/split_foo.apk 12788 // /data/app/com.example/lib/arm/libfoo.so 12789 // /data/app/com.example/lib/arm64/libfoo.so 12790 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 12791 12792 /** New install */ 12793 FileInstallArgs(InstallParams params) { 12794 super(params.origin, params.move, params.observer, params.installFlags, 12795 params.installerPackageName, params.volumeUuid, 12796 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 12797 params.grantedRuntimePermissions, 12798 params.traceMethod, params.traceCookie, params.certificates); 12799 if (isFwdLocked()) { 12800 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 12801 } 12802 } 12803 12804 /** Existing install */ 12805 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 12806 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 12807 null, null, null, 0, null /*certificates*/); 12808 this.codeFile = (codePath != null) ? new File(codePath) : null; 12809 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 12810 } 12811 12812 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12813 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 12814 try { 12815 return doCopyApk(imcs, temp); 12816 } finally { 12817 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12818 } 12819 } 12820 12821 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12822 if (origin.staged) { 12823 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 12824 codeFile = origin.file; 12825 resourceFile = origin.file; 12826 return PackageManager.INSTALL_SUCCEEDED; 12827 } 12828 12829 try { 12830 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12831 final File tempDir = 12832 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 12833 codeFile = tempDir; 12834 resourceFile = tempDir; 12835 } catch (IOException e) { 12836 Slog.w(TAG, "Failed to create copy file: " + e); 12837 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12838 } 12839 12840 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 12841 @Override 12842 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 12843 if (!FileUtils.isValidExtFilename(name)) { 12844 throw new IllegalArgumentException("Invalid filename: " + name); 12845 } 12846 try { 12847 final File file = new File(codeFile, name); 12848 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 12849 O_RDWR | O_CREAT, 0644); 12850 Os.chmod(file.getAbsolutePath(), 0644); 12851 return new ParcelFileDescriptor(fd); 12852 } catch (ErrnoException e) { 12853 throw new RemoteException("Failed to open: " + e.getMessage()); 12854 } 12855 } 12856 }; 12857 12858 int ret = PackageManager.INSTALL_SUCCEEDED; 12859 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 12860 if (ret != PackageManager.INSTALL_SUCCEEDED) { 12861 Slog.e(TAG, "Failed to copy package"); 12862 return ret; 12863 } 12864 12865 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 12866 NativeLibraryHelper.Handle handle = null; 12867 try { 12868 handle = NativeLibraryHelper.Handle.create(codeFile); 12869 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 12870 abiOverride); 12871 } catch (IOException e) { 12872 Slog.e(TAG, "Copying native libraries failed", e); 12873 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12874 } finally { 12875 IoUtils.closeQuietly(handle); 12876 } 12877 12878 return ret; 12879 } 12880 12881 int doPreInstall(int status) { 12882 if (status != PackageManager.INSTALL_SUCCEEDED) { 12883 cleanUp(); 12884 } 12885 return status; 12886 } 12887 12888 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 12889 if (status != PackageManager.INSTALL_SUCCEEDED) { 12890 cleanUp(); 12891 return false; 12892 } 12893 12894 final File targetDir = codeFile.getParentFile(); 12895 final File beforeCodeFile = codeFile; 12896 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 12897 12898 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 12899 try { 12900 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 12901 } catch (ErrnoException e) { 12902 Slog.w(TAG, "Failed to rename", e); 12903 return false; 12904 } 12905 12906 if (!SELinux.restoreconRecursive(afterCodeFile)) { 12907 Slog.w(TAG, "Failed to restorecon"); 12908 return false; 12909 } 12910 12911 // Reflect the rename internally 12912 codeFile = afterCodeFile; 12913 resourceFile = afterCodeFile; 12914 12915 // Reflect the rename in scanned details 12916 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 12917 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 12918 afterCodeFile, pkg.baseCodePath)); 12919 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 12920 afterCodeFile, pkg.splitCodePaths)); 12921 12922 // Reflect the rename in app info 12923 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 12924 pkg.setApplicationInfoCodePath(pkg.codePath); 12925 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 12926 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 12927 pkg.setApplicationInfoResourcePath(pkg.codePath); 12928 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 12929 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 12930 12931 return true; 12932 } 12933 12934 int doPostInstall(int status, int uid) { 12935 if (status != PackageManager.INSTALL_SUCCEEDED) { 12936 cleanUp(); 12937 } 12938 return status; 12939 } 12940 12941 @Override 12942 String getCodePath() { 12943 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 12944 } 12945 12946 @Override 12947 String getResourcePath() { 12948 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 12949 } 12950 12951 private boolean cleanUp() { 12952 if (codeFile == null || !codeFile.exists()) { 12953 return false; 12954 } 12955 12956 removeCodePathLI(codeFile); 12957 12958 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 12959 resourceFile.delete(); 12960 } 12961 12962 return true; 12963 } 12964 12965 void cleanUpResourcesLI() { 12966 // Try enumerating all code paths before deleting 12967 List<String> allCodePaths = Collections.EMPTY_LIST; 12968 if (codeFile != null && codeFile.exists()) { 12969 try { 12970 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 12971 allCodePaths = pkg.getAllCodePaths(); 12972 } catch (PackageParserException e) { 12973 // Ignored; we tried our best 12974 } 12975 } 12976 12977 cleanUp(); 12978 removeDexFiles(allCodePaths, instructionSets); 12979 } 12980 12981 boolean doPostDeleteLI(boolean delete) { 12982 // XXX err, shouldn't we respect the delete flag? 12983 cleanUpResourcesLI(); 12984 return true; 12985 } 12986 } 12987 12988 private boolean isAsecExternal(String cid) { 12989 final String asecPath = PackageHelper.getSdFilesystem(cid); 12990 return !asecPath.startsWith(mAsecInternalPath); 12991 } 12992 12993 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 12994 PackageManagerException { 12995 if (copyRet < 0) { 12996 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 12997 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 12998 throw new PackageManagerException(copyRet, message); 12999 } 13000 } 13001 } 13002 13003 /** 13004 * Extract the MountService "container ID" from the full code path of an 13005 * .apk. 13006 */ 13007 static String cidFromCodePath(String fullCodePath) { 13008 int eidx = fullCodePath.lastIndexOf("/"); 13009 String subStr1 = fullCodePath.substring(0, eidx); 13010 int sidx = subStr1.lastIndexOf("/"); 13011 return subStr1.substring(sidx+1, eidx); 13012 } 13013 13014 /** 13015 * Logic to handle installation of ASEC applications, including copying and 13016 * renaming logic. 13017 */ 13018 class AsecInstallArgs extends InstallArgs { 13019 static final String RES_FILE_NAME = "pkg.apk"; 13020 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 13021 13022 String cid; 13023 String packagePath; 13024 String resourcePath; 13025 13026 /** New install */ 13027 AsecInstallArgs(InstallParams params) { 13028 super(params.origin, params.move, params.observer, params.installFlags, 13029 params.installerPackageName, params.volumeUuid, 13030 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13031 params.grantedRuntimePermissions, 13032 params.traceMethod, params.traceCookie, params.certificates); 13033 } 13034 13035 /** Existing install */ 13036 AsecInstallArgs(String fullCodePath, String[] instructionSets, 13037 boolean isExternal, boolean isForwardLocked) { 13038 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 13039 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13040 instructionSets, null, null, null, 0, null /*certificates*/); 13041 // Hackily pretend we're still looking at a full code path 13042 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 13043 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 13044 } 13045 13046 // Extract cid from fullCodePath 13047 int eidx = fullCodePath.lastIndexOf("/"); 13048 String subStr1 = fullCodePath.substring(0, eidx); 13049 int sidx = subStr1.lastIndexOf("/"); 13050 cid = subStr1.substring(sidx+1, eidx); 13051 setMountPath(subStr1); 13052 } 13053 13054 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 13055 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 13056 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13057 instructionSets, null, null, null, 0, null /*certificates*/); 13058 this.cid = cid; 13059 setMountPath(PackageHelper.getSdDir(cid)); 13060 } 13061 13062 void createCopyFile() { 13063 cid = mInstallerService.allocateExternalStageCidLegacy(); 13064 } 13065 13066 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13067 if (origin.staged && origin.cid != null) { 13068 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 13069 cid = origin.cid; 13070 setMountPath(PackageHelper.getSdDir(cid)); 13071 return PackageManager.INSTALL_SUCCEEDED; 13072 } 13073 13074 if (temp) { 13075 createCopyFile(); 13076 } else { 13077 /* 13078 * Pre-emptively destroy the container since it's destroyed if 13079 * copying fails due to it existing anyway. 13080 */ 13081 PackageHelper.destroySdDir(cid); 13082 } 13083 13084 final String newMountPath = imcs.copyPackageToContainer( 13085 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 13086 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 13087 13088 if (newMountPath != null) { 13089 setMountPath(newMountPath); 13090 return PackageManager.INSTALL_SUCCEEDED; 13091 } else { 13092 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13093 } 13094 } 13095 13096 @Override 13097 String getCodePath() { 13098 return packagePath; 13099 } 13100 13101 @Override 13102 String getResourcePath() { 13103 return resourcePath; 13104 } 13105 13106 int doPreInstall(int status) { 13107 if (status != PackageManager.INSTALL_SUCCEEDED) { 13108 // Destroy container 13109 PackageHelper.destroySdDir(cid); 13110 } else { 13111 boolean mounted = PackageHelper.isContainerMounted(cid); 13112 if (!mounted) { 13113 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 13114 Process.SYSTEM_UID); 13115 if (newMountPath != null) { 13116 setMountPath(newMountPath); 13117 } else { 13118 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13119 } 13120 } 13121 } 13122 return status; 13123 } 13124 13125 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13126 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 13127 String newMountPath = null; 13128 if (PackageHelper.isContainerMounted(cid)) { 13129 // Unmount the container 13130 if (!PackageHelper.unMountSdDir(cid)) { 13131 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 13132 return false; 13133 } 13134 } 13135 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13136 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 13137 " which might be stale. Will try to clean up."); 13138 // Clean up the stale container and proceed to recreate. 13139 if (!PackageHelper.destroySdDir(newCacheId)) { 13140 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 13141 return false; 13142 } 13143 // Successfully cleaned up stale container. Try to rename again. 13144 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13145 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 13146 + " inspite of cleaning it up."); 13147 return false; 13148 } 13149 } 13150 if (!PackageHelper.isContainerMounted(newCacheId)) { 13151 Slog.w(TAG, "Mounting container " + newCacheId); 13152 newMountPath = PackageHelper.mountSdDir(newCacheId, 13153 getEncryptKey(), Process.SYSTEM_UID); 13154 } else { 13155 newMountPath = PackageHelper.getSdDir(newCacheId); 13156 } 13157 if (newMountPath == null) { 13158 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 13159 return false; 13160 } 13161 Log.i(TAG, "Succesfully renamed " + cid + 13162 " to " + newCacheId + 13163 " at new path: " + newMountPath); 13164 cid = newCacheId; 13165 13166 final File beforeCodeFile = new File(packagePath); 13167 setMountPath(newMountPath); 13168 final File afterCodeFile = new File(packagePath); 13169 13170 // Reflect the rename in scanned details 13171 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13172 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13173 afterCodeFile, pkg.baseCodePath)); 13174 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13175 afterCodeFile, pkg.splitCodePaths)); 13176 13177 // Reflect the rename in app info 13178 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13179 pkg.setApplicationInfoCodePath(pkg.codePath); 13180 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13181 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13182 pkg.setApplicationInfoResourcePath(pkg.codePath); 13183 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13184 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13185 13186 return true; 13187 } 13188 13189 private void setMountPath(String mountPath) { 13190 final File mountFile = new File(mountPath); 13191 13192 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 13193 if (monolithicFile.exists()) { 13194 packagePath = monolithicFile.getAbsolutePath(); 13195 if (isFwdLocked()) { 13196 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 13197 } else { 13198 resourcePath = packagePath; 13199 } 13200 } else { 13201 packagePath = mountFile.getAbsolutePath(); 13202 resourcePath = packagePath; 13203 } 13204 } 13205 13206 int doPostInstall(int status, int uid) { 13207 if (status != PackageManager.INSTALL_SUCCEEDED) { 13208 cleanUp(); 13209 } else { 13210 final int groupOwner; 13211 final String protectedFile; 13212 if (isFwdLocked()) { 13213 groupOwner = UserHandle.getSharedAppGid(uid); 13214 protectedFile = RES_FILE_NAME; 13215 } else { 13216 groupOwner = -1; 13217 protectedFile = null; 13218 } 13219 13220 if (uid < Process.FIRST_APPLICATION_UID 13221 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 13222 Slog.e(TAG, "Failed to finalize " + cid); 13223 PackageHelper.destroySdDir(cid); 13224 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13225 } 13226 13227 boolean mounted = PackageHelper.isContainerMounted(cid); 13228 if (!mounted) { 13229 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 13230 } 13231 } 13232 return status; 13233 } 13234 13235 private void cleanUp() { 13236 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 13237 13238 // Destroy secure container 13239 PackageHelper.destroySdDir(cid); 13240 } 13241 13242 private List<String> getAllCodePaths() { 13243 final File codeFile = new File(getCodePath()); 13244 if (codeFile != null && codeFile.exists()) { 13245 try { 13246 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13247 return pkg.getAllCodePaths(); 13248 } catch (PackageParserException e) { 13249 // Ignored; we tried our best 13250 } 13251 } 13252 return Collections.EMPTY_LIST; 13253 } 13254 13255 void cleanUpResourcesLI() { 13256 // Enumerate all code paths before deleting 13257 cleanUpResourcesLI(getAllCodePaths()); 13258 } 13259 13260 private void cleanUpResourcesLI(List<String> allCodePaths) { 13261 cleanUp(); 13262 removeDexFiles(allCodePaths, instructionSets); 13263 } 13264 13265 String getPackageName() { 13266 return getAsecPackageName(cid); 13267 } 13268 13269 boolean doPostDeleteLI(boolean delete) { 13270 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 13271 final List<String> allCodePaths = getAllCodePaths(); 13272 boolean mounted = PackageHelper.isContainerMounted(cid); 13273 if (mounted) { 13274 // Unmount first 13275 if (PackageHelper.unMountSdDir(cid)) { 13276 mounted = false; 13277 } 13278 } 13279 if (!mounted && delete) { 13280 cleanUpResourcesLI(allCodePaths); 13281 } 13282 return !mounted; 13283 } 13284 13285 @Override 13286 int doPreCopy() { 13287 if (isFwdLocked()) { 13288 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 13289 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 13290 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13291 } 13292 } 13293 13294 return PackageManager.INSTALL_SUCCEEDED; 13295 } 13296 13297 @Override 13298 int doPostCopy(int uid) { 13299 if (isFwdLocked()) { 13300 if (uid < Process.FIRST_APPLICATION_UID 13301 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 13302 RES_FILE_NAME)) { 13303 Slog.e(TAG, "Failed to finalize " + cid); 13304 PackageHelper.destroySdDir(cid); 13305 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13306 } 13307 } 13308 13309 return PackageManager.INSTALL_SUCCEEDED; 13310 } 13311 } 13312 13313 /** 13314 * Logic to handle movement of existing installed applications. 13315 */ 13316 class MoveInstallArgs extends InstallArgs { 13317 private File codeFile; 13318 private File resourceFile; 13319 13320 /** New install */ 13321 MoveInstallArgs(InstallParams params) { 13322 super(params.origin, params.move, params.observer, params.installFlags, 13323 params.installerPackageName, params.volumeUuid, 13324 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13325 params.grantedRuntimePermissions, 13326 params.traceMethod, params.traceCookie, params.certificates); 13327 } 13328 13329 int copyApk(IMediaContainerService imcs, boolean temp) { 13330 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 13331 + move.fromUuid + " to " + move.toUuid); 13332 synchronized (mInstaller) { 13333 try { 13334 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 13335 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 13336 } catch (InstallerException e) { 13337 Slog.w(TAG, "Failed to move app", e); 13338 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13339 } 13340 } 13341 13342 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 13343 resourceFile = codeFile; 13344 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 13345 13346 return PackageManager.INSTALL_SUCCEEDED; 13347 } 13348 13349 int doPreInstall(int status) { 13350 if (status != PackageManager.INSTALL_SUCCEEDED) { 13351 cleanUp(move.toUuid); 13352 } 13353 return status; 13354 } 13355 13356 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13357 if (status != PackageManager.INSTALL_SUCCEEDED) { 13358 cleanUp(move.toUuid); 13359 return false; 13360 } 13361 13362 // Reflect the move in app info 13363 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13364 pkg.setApplicationInfoCodePath(pkg.codePath); 13365 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13366 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13367 pkg.setApplicationInfoResourcePath(pkg.codePath); 13368 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13369 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13370 13371 return true; 13372 } 13373 13374 int doPostInstall(int status, int uid) { 13375 if (status == PackageManager.INSTALL_SUCCEEDED) { 13376 cleanUp(move.fromUuid); 13377 } else { 13378 cleanUp(move.toUuid); 13379 } 13380 return status; 13381 } 13382 13383 @Override 13384 String getCodePath() { 13385 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13386 } 13387 13388 @Override 13389 String getResourcePath() { 13390 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13391 } 13392 13393 private boolean cleanUp(String volumeUuid) { 13394 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 13395 move.dataAppName); 13396 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 13397 synchronized (mInstallLock) { 13398 // Clean up both app data and code 13399 // All package moves are frozen until finished 13400 try { 13401 mInstaller.destroyAppData(volumeUuid, move.packageName, UserHandle.USER_ALL, 13402 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 13403 } catch (InstallerException e) { 13404 Slog.w(TAG, String.valueOf(e)); 13405 } 13406 removeCodePathLI(codeFile); 13407 } 13408 return true; 13409 } 13410 13411 void cleanUpResourcesLI() { 13412 throw new UnsupportedOperationException(); 13413 } 13414 13415 boolean doPostDeleteLI(boolean delete) { 13416 throw new UnsupportedOperationException(); 13417 } 13418 } 13419 13420 static String getAsecPackageName(String packageCid) { 13421 int idx = packageCid.lastIndexOf("-"); 13422 if (idx == -1) { 13423 return packageCid; 13424 } 13425 return packageCid.substring(0, idx); 13426 } 13427 13428 // Utility method used to create code paths based on package name and available index. 13429 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 13430 String idxStr = ""; 13431 int idx = 1; 13432 // Fall back to default value of idx=1 if prefix is not 13433 // part of oldCodePath 13434 if (oldCodePath != null) { 13435 String subStr = oldCodePath; 13436 // Drop the suffix right away 13437 if (suffix != null && subStr.endsWith(suffix)) { 13438 subStr = subStr.substring(0, subStr.length() - suffix.length()); 13439 } 13440 // If oldCodePath already contains prefix find out the 13441 // ending index to either increment or decrement. 13442 int sidx = subStr.lastIndexOf(prefix); 13443 if (sidx != -1) { 13444 subStr = subStr.substring(sidx + prefix.length()); 13445 if (subStr != null) { 13446 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 13447 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 13448 } 13449 try { 13450 idx = Integer.parseInt(subStr); 13451 if (idx <= 1) { 13452 idx++; 13453 } else { 13454 idx--; 13455 } 13456 } catch(NumberFormatException e) { 13457 } 13458 } 13459 } 13460 } 13461 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 13462 return prefix + idxStr; 13463 } 13464 13465 private File getNextCodePath(File targetDir, String packageName) { 13466 int suffix = 1; 13467 File result; 13468 do { 13469 result = new File(targetDir, packageName + "-" + suffix); 13470 suffix++; 13471 } while (result.exists()); 13472 return result; 13473 } 13474 13475 // Utility method that returns the relative package path with respect 13476 // to the installation directory. Like say for /data/data/com.test-1.apk 13477 // string com.test-1 is returned. 13478 static String deriveCodePathName(String codePath) { 13479 if (codePath == null) { 13480 return null; 13481 } 13482 final File codeFile = new File(codePath); 13483 final String name = codeFile.getName(); 13484 if (codeFile.isDirectory()) { 13485 return name; 13486 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 13487 final int lastDot = name.lastIndexOf('.'); 13488 return name.substring(0, lastDot); 13489 } else { 13490 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 13491 return null; 13492 } 13493 } 13494 13495 static class PackageInstalledInfo { 13496 String name; 13497 int uid; 13498 // The set of users that originally had this package installed. 13499 int[] origUsers; 13500 // The set of users that now have this package installed. 13501 int[] newUsers; 13502 PackageParser.Package pkg; 13503 int returnCode; 13504 String returnMsg; 13505 PackageRemovedInfo removedInfo; 13506 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 13507 13508 public void setError(int code, String msg) { 13509 setReturnCode(code); 13510 setReturnMessage(msg); 13511 Slog.w(TAG, msg); 13512 } 13513 13514 public void setError(String msg, PackageParserException e) { 13515 setReturnCode(e.error); 13516 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13517 Slog.w(TAG, msg, e); 13518 } 13519 13520 public void setError(String msg, PackageManagerException e) { 13521 returnCode = e.error; 13522 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13523 Slog.w(TAG, msg, e); 13524 } 13525 13526 public void setReturnCode(int returnCode) { 13527 this.returnCode = returnCode; 13528 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13529 for (int i = 0; i < childCount; i++) { 13530 addedChildPackages.valueAt(i).returnCode = returnCode; 13531 } 13532 } 13533 13534 private void setReturnMessage(String returnMsg) { 13535 this.returnMsg = returnMsg; 13536 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13537 for (int i = 0; i < childCount; i++) { 13538 addedChildPackages.valueAt(i).returnMsg = returnMsg; 13539 } 13540 } 13541 13542 // In some error cases we want to convey more info back to the observer 13543 String origPackage; 13544 String origPermission; 13545 } 13546 13547 /* 13548 * Install a non-existing package. 13549 */ 13550 private void installNewPackageLIF(PackageParser.Package pkg, int parseFlags, int scanFlags, 13551 UserHandle user, String installerPackageName, String volumeUuid, 13552 PackageInstalledInfo res) { 13553 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 13554 13555 // Remember this for later, in case we need to rollback this install 13556 String pkgName = pkg.packageName; 13557 13558 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 13559 13560 synchronized(mPackages) { 13561 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 13562 // A package with the same name is already installed, though 13563 // it has been renamed to an older name. The package we 13564 // are trying to install should be installed as an update to 13565 // the existing one, but that has not been requested, so bail. 13566 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13567 + " without first uninstalling package running as " 13568 + mSettings.mRenamedPackages.get(pkgName)); 13569 return; 13570 } 13571 if (mPackages.containsKey(pkgName)) { 13572 // Don't allow installation over an existing package with the same name. 13573 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13574 + " without first uninstalling."); 13575 return; 13576 } 13577 } 13578 13579 try { 13580 PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 13581 System.currentTimeMillis(), user); 13582 13583 updateSettingsLI(newPackage, installerPackageName, null, res, user); 13584 13585 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13586 prepareAppDataAfterInstallLIF(newPackage); 13587 13588 } else { 13589 // Remove package from internal structures, but keep around any 13590 // data that might have already existed 13591 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 13592 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 13593 } 13594 } catch (PackageManagerException e) { 13595 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13596 } 13597 13598 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13599 } 13600 13601 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 13602 // Can't rotate keys during boot or if sharedUser. 13603 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 13604 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 13605 return false; 13606 } 13607 // app is using upgradeKeySets; make sure all are valid 13608 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13609 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 13610 for (int i = 0; i < upgradeKeySets.length; i++) { 13611 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 13612 Slog.wtf(TAG, "Package " 13613 + (oldPs.name != null ? oldPs.name : "<null>") 13614 + " contains upgrade-key-set reference to unknown key-set: " 13615 + upgradeKeySets[i] 13616 + " reverting to signatures check."); 13617 return false; 13618 } 13619 } 13620 return true; 13621 } 13622 13623 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 13624 // Upgrade keysets are being used. Determine if new package has a superset of the 13625 // required keys. 13626 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 13627 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13628 for (int i = 0; i < upgradeKeySets.length; i++) { 13629 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 13630 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 13631 return true; 13632 } 13633 } 13634 return false; 13635 } 13636 13637 private void replacePackageLIF(PackageParser.Package pkg, int parseFlags, int scanFlags, 13638 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 13639 final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 13640 13641 final PackageParser.Package oldPackage; 13642 final String pkgName = pkg.packageName; 13643 final int[] allUsers; 13644 13645 // First find the old package info and check signatures 13646 synchronized(mPackages) { 13647 oldPackage = mPackages.get(pkgName); 13648 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 13649 if (isEphemeral && !oldIsEphemeral) { 13650 // can't downgrade from full to ephemeral 13651 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 13652 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 13653 return; 13654 } 13655 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 13656 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13657 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 13658 if (!checkUpgradeKeySetLP(ps, pkg)) { 13659 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13660 "New package not signed by keys specified by upgrade-keysets: " 13661 + pkgName); 13662 return; 13663 } 13664 } else { 13665 // default to original signature matching 13666 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 13667 != PackageManager.SIGNATURE_MATCH) { 13668 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13669 "New package has a different signature: " + pkgName); 13670 return; 13671 } 13672 } 13673 13674 // Check for shared user id changes 13675 String invalidPackageName = 13676 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 13677 if (invalidPackageName != null) { 13678 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 13679 "Package " + invalidPackageName + " tried to change user " 13680 + oldPackage.mSharedUserId); 13681 return; 13682 } 13683 13684 // In case of rollback, remember per-user/profile install state 13685 allUsers = sUserManager.getUserIds(); 13686 } 13687 13688 // Update what is removed 13689 res.removedInfo = new PackageRemovedInfo(); 13690 res.removedInfo.uid = oldPackage.applicationInfo.uid; 13691 res.removedInfo.removedPackage = oldPackage.packageName; 13692 res.removedInfo.isUpdate = true; 13693 final int childCount = (oldPackage.childPackages != null) 13694 ? oldPackage.childPackages.size() : 0; 13695 for (int i = 0; i < childCount; i++) { 13696 boolean childPackageUpdated = false; 13697 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 13698 if (res.addedChildPackages != null) { 13699 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 13700 if (childRes != null) { 13701 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 13702 childRes.removedInfo.removedPackage = childPkg.packageName; 13703 childRes.removedInfo.isUpdate = true; 13704 childPackageUpdated = true; 13705 } 13706 } 13707 if (!childPackageUpdated) { 13708 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 13709 childRemovedRes.removedPackage = childPkg.packageName; 13710 childRemovedRes.isUpdate = false; 13711 childRemovedRes.dataRemoved = true; 13712 synchronized (mPackages) { 13713 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 13714 if (childPs != null) { 13715 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 13716 } 13717 } 13718 if (res.removedInfo.removedChildPackages == null) { 13719 res.removedInfo.removedChildPackages = new ArrayMap<>(); 13720 } 13721 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 13722 } 13723 } 13724 13725 boolean sysPkg = (isSystemApp(oldPackage)); 13726 if (sysPkg) { 13727 replaceSystemPackageLIF(oldPackage, pkg, parseFlags, scanFlags, 13728 user, allUsers, installerPackageName, res); 13729 } else { 13730 replaceNonSystemPackageLIF(oldPackage, pkg, parseFlags, scanFlags, 13731 user, allUsers, installerPackageName, res); 13732 } 13733 } 13734 13735 public List<String> getPreviousCodePaths(String packageName) { 13736 final PackageSetting ps = mSettings.mPackages.get(packageName); 13737 final List<String> result = new ArrayList<String>(); 13738 if (ps != null && ps.oldCodePaths != null) { 13739 result.addAll(ps.oldCodePaths); 13740 } 13741 return result; 13742 } 13743 13744 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 13745 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 13746 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 13747 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 13748 + deletedPackage); 13749 13750 String pkgName = deletedPackage.packageName; 13751 boolean deletedPkg = true; 13752 boolean addedPkg = false; 13753 boolean updatedSettings = false; 13754 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 13755 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 13756 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 13757 13758 final long origUpdateTime = (pkg.mExtras != null) 13759 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 13760 13761 // First delete the existing package while retaining the data directory 13762 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 13763 res.removedInfo, true, pkg)) { 13764 // If the existing package wasn't successfully deleted 13765 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 13766 deletedPkg = false; 13767 } else { 13768 // Successfully deleted the old package; proceed with replace. 13769 13770 // If deleted package lived in a container, give users a chance to 13771 // relinquish resources before killing. 13772 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 13773 if (DEBUG_INSTALL) { 13774 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 13775 } 13776 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 13777 final ArrayList<String> pkgList = new ArrayList<String>(1); 13778 pkgList.add(deletedPackage.applicationInfo.packageName); 13779 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 13780 } 13781 13782 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 13783 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 13784 clearAppProfilesLIF(pkg); 13785 13786 try { 13787 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, 13788 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 13789 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 13790 13791 // Update the in-memory copy of the previous code paths. 13792 PackageSetting ps = mSettings.mPackages.get(pkgName); 13793 if (!killApp) { 13794 if (ps.oldCodePaths == null) { 13795 ps.oldCodePaths = new ArraySet<>(); 13796 } 13797 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 13798 if (deletedPackage.splitCodePaths != null) { 13799 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 13800 } 13801 } else { 13802 ps.oldCodePaths = null; 13803 } 13804 if (ps.childPackageNames != null) { 13805 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 13806 final String childPkgName = ps.childPackageNames.get(i); 13807 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 13808 childPs.oldCodePaths = ps.oldCodePaths; 13809 } 13810 } 13811 prepareAppDataAfterInstallLIF(newPackage); 13812 addedPkg = true; 13813 } catch (PackageManagerException e) { 13814 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13815 } 13816 } 13817 13818 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 13819 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 13820 13821 // Revert all internal state mutations and added folders for the failed install 13822 if (addedPkg) { 13823 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 13824 res.removedInfo, true, null); 13825 } 13826 13827 // Restore the old package 13828 if (deletedPkg) { 13829 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 13830 File restoreFile = new File(deletedPackage.codePath); 13831 // Parse old package 13832 boolean oldExternal = isExternal(deletedPackage); 13833 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 13834 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 13835 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 13836 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 13837 try { 13838 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 13839 null); 13840 } catch (PackageManagerException e) { 13841 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 13842 + e.getMessage()); 13843 return; 13844 } 13845 13846 synchronized (mPackages) { 13847 // Ensure the installer package name up to date 13848 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 13849 13850 // Update permissions for restored package 13851 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 13852 13853 mSettings.writeLPr(); 13854 } 13855 13856 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 13857 } 13858 } else { 13859 synchronized (mPackages) { 13860 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 13861 if (ps != null) { 13862 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 13863 if (res.removedInfo.removedChildPackages != null) { 13864 final int childCount = res.removedInfo.removedChildPackages.size(); 13865 // Iterate in reverse as we may modify the collection 13866 for (int i = childCount - 1; i >= 0; i--) { 13867 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 13868 if (res.addedChildPackages.containsKey(childPackageName)) { 13869 res.removedInfo.removedChildPackages.removeAt(i); 13870 } else { 13871 PackageRemovedInfo childInfo = res.removedInfo 13872 .removedChildPackages.valueAt(i); 13873 childInfo.removedForAllUsers = mPackages.get( 13874 childInfo.removedPackage) == null; 13875 } 13876 } 13877 } 13878 } 13879 } 13880 } 13881 } 13882 13883 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 13884 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 13885 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 13886 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 13887 + ", old=" + deletedPackage); 13888 13889 final boolean disabledSystem; 13890 13891 // Set the system/privileged flags as needed 13892 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 13893 if ((deletedPackage.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 13894 != 0) { 13895 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 13896 } 13897 13898 // Remove existing system package 13899 removePackageLI(deletedPackage, true); 13900 13901 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 13902 if (!disabledSystem) { 13903 // We didn't need to disable the .apk as a current system package, 13904 // which means we are replacing another update that is already 13905 // installed. We need to make sure to delete the older one's .apk. 13906 res.removedInfo.args = createInstallArgsForExisting(0, 13907 deletedPackage.applicationInfo.getCodePath(), 13908 deletedPackage.applicationInfo.getResourcePath(), 13909 getAppDexInstructionSets(deletedPackage.applicationInfo)); 13910 } else { 13911 res.removedInfo.args = null; 13912 } 13913 13914 // Successfully disabled the old package. Now proceed with re-installation 13915 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 13916 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 13917 clearAppProfilesLIF(pkg); 13918 13919 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 13920 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 13921 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 13922 13923 PackageParser.Package newPackage = null; 13924 try { 13925 // Add the package to the internal data structures 13926 newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user); 13927 13928 // Set the update and install times 13929 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 13930 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 13931 System.currentTimeMillis()); 13932 13933 // Update the package dynamic state if succeeded 13934 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13935 // Now that the install succeeded make sure we remove data 13936 // directories for any child package the update removed. 13937 final int deletedChildCount = (deletedPackage.childPackages != null) 13938 ? deletedPackage.childPackages.size() : 0; 13939 final int newChildCount = (newPackage.childPackages != null) 13940 ? newPackage.childPackages.size() : 0; 13941 for (int i = 0; i < deletedChildCount; i++) { 13942 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 13943 boolean childPackageDeleted = true; 13944 for (int j = 0; j < newChildCount; j++) { 13945 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 13946 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 13947 childPackageDeleted = false; 13948 break; 13949 } 13950 } 13951 if (childPackageDeleted) { 13952 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 13953 deletedChildPkg.packageName); 13954 if (ps != null && res.removedInfo.removedChildPackages != null) { 13955 PackageRemovedInfo removedChildRes = res.removedInfo 13956 .removedChildPackages.get(deletedChildPkg.packageName); 13957 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 13958 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 13959 } 13960 } 13961 } 13962 13963 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 13964 prepareAppDataAfterInstallLIF(newPackage); 13965 } 13966 } catch (PackageManagerException e) { 13967 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 13968 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13969 } 13970 13971 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 13972 // Re installation failed. Restore old information 13973 // Remove new pkg information 13974 if (newPackage != null) { 13975 removeInstalledPackageLI(newPackage, true); 13976 } 13977 // Add back the old system package 13978 try { 13979 scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 13980 } catch (PackageManagerException e) { 13981 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 13982 } 13983 13984 synchronized (mPackages) { 13985 if (disabledSystem) { 13986 enableSystemPackageLPw(deletedPackage); 13987 } 13988 13989 // Ensure the installer package name up to date 13990 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 13991 13992 // Update permissions for restored package 13993 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 13994 13995 mSettings.writeLPr(); 13996 } 13997 13998 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 13999 + " after failed upgrade"); 14000 } 14001 } 14002 14003 /** 14004 * Checks whether the parent or any of the child packages have a change shared 14005 * user. For a package to be a valid update the shred users of the parent and 14006 * the children should match. We may later support changing child shared users. 14007 * @param oldPkg The updated package. 14008 * @param newPkg The update package. 14009 * @return The shared user that change between the versions. 14010 */ 14011 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 14012 PackageParser.Package newPkg) { 14013 // Check parent shared user 14014 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 14015 return newPkg.packageName; 14016 } 14017 // Check child shared users 14018 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14019 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 14020 for (int i = 0; i < newChildCount; i++) { 14021 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 14022 // If this child was present, did it have the same shared user? 14023 for (int j = 0; j < oldChildCount; j++) { 14024 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 14025 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 14026 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 14027 return newChildPkg.packageName; 14028 } 14029 } 14030 } 14031 return null; 14032 } 14033 14034 private void removeNativeBinariesLI(PackageSetting ps) { 14035 // Remove the lib path for the parent package 14036 if (ps != null) { 14037 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 14038 // Remove the lib path for the child packages 14039 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 14040 for (int i = 0; i < childCount; i++) { 14041 PackageSetting childPs = null; 14042 synchronized (mPackages) { 14043 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 14044 } 14045 if (childPs != null) { 14046 NativeLibraryHelper.removeNativeBinariesLI(childPs 14047 .legacyNativeLibraryPathString); 14048 } 14049 } 14050 } 14051 } 14052 14053 private void enableSystemPackageLPw(PackageParser.Package pkg) { 14054 // Enable the parent package 14055 mSettings.enableSystemPackageLPw(pkg.packageName); 14056 // Enable the child packages 14057 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14058 for (int i = 0; i < childCount; i++) { 14059 PackageParser.Package childPkg = pkg.childPackages.get(i); 14060 mSettings.enableSystemPackageLPw(childPkg.packageName); 14061 } 14062 } 14063 14064 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 14065 PackageParser.Package newPkg) { 14066 // Disable the parent package (parent always replaced) 14067 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 14068 // Disable the child packages 14069 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14070 for (int i = 0; i < childCount; i++) { 14071 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 14072 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 14073 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 14074 } 14075 return disabled; 14076 } 14077 14078 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 14079 String installerPackageName) { 14080 // Enable the parent package 14081 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 14082 // Enable the child packages 14083 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14084 for (int i = 0; i < childCount; i++) { 14085 PackageParser.Package childPkg = pkg.childPackages.get(i); 14086 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 14087 } 14088 } 14089 14090 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 14091 // Collect all used permissions in the UID 14092 ArraySet<String> usedPermissions = new ArraySet<>(); 14093 final int packageCount = su.packages.size(); 14094 for (int i = 0; i < packageCount; i++) { 14095 PackageSetting ps = su.packages.valueAt(i); 14096 if (ps.pkg == null) { 14097 continue; 14098 } 14099 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 14100 for (int j = 0; j < requestedPermCount; j++) { 14101 String permission = ps.pkg.requestedPermissions.get(j); 14102 BasePermission bp = mSettings.mPermissions.get(permission); 14103 if (bp != null) { 14104 usedPermissions.add(permission); 14105 } 14106 } 14107 } 14108 14109 PermissionsState permissionsState = su.getPermissionsState(); 14110 // Prune install permissions 14111 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 14112 final int installPermCount = installPermStates.size(); 14113 for (int i = installPermCount - 1; i >= 0; i--) { 14114 PermissionState permissionState = installPermStates.get(i); 14115 if (!usedPermissions.contains(permissionState.getName())) { 14116 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14117 if (bp != null) { 14118 permissionsState.revokeInstallPermission(bp); 14119 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 14120 PackageManager.MASK_PERMISSION_FLAGS, 0); 14121 } 14122 } 14123 } 14124 14125 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 14126 14127 // Prune runtime permissions 14128 for (int userId : allUserIds) { 14129 List<PermissionState> runtimePermStates = permissionsState 14130 .getRuntimePermissionStates(userId); 14131 final int runtimePermCount = runtimePermStates.size(); 14132 for (int i = runtimePermCount - 1; i >= 0; i--) { 14133 PermissionState permissionState = runtimePermStates.get(i); 14134 if (!usedPermissions.contains(permissionState.getName())) { 14135 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14136 if (bp != null) { 14137 permissionsState.revokeRuntimePermission(bp, userId); 14138 permissionsState.updatePermissionFlags(bp, userId, 14139 PackageManager.MASK_PERMISSION_FLAGS, 0); 14140 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 14141 runtimePermissionChangedUserIds, userId); 14142 } 14143 } 14144 } 14145 } 14146 14147 return runtimePermissionChangedUserIds; 14148 } 14149 14150 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 14151 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 14152 // Update the parent package setting 14153 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 14154 res, user); 14155 // Update the child packages setting 14156 final int childCount = (newPackage.childPackages != null) 14157 ? newPackage.childPackages.size() : 0; 14158 for (int i = 0; i < childCount; i++) { 14159 PackageParser.Package childPackage = newPackage.childPackages.get(i); 14160 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 14161 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 14162 childRes.origUsers, childRes, user); 14163 } 14164 } 14165 14166 private void updateSettingsInternalLI(PackageParser.Package newPackage, 14167 String installerPackageName, int[] allUsers, int[] installedForUsers, 14168 PackageInstalledInfo res, UserHandle user) { 14169 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 14170 14171 String pkgName = newPackage.packageName; 14172 synchronized (mPackages) { 14173 //write settings. the installStatus will be incomplete at this stage. 14174 //note that the new package setting would have already been 14175 //added to mPackages. It hasn't been persisted yet. 14176 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 14177 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14178 mSettings.writeLPr(); 14179 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14180 } 14181 14182 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 14183 synchronized (mPackages) { 14184 updatePermissionsLPw(newPackage.packageName, newPackage, 14185 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 14186 ? UPDATE_PERMISSIONS_ALL : 0)); 14187 // For system-bundled packages, we assume that installing an upgraded version 14188 // of the package implies that the user actually wants to run that new code, 14189 // so we enable the package. 14190 PackageSetting ps = mSettings.mPackages.get(pkgName); 14191 final int userId = user.getIdentifier(); 14192 if (ps != null) { 14193 if (isSystemApp(newPackage)) { 14194 if (DEBUG_INSTALL) { 14195 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 14196 } 14197 // Enable system package for requested users 14198 if (res.origUsers != null) { 14199 for (int origUserId : res.origUsers) { 14200 if (userId == UserHandle.USER_ALL || userId == origUserId) { 14201 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 14202 origUserId, installerPackageName); 14203 } 14204 } 14205 } 14206 // Also convey the prior install/uninstall state 14207 if (allUsers != null && installedForUsers != null) { 14208 for (int currentUserId : allUsers) { 14209 final boolean installed = ArrayUtils.contains( 14210 installedForUsers, currentUserId); 14211 if (DEBUG_INSTALL) { 14212 Slog.d(TAG, " user " + currentUserId + " => " + installed); 14213 } 14214 ps.setInstalled(installed, currentUserId); 14215 } 14216 // these install state changes will be persisted in the 14217 // upcoming call to mSettings.writeLPr(). 14218 } 14219 } 14220 // It's implied that when a user requests installation, they want the app to be 14221 // installed and enabled. 14222 if (userId != UserHandle.USER_ALL) { 14223 ps.setInstalled(true, userId); 14224 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 14225 } 14226 } 14227 res.name = pkgName; 14228 res.uid = newPackage.applicationInfo.uid; 14229 res.pkg = newPackage; 14230 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 14231 mSettings.setInstallerPackageName(pkgName, installerPackageName); 14232 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14233 //to update install status 14234 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14235 mSettings.writeLPr(); 14236 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14237 } 14238 14239 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14240 } 14241 14242 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 14243 try { 14244 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 14245 installPackageLI(args, res); 14246 } finally { 14247 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14248 } 14249 } 14250 14251 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 14252 final int installFlags = args.installFlags; 14253 final String installerPackageName = args.installerPackageName; 14254 final String volumeUuid = args.volumeUuid; 14255 final File tmpPackageFile = new File(args.getCodePath()); 14256 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 14257 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 14258 || (args.volumeUuid != null)); 14259 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 14260 boolean replace = false; 14261 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 14262 if (args.move != null) { 14263 // moving a complete application; perform an initial scan on the new install location 14264 scanFlags |= SCAN_INITIAL; 14265 } 14266 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 14267 scanFlags |= SCAN_DONT_KILL_APP; 14268 } 14269 14270 // Result object to be returned 14271 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14272 14273 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 14274 14275 // Sanity check 14276 if (ephemeral && (forwardLocked || onExternal)) { 14277 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 14278 + " external=" + onExternal); 14279 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14280 return; 14281 } 14282 14283 // Retrieve PackageSettings and parse package 14284 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 14285 | PackageParser.PARSE_ENFORCE_CODE 14286 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 14287 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 14288 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0); 14289 PackageParser pp = new PackageParser(); 14290 pp.setSeparateProcesses(mSeparateProcesses); 14291 pp.setDisplayMetrics(mMetrics); 14292 14293 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 14294 final PackageParser.Package pkg; 14295 try { 14296 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 14297 } catch (PackageParserException e) { 14298 res.setError("Failed parse during installPackageLI", e); 14299 return; 14300 } finally { 14301 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14302 } 14303 14304 // If we are installing a clustered package add results for the children 14305 if (pkg.childPackages != null) { 14306 synchronized (mPackages) { 14307 final int childCount = pkg.childPackages.size(); 14308 for (int i = 0; i < childCount; i++) { 14309 PackageParser.Package childPkg = pkg.childPackages.get(i); 14310 PackageInstalledInfo childRes = new PackageInstalledInfo(); 14311 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14312 childRes.pkg = childPkg; 14313 childRes.name = childPkg.packageName; 14314 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14315 if (childPs != null) { 14316 childRes.origUsers = childPs.queryInstalledUsers( 14317 sUserManager.getUserIds(), true); 14318 } 14319 if ((mPackages.containsKey(childPkg.packageName))) { 14320 childRes.removedInfo = new PackageRemovedInfo(); 14321 childRes.removedInfo.removedPackage = childPkg.packageName; 14322 } 14323 if (res.addedChildPackages == null) { 14324 res.addedChildPackages = new ArrayMap<>(); 14325 } 14326 res.addedChildPackages.put(childPkg.packageName, childRes); 14327 } 14328 } 14329 } 14330 14331 // If package doesn't declare API override, mark that we have an install 14332 // time CPU ABI override. 14333 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 14334 pkg.cpuAbiOverride = args.abiOverride; 14335 } 14336 14337 String pkgName = res.name = pkg.packageName; 14338 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 14339 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 14340 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 14341 return; 14342 } 14343 } 14344 14345 try { 14346 // either use what we've been given or parse directly from the APK 14347 if (args.certificates != null) { 14348 try { 14349 PackageParser.populateCertificates(pkg, args.certificates); 14350 } catch (PackageParserException e) { 14351 // there was something wrong with the certificates we were given; 14352 // try to pull them from the APK 14353 PackageParser.collectCertificates(pkg, parseFlags); 14354 } 14355 } else { 14356 PackageParser.collectCertificates(pkg, parseFlags); 14357 } 14358 } catch (PackageParserException e) { 14359 res.setError("Failed collect during installPackageLI", e); 14360 return; 14361 } 14362 14363 // Get rid of all references to package scan path via parser. 14364 pp = null; 14365 String oldCodePath = null; 14366 boolean systemApp = false; 14367 synchronized (mPackages) { 14368 // Check if installing already existing package 14369 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14370 String oldName = mSettings.mRenamedPackages.get(pkgName); 14371 if (pkg.mOriginalPackages != null 14372 && pkg.mOriginalPackages.contains(oldName) 14373 && mPackages.containsKey(oldName)) { 14374 // This package is derived from an original package, 14375 // and this device has been updating from that original 14376 // name. We must continue using the original name, so 14377 // rename the new package here. 14378 pkg.setPackageName(oldName); 14379 pkgName = pkg.packageName; 14380 replace = true; 14381 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 14382 + oldName + " pkgName=" + pkgName); 14383 } else if (mPackages.containsKey(pkgName)) { 14384 // This package, under its official name, already exists 14385 // on the device; we should replace it. 14386 replace = true; 14387 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 14388 } 14389 14390 // Child packages are installed through the parent package 14391 if (pkg.parentPackage != null) { 14392 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14393 "Package " + pkg.packageName + " is child of package " 14394 + pkg.parentPackage.parentPackage + ". Child packages " 14395 + "can be updated only through the parent package."); 14396 return; 14397 } 14398 14399 if (replace) { 14400 // Prevent apps opting out from runtime permissions 14401 PackageParser.Package oldPackage = mPackages.get(pkgName); 14402 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 14403 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 14404 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 14405 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 14406 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 14407 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 14408 + " doesn't support runtime permissions but the old" 14409 + " target SDK " + oldTargetSdk + " does."); 14410 return; 14411 } 14412 14413 // Prevent installing of child packages 14414 if (oldPackage.parentPackage != null) { 14415 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14416 "Package " + pkg.packageName + " is child of package " 14417 + oldPackage.parentPackage + ". Child packages " 14418 + "can be updated only through the parent package."); 14419 return; 14420 } 14421 } 14422 } 14423 14424 PackageSetting ps = mSettings.mPackages.get(pkgName); 14425 if (ps != null) { 14426 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 14427 14428 // Quick sanity check that we're signed correctly if updating; 14429 // we'll check this again later when scanning, but we want to 14430 // bail early here before tripping over redefined permissions. 14431 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14432 if (!checkUpgradeKeySetLP(ps, pkg)) { 14433 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 14434 + pkg.packageName + " upgrade keys do not match the " 14435 + "previously installed version"); 14436 return; 14437 } 14438 } else { 14439 try { 14440 verifySignaturesLP(ps, pkg); 14441 } catch (PackageManagerException e) { 14442 res.setError(e.error, e.getMessage()); 14443 return; 14444 } 14445 } 14446 14447 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 14448 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 14449 systemApp = (ps.pkg.applicationInfo.flags & 14450 ApplicationInfo.FLAG_SYSTEM) != 0; 14451 } 14452 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14453 } 14454 14455 // Check whether the newly-scanned package wants to define an already-defined perm 14456 int N = pkg.permissions.size(); 14457 for (int i = N-1; i >= 0; i--) { 14458 PackageParser.Permission perm = pkg.permissions.get(i); 14459 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 14460 if (bp != null) { 14461 // If the defining package is signed with our cert, it's okay. This 14462 // also includes the "updating the same package" case, of course. 14463 // "updating same package" could also involve key-rotation. 14464 final boolean sigsOk; 14465 if (bp.sourcePackage.equals(pkg.packageName) 14466 && (bp.packageSetting instanceof PackageSetting) 14467 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 14468 scanFlags))) { 14469 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 14470 } else { 14471 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 14472 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 14473 } 14474 if (!sigsOk) { 14475 // If the owning package is the system itself, we log but allow 14476 // install to proceed; we fail the install on all other permission 14477 // redefinitions. 14478 if (!bp.sourcePackage.equals("android")) { 14479 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 14480 + pkg.packageName + " attempting to redeclare permission " 14481 + perm.info.name + " already owned by " + bp.sourcePackage); 14482 res.origPermission = perm.info.name; 14483 res.origPackage = bp.sourcePackage; 14484 return; 14485 } else { 14486 Slog.w(TAG, "Package " + pkg.packageName 14487 + " attempting to redeclare system permission " 14488 + perm.info.name + "; ignoring new declaration"); 14489 pkg.permissions.remove(i); 14490 } 14491 } 14492 } 14493 } 14494 } 14495 14496 if (systemApp) { 14497 if (onExternal) { 14498 // Abort update; system app can't be replaced with app on sdcard 14499 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 14500 "Cannot install updates to system apps on sdcard"); 14501 return; 14502 } else if (ephemeral) { 14503 // Abort update; system app can't be replaced with an ephemeral app 14504 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 14505 "Cannot update a system app with an ephemeral app"); 14506 return; 14507 } 14508 } 14509 14510 if (args.move != null) { 14511 // We did an in-place move, so dex is ready to roll 14512 scanFlags |= SCAN_NO_DEX; 14513 scanFlags |= SCAN_MOVE; 14514 14515 synchronized (mPackages) { 14516 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14517 if (ps == null) { 14518 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 14519 "Missing settings for moved package " + pkgName); 14520 } 14521 14522 // We moved the entire application as-is, so bring over the 14523 // previously derived ABI information. 14524 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 14525 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 14526 } 14527 14528 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 14529 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 14530 scanFlags |= SCAN_NO_DEX; 14531 14532 try { 14533 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 14534 args.abiOverride : pkg.cpuAbiOverride); 14535 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 14536 true /* extract libs */); 14537 } catch (PackageManagerException pme) { 14538 Slog.e(TAG, "Error deriving application ABI", pme); 14539 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 14540 return; 14541 } 14542 14543 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 14544 // Do not run PackageDexOptimizer through the local performDexOpt 14545 // method because `pkg` is not in `mPackages` yet. 14546 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instructionSets */, 14547 false /* checkProfiles */, getCompilerFilterForReason(REASON_INSTALL)); 14548 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14549 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 14550 String msg = "Extracting package failed for " + pkgName; 14551 res.setError(INSTALL_FAILED_DEXOPT, msg); 14552 return; 14553 } 14554 14555 // Notify BackgroundDexOptService that the package has been changed. 14556 // If this is an update of a package which used to fail to compile, 14557 // BDOS will remove it from its blacklist. 14558 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 14559 } 14560 14561 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 14562 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 14563 return; 14564 } 14565 14566 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 14567 14568 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 14569 "installPackageLI")) { 14570 if (replace) { 14571 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 14572 installerPackageName, res); 14573 } else { 14574 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 14575 args.user, installerPackageName, volumeUuid, res); 14576 } 14577 } 14578 synchronized (mPackages) { 14579 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14580 if (ps != null) { 14581 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14582 } 14583 14584 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14585 for (int i = 0; i < childCount; i++) { 14586 PackageParser.Package childPkg = pkg.childPackages.get(i); 14587 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14588 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14589 if (childPs != null) { 14590 childRes.newUsers = childPs.queryInstalledUsers( 14591 sUserManager.getUserIds(), true); 14592 } 14593 } 14594 } 14595 } 14596 14597 private void startIntentFilterVerifications(int userId, boolean replacing, 14598 PackageParser.Package pkg) { 14599 if (mIntentFilterVerifierComponent == null) { 14600 Slog.w(TAG, "No IntentFilter verification will not be done as " 14601 + "there is no IntentFilterVerifier available!"); 14602 return; 14603 } 14604 14605 final int verifierUid = getPackageUid( 14606 mIntentFilterVerifierComponent.getPackageName(), 14607 MATCH_DEBUG_TRIAGED_MISSING, 14608 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 14609 14610 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14611 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 14612 mHandler.sendMessage(msg); 14613 14614 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14615 for (int i = 0; i < childCount; i++) { 14616 PackageParser.Package childPkg = pkg.childPackages.get(i); 14617 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14618 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 14619 mHandler.sendMessage(msg); 14620 } 14621 } 14622 14623 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 14624 PackageParser.Package pkg) { 14625 int size = pkg.activities.size(); 14626 if (size == 0) { 14627 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14628 "No activity, so no need to verify any IntentFilter!"); 14629 return; 14630 } 14631 14632 final boolean hasDomainURLs = hasDomainURLs(pkg); 14633 if (!hasDomainURLs) { 14634 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14635 "No domain URLs, so no need to verify any IntentFilter!"); 14636 return; 14637 } 14638 14639 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 14640 + " if any IntentFilter from the " + size 14641 + " Activities needs verification ..."); 14642 14643 int count = 0; 14644 final String packageName = pkg.packageName; 14645 14646 synchronized (mPackages) { 14647 // If this is a new install and we see that we've already run verification for this 14648 // package, we have nothing to do: it means the state was restored from backup. 14649 if (!replacing) { 14650 IntentFilterVerificationInfo ivi = 14651 mSettings.getIntentFilterVerificationLPr(packageName); 14652 if (ivi != null) { 14653 if (DEBUG_DOMAIN_VERIFICATION) { 14654 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 14655 + ivi.getStatusString()); 14656 } 14657 return; 14658 } 14659 } 14660 14661 // If any filters need to be verified, then all need to be. 14662 boolean needToVerify = false; 14663 for (PackageParser.Activity a : pkg.activities) { 14664 for (ActivityIntentInfo filter : a.intents) { 14665 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 14666 if (DEBUG_DOMAIN_VERIFICATION) { 14667 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 14668 } 14669 needToVerify = true; 14670 break; 14671 } 14672 } 14673 } 14674 14675 if (needToVerify) { 14676 final int verificationId = mIntentFilterVerificationToken++; 14677 for (PackageParser.Activity a : pkg.activities) { 14678 for (ActivityIntentInfo filter : a.intents) { 14679 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 14680 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14681 "Verification needed for IntentFilter:" + filter.toString()); 14682 mIntentFilterVerifier.addOneIntentFilterVerification( 14683 verifierUid, userId, verificationId, filter, packageName); 14684 count++; 14685 } 14686 } 14687 } 14688 } 14689 } 14690 14691 if (count > 0) { 14692 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 14693 + " IntentFilter verification" + (count > 1 ? "s" : "") 14694 + " for userId:" + userId); 14695 mIntentFilterVerifier.startVerifications(userId); 14696 } else { 14697 if (DEBUG_DOMAIN_VERIFICATION) { 14698 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 14699 } 14700 } 14701 } 14702 14703 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 14704 final ComponentName cn = filter.activity.getComponentName(); 14705 final String packageName = cn.getPackageName(); 14706 14707 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 14708 packageName); 14709 if (ivi == null) { 14710 return true; 14711 } 14712 int status = ivi.getStatus(); 14713 switch (status) { 14714 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 14715 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 14716 return true; 14717 14718 default: 14719 // Nothing to do 14720 return false; 14721 } 14722 } 14723 14724 private static boolean isMultiArch(ApplicationInfo info) { 14725 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 14726 } 14727 14728 private static boolean isExternal(PackageParser.Package pkg) { 14729 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 14730 } 14731 14732 private static boolean isExternal(PackageSetting ps) { 14733 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 14734 } 14735 14736 private static boolean isEphemeral(PackageParser.Package pkg) { 14737 return pkg.applicationInfo.isEphemeralApp(); 14738 } 14739 14740 private static boolean isEphemeral(PackageSetting ps) { 14741 return ps.pkg != null && isEphemeral(ps.pkg); 14742 } 14743 14744 private static boolean isSystemApp(PackageParser.Package pkg) { 14745 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 14746 } 14747 14748 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 14749 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14750 } 14751 14752 private static boolean hasDomainURLs(PackageParser.Package pkg) { 14753 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 14754 } 14755 14756 private static boolean isSystemApp(PackageSetting ps) { 14757 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 14758 } 14759 14760 private static boolean isUpdatedSystemApp(PackageSetting ps) { 14761 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 14762 } 14763 14764 private int packageFlagsToInstallFlags(PackageSetting ps) { 14765 int installFlags = 0; 14766 if (isEphemeral(ps)) { 14767 installFlags |= PackageManager.INSTALL_EPHEMERAL; 14768 } 14769 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 14770 // This existing package was an external ASEC install when we have 14771 // the external flag without a UUID 14772 installFlags |= PackageManager.INSTALL_EXTERNAL; 14773 } 14774 if (ps.isForwardLocked()) { 14775 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 14776 } 14777 return installFlags; 14778 } 14779 14780 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 14781 if (isExternal(pkg)) { 14782 if (TextUtils.isEmpty(pkg.volumeUuid)) { 14783 return StorageManager.UUID_PRIMARY_PHYSICAL; 14784 } else { 14785 return pkg.volumeUuid; 14786 } 14787 } else { 14788 return StorageManager.UUID_PRIVATE_INTERNAL; 14789 } 14790 } 14791 14792 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 14793 if (isExternal(pkg)) { 14794 if (TextUtils.isEmpty(pkg.volumeUuid)) { 14795 return mSettings.getExternalVersion(); 14796 } else { 14797 return mSettings.findOrCreateVersion(pkg.volumeUuid); 14798 } 14799 } else { 14800 return mSettings.getInternalVersion(); 14801 } 14802 } 14803 14804 private void deleteTempPackageFiles() { 14805 final FilenameFilter filter = new FilenameFilter() { 14806 public boolean accept(File dir, String name) { 14807 return name.startsWith("vmdl") && name.endsWith(".tmp"); 14808 } 14809 }; 14810 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 14811 file.delete(); 14812 } 14813 } 14814 14815 @Override 14816 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 14817 int flags) { 14818 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 14819 flags); 14820 } 14821 14822 @Override 14823 public void deletePackage(final String packageName, 14824 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 14825 mContext.enforceCallingOrSelfPermission( 14826 android.Manifest.permission.DELETE_PACKAGES, null); 14827 Preconditions.checkNotNull(packageName); 14828 Preconditions.checkNotNull(observer); 14829 final int uid = Binder.getCallingUid(); 14830 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 14831 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 14832 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 14833 mContext.enforceCallingOrSelfPermission( 14834 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 14835 "deletePackage for user " + userId); 14836 } 14837 14838 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 14839 try { 14840 observer.onPackageDeleted(packageName, 14841 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 14842 } catch (RemoteException re) { 14843 } 14844 return; 14845 } 14846 14847 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 14848 try { 14849 observer.onPackageDeleted(packageName, 14850 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 14851 } catch (RemoteException re) { 14852 } 14853 return; 14854 } 14855 14856 if (DEBUG_REMOVE) { 14857 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 14858 + " deleteAllUsers: " + deleteAllUsers ); 14859 } 14860 // Queue up an async operation since the package deletion may take a little while. 14861 mHandler.post(new Runnable() { 14862 public void run() { 14863 mHandler.removeCallbacks(this); 14864 int returnCode; 14865 if (!deleteAllUsers) { 14866 returnCode = deletePackageX(packageName, userId, deleteFlags); 14867 } else { 14868 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 14869 // If nobody is blocking uninstall, proceed with delete for all users 14870 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 14871 returnCode = deletePackageX(packageName, userId, deleteFlags); 14872 } else { 14873 // Otherwise uninstall individually for users with blockUninstalls=false 14874 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 14875 for (int userId : users) { 14876 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 14877 returnCode = deletePackageX(packageName, userId, userFlags); 14878 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 14879 Slog.w(TAG, "Package delete failed for user " + userId 14880 + ", returnCode " + returnCode); 14881 } 14882 } 14883 } 14884 // The app has only been marked uninstalled for certain users. 14885 // We still need to report that delete was blocked 14886 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 14887 } 14888 } 14889 try { 14890 observer.onPackageDeleted(packageName, returnCode, null); 14891 } catch (RemoteException e) { 14892 Log.i(TAG, "Observer no longer exists."); 14893 } //end catch 14894 } //end run 14895 }); 14896 } 14897 14898 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 14899 int[] result = EMPTY_INT_ARRAY; 14900 for (int userId : userIds) { 14901 if (getBlockUninstallForUser(packageName, userId)) { 14902 result = ArrayUtils.appendInt(result, userId); 14903 } 14904 } 14905 return result; 14906 } 14907 14908 @Override 14909 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 14910 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 14911 } 14912 14913 private boolean isPackageDeviceAdmin(String packageName, int userId) { 14914 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 14915 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 14916 try { 14917 if (dpm != null) { 14918 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 14919 /* callingUserOnly =*/ false); 14920 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 14921 : deviceOwnerComponentName.getPackageName(); 14922 // Does the package contains the device owner? 14923 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 14924 // this check is probably not needed, since DO should be registered as a device 14925 // admin on some user too. (Original bug for this: b/17657954) 14926 if (packageName.equals(deviceOwnerPackageName)) { 14927 return true; 14928 } 14929 // Does it contain a device admin for any user? 14930 int[] users; 14931 if (userId == UserHandle.USER_ALL) { 14932 users = sUserManager.getUserIds(); 14933 } else { 14934 users = new int[]{userId}; 14935 } 14936 for (int i = 0; i < users.length; ++i) { 14937 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 14938 return true; 14939 } 14940 } 14941 } 14942 } catch (RemoteException e) { 14943 } 14944 return false; 14945 } 14946 14947 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 14948 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 14949 } 14950 14951 /** 14952 * This method is an internal method that could be get invoked either 14953 * to delete an installed package or to clean up a failed installation. 14954 * After deleting an installed package, a broadcast is sent to notify any 14955 * listeners that the package has been removed. For cleaning up a failed 14956 * installation, the broadcast is not necessary since the package's 14957 * installation wouldn't have sent the initial broadcast either 14958 * The key steps in deleting a package are 14959 * deleting the package information in internal structures like mPackages, 14960 * deleting the packages base directories through installd 14961 * updating mSettings to reflect current status 14962 * persisting settings for later use 14963 * sending a broadcast if necessary 14964 */ 14965 private int deletePackageX(String packageName, int userId, int deleteFlags) { 14966 final PackageRemovedInfo info = new PackageRemovedInfo(); 14967 final boolean res; 14968 14969 final UserHandle removeForUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 14970 ? UserHandle.ALL : new UserHandle(userId); 14971 14972 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 14973 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 14974 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 14975 } 14976 14977 PackageSetting uninstalledPs = null; 14978 14979 // for the uninstall-updates case and restricted profiles, remember the per- 14980 // user handle installed state 14981 int[] allUsers; 14982 synchronized (mPackages) { 14983 uninstalledPs = mSettings.mPackages.get(packageName); 14984 if (uninstalledPs == null) { 14985 Slog.w(TAG, "Not removing non-existent package " + packageName); 14986 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 14987 } 14988 allUsers = sUserManager.getUserIds(); 14989 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 14990 } 14991 14992 synchronized (mInstallLock) { 14993 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 14994 try (PackageFreezer freezer = freezePackageForDelete(packageName, deleteFlags, 14995 "deletePackageX")) { 14996 res = deletePackageLIF(packageName, removeForUser, true, allUsers, 14997 deleteFlags | REMOVE_CHATTY, info, true, null); 14998 } 14999 synchronized (mPackages) { 15000 if (res) { 15001 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 15002 } 15003 } 15004 } 15005 15006 if (res) { 15007 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 15008 info.sendPackageRemovedBroadcasts(killApp); 15009 info.sendSystemPackageUpdatedBroadcasts(); 15010 info.sendSystemPackageAppearedBroadcasts(); 15011 } 15012 // Force a gc here. 15013 Runtime.getRuntime().gc(); 15014 // Delete the resources here after sending the broadcast to let 15015 // other processes clean up before deleting resources. 15016 if (info.args != null) { 15017 synchronized (mInstallLock) { 15018 info.args.doPostDeleteLI(true); 15019 } 15020 } 15021 15022 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15023 } 15024 15025 class PackageRemovedInfo { 15026 String removedPackage; 15027 int uid = -1; 15028 int removedAppId = -1; 15029 int[] origUsers; 15030 int[] removedUsers = null; 15031 boolean isRemovedPackageSystemUpdate = false; 15032 boolean isUpdate; 15033 boolean dataRemoved; 15034 boolean removedForAllUsers; 15035 // Clean up resources deleted packages. 15036 InstallArgs args = null; 15037 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 15038 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 15039 15040 void sendPackageRemovedBroadcasts(boolean killApp) { 15041 sendPackageRemovedBroadcastInternal(killApp); 15042 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 15043 for (int i = 0; i < childCount; i++) { 15044 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15045 childInfo.sendPackageRemovedBroadcastInternal(killApp); 15046 } 15047 } 15048 15049 void sendSystemPackageUpdatedBroadcasts() { 15050 if (isRemovedPackageSystemUpdate) { 15051 sendSystemPackageUpdatedBroadcastsInternal(); 15052 final int childCount = (removedChildPackages != null) 15053 ? removedChildPackages.size() : 0; 15054 for (int i = 0; i < childCount; i++) { 15055 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15056 if (childInfo.isRemovedPackageSystemUpdate) { 15057 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 15058 } 15059 } 15060 } 15061 } 15062 15063 void sendSystemPackageAppearedBroadcasts() { 15064 final int packageCount = (appearedChildPackages != null) 15065 ? appearedChildPackages.size() : 0; 15066 for (int i = 0; i < packageCount; i++) { 15067 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 15068 for (int userId : installedInfo.newUsers) { 15069 sendPackageAddedForUser(installedInfo.name, true, 15070 UserHandle.getAppId(installedInfo.uid), userId); 15071 } 15072 } 15073 } 15074 15075 private void sendSystemPackageUpdatedBroadcastsInternal() { 15076 Bundle extras = new Bundle(2); 15077 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15078 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15079 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 15080 extras, 0, null, null, null); 15081 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 15082 extras, 0, null, null, null); 15083 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 15084 null, 0, removedPackage, null, null); 15085 } 15086 15087 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 15088 Bundle extras = new Bundle(2); 15089 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15090 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 15091 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 15092 if (isUpdate || isRemovedPackageSystemUpdate) { 15093 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15094 } 15095 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 15096 if (removedPackage != null) { 15097 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 15098 extras, 0, null, null, removedUsers); 15099 if (dataRemoved && !isRemovedPackageSystemUpdate) { 15100 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 15101 removedPackage, extras, 0, null, null, removedUsers); 15102 } 15103 } 15104 if (removedAppId >= 0) { 15105 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 15106 removedUsers); 15107 } 15108 } 15109 } 15110 15111 /* 15112 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 15113 * flag is not set, the data directory is removed as well. 15114 * make sure this flag is set for partially installed apps. If not its meaningless to 15115 * delete a partially installed application. 15116 */ 15117 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 15118 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 15119 String packageName = ps.name; 15120 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 15121 // Retrieve object to delete permissions for shared user later on 15122 final PackageParser.Package deletedPkg; 15123 final PackageSetting deletedPs; 15124 // reader 15125 synchronized (mPackages) { 15126 deletedPkg = mPackages.get(packageName); 15127 deletedPs = mSettings.mPackages.get(packageName); 15128 if (outInfo != null) { 15129 outInfo.removedPackage = packageName; 15130 outInfo.removedUsers = deletedPs != null 15131 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 15132 : null; 15133 } 15134 } 15135 15136 removePackageLI(ps, (flags & REMOVE_CHATTY) != 0); 15137 15138 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 15139 destroyAppDataLIF(deletedPkg, UserHandle.USER_ALL, 15140 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15141 destroyAppProfilesLIF(deletedPkg); 15142 if (outInfo != null) { 15143 outInfo.dataRemoved = true; 15144 } 15145 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 15146 } 15147 15148 // writer 15149 synchronized (mPackages) { 15150 if (deletedPs != null) { 15151 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 15152 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 15153 clearDefaultBrowserIfNeeded(packageName); 15154 if (outInfo != null) { 15155 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 15156 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 15157 } 15158 updatePermissionsLPw(deletedPs.name, null, 0); 15159 if (deletedPs.sharedUser != null) { 15160 // Remove permissions associated with package. Since runtime 15161 // permissions are per user we have to kill the removed package 15162 // or packages running under the shared user of the removed 15163 // package if revoking the permissions requested only by the removed 15164 // package is successful and this causes a change in gids. 15165 for (int userId : UserManagerService.getInstance().getUserIds()) { 15166 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 15167 userId); 15168 if (userIdToKill == UserHandle.USER_ALL 15169 || userIdToKill >= UserHandle.USER_SYSTEM) { 15170 // If gids changed for this user, kill all affected packages. 15171 mHandler.post(new Runnable() { 15172 @Override 15173 public void run() { 15174 // This has to happen with no lock held. 15175 killApplication(deletedPs.name, deletedPs.appId, 15176 KILL_APP_REASON_GIDS_CHANGED); 15177 } 15178 }); 15179 break; 15180 } 15181 } 15182 } 15183 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 15184 } 15185 // make sure to preserve per-user disabled state if this removal was just 15186 // a downgrade of a system app to the factory package 15187 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 15188 if (DEBUG_REMOVE) { 15189 Slog.d(TAG, "Propagating install state across downgrade"); 15190 } 15191 for (int userId : allUserHandles) { 15192 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15193 if (DEBUG_REMOVE) { 15194 Slog.d(TAG, " user " + userId + " => " + installed); 15195 } 15196 ps.setInstalled(installed, userId); 15197 } 15198 } 15199 } 15200 // can downgrade to reader 15201 if (writeSettings) { 15202 // Save settings now 15203 mSettings.writeLPr(); 15204 } 15205 } 15206 if (outInfo != null) { 15207 // A user ID was deleted here. Go through all users and remove it 15208 // from KeyStore. 15209 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 15210 } 15211 } 15212 15213 static boolean locationIsPrivileged(File path) { 15214 try { 15215 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 15216 .getCanonicalPath(); 15217 return path.getCanonicalPath().startsWith(privilegedAppDir); 15218 } catch (IOException e) { 15219 Slog.e(TAG, "Unable to access code path " + path); 15220 } 15221 return false; 15222 } 15223 15224 /* 15225 * Tries to delete system package. 15226 */ 15227 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 15228 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 15229 boolean writeSettings) { 15230 if (deletedPs.parentPackageName != null) { 15231 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 15232 return false; 15233 } 15234 15235 final boolean applyUserRestrictions 15236 = (allUserHandles != null) && (outInfo.origUsers != null); 15237 final PackageSetting disabledPs; 15238 // Confirm if the system package has been updated 15239 // An updated system app can be deleted. This will also have to restore 15240 // the system pkg from system partition 15241 // reader 15242 synchronized (mPackages) { 15243 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 15244 } 15245 15246 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 15247 + " disabledPs=" + disabledPs); 15248 15249 if (disabledPs == null) { 15250 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 15251 return false; 15252 } else if (DEBUG_REMOVE) { 15253 Slog.d(TAG, "Deleting system pkg from data partition"); 15254 } 15255 15256 if (DEBUG_REMOVE) { 15257 if (applyUserRestrictions) { 15258 Slog.d(TAG, "Remembering install states:"); 15259 for (int userId : allUserHandles) { 15260 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 15261 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 15262 } 15263 } 15264 } 15265 15266 // Delete the updated package 15267 outInfo.isRemovedPackageSystemUpdate = true; 15268 if (outInfo.removedChildPackages != null) { 15269 final int childCount = (deletedPs.childPackageNames != null) 15270 ? deletedPs.childPackageNames.size() : 0; 15271 for (int i = 0; i < childCount; i++) { 15272 String childPackageName = deletedPs.childPackageNames.get(i); 15273 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 15274 .contains(childPackageName)) { 15275 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15276 childPackageName); 15277 if (childInfo != null) { 15278 childInfo.isRemovedPackageSystemUpdate = true; 15279 } 15280 } 15281 } 15282 } 15283 15284 if (disabledPs.versionCode < deletedPs.versionCode) { 15285 // Delete data for downgrades 15286 flags &= ~PackageManager.DELETE_KEEP_DATA; 15287 } else { 15288 // Preserve data by setting flag 15289 flags |= PackageManager.DELETE_KEEP_DATA; 15290 } 15291 15292 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 15293 outInfo, writeSettings, disabledPs.pkg); 15294 if (!ret) { 15295 return false; 15296 } 15297 15298 // writer 15299 synchronized (mPackages) { 15300 // Reinstate the old system package 15301 enableSystemPackageLPw(disabledPs.pkg); 15302 // Remove any native libraries from the upgraded package. 15303 removeNativeBinariesLI(deletedPs); 15304 } 15305 15306 // Install the system package 15307 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 15308 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 15309 if (locationIsPrivileged(disabledPs.codePath)) { 15310 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 15311 } 15312 15313 final PackageParser.Package newPkg; 15314 try { 15315 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 15316 } catch (PackageManagerException e) { 15317 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 15318 + e.getMessage()); 15319 return false; 15320 } 15321 15322 prepareAppDataAfterInstallLIF(newPkg); 15323 15324 // writer 15325 synchronized (mPackages) { 15326 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 15327 15328 // Propagate the permissions state as we do not want to drop on the floor 15329 // runtime permissions. The update permissions method below will take 15330 // care of removing obsolete permissions and grant install permissions. 15331 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 15332 updatePermissionsLPw(newPkg.packageName, newPkg, 15333 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 15334 15335 if (applyUserRestrictions) { 15336 if (DEBUG_REMOVE) { 15337 Slog.d(TAG, "Propagating install state across reinstall"); 15338 } 15339 for (int userId : allUserHandles) { 15340 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15341 if (DEBUG_REMOVE) { 15342 Slog.d(TAG, " user " + userId + " => " + installed); 15343 } 15344 ps.setInstalled(installed, userId); 15345 15346 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 15347 } 15348 // Regardless of writeSettings we need to ensure that this restriction 15349 // state propagation is persisted 15350 mSettings.writeAllUsersPackageRestrictionsLPr(); 15351 } 15352 // can downgrade to reader here 15353 if (writeSettings) { 15354 mSettings.writeLPr(); 15355 } 15356 } 15357 return true; 15358 } 15359 15360 private boolean deleteInstalledPackageLIF(PackageSetting ps, 15361 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 15362 PackageRemovedInfo outInfo, boolean writeSettings, 15363 PackageParser.Package replacingPackage) { 15364 synchronized (mPackages) { 15365 if (outInfo != null) { 15366 outInfo.uid = ps.appId; 15367 } 15368 15369 if (outInfo != null && outInfo.removedChildPackages != null) { 15370 final int childCount = (ps.childPackageNames != null) 15371 ? ps.childPackageNames.size() : 0; 15372 for (int i = 0; i < childCount; i++) { 15373 String childPackageName = ps.childPackageNames.get(i); 15374 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 15375 if (childPs == null) { 15376 return false; 15377 } 15378 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15379 childPackageName); 15380 if (childInfo != null) { 15381 childInfo.uid = childPs.appId; 15382 } 15383 } 15384 } 15385 } 15386 15387 // Delete package data from internal structures and also remove data if flag is set 15388 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 15389 15390 // Delete the child packages data 15391 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 15392 for (int i = 0; i < childCount; i++) { 15393 PackageSetting childPs; 15394 synchronized (mPackages) { 15395 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 15396 } 15397 if (childPs != null) { 15398 PackageRemovedInfo childOutInfo = (outInfo != null 15399 && outInfo.removedChildPackages != null) 15400 ? outInfo.removedChildPackages.get(childPs.name) : null; 15401 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 15402 && (replacingPackage != null 15403 && !replacingPackage.hasChildPackage(childPs.name)) 15404 ? flags & ~DELETE_KEEP_DATA : flags; 15405 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 15406 deleteFlags, writeSettings); 15407 } 15408 } 15409 15410 // Delete application code and resources only for parent packages 15411 if (ps.parentPackageName == null) { 15412 if (deleteCodeAndResources && (outInfo != null)) { 15413 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 15414 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 15415 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 15416 } 15417 } 15418 15419 return true; 15420 } 15421 15422 @Override 15423 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 15424 int userId) { 15425 mContext.enforceCallingOrSelfPermission( 15426 android.Manifest.permission.DELETE_PACKAGES, null); 15427 synchronized (mPackages) { 15428 PackageSetting ps = mSettings.mPackages.get(packageName); 15429 if (ps == null) { 15430 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 15431 return false; 15432 } 15433 if (!ps.getInstalled(userId)) { 15434 // Can't block uninstall for an app that is not installed or enabled. 15435 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 15436 return false; 15437 } 15438 ps.setBlockUninstall(blockUninstall, userId); 15439 mSettings.writePackageRestrictionsLPr(userId); 15440 } 15441 return true; 15442 } 15443 15444 @Override 15445 public boolean getBlockUninstallForUser(String packageName, int userId) { 15446 synchronized (mPackages) { 15447 PackageSetting ps = mSettings.mPackages.get(packageName); 15448 if (ps == null) { 15449 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 15450 return false; 15451 } 15452 return ps.getBlockUninstall(userId); 15453 } 15454 } 15455 15456 @Override 15457 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 15458 int callingUid = Binder.getCallingUid(); 15459 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 15460 throw new SecurityException( 15461 "setRequiredForSystemUser can only be run by the system or root"); 15462 } 15463 synchronized (mPackages) { 15464 PackageSetting ps = mSettings.mPackages.get(packageName); 15465 if (ps == null) { 15466 Log.w(TAG, "Package doesn't exist: " + packageName); 15467 return false; 15468 } 15469 if (systemUserApp) { 15470 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15471 } else { 15472 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15473 } 15474 mSettings.writeLPr(); 15475 } 15476 return true; 15477 } 15478 15479 /* 15480 * This method handles package deletion in general 15481 */ 15482 private boolean deletePackageLIF(String packageName, UserHandle user, 15483 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 15484 PackageRemovedInfo outInfo, boolean writeSettings, 15485 PackageParser.Package replacingPackage) { 15486 if (packageName == null) { 15487 Slog.w(TAG, "Attempt to delete null packageName."); 15488 return false; 15489 } 15490 15491 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 15492 15493 PackageSetting ps; 15494 15495 synchronized (mPackages) { 15496 ps = mSettings.mPackages.get(packageName); 15497 if (ps == null) { 15498 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 15499 return false; 15500 } 15501 15502 if (ps.parentPackageName != null && (!isSystemApp(ps) 15503 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 15504 if (DEBUG_REMOVE) { 15505 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 15506 + ((user == null) ? UserHandle.USER_ALL : user)); 15507 } 15508 final int removedUserId = (user != null) ? user.getIdentifier() 15509 : UserHandle.USER_ALL; 15510 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 15511 return false; 15512 } 15513 markPackageUninstalledForUserLPw(ps, user); 15514 scheduleWritePackageRestrictionsLocked(user); 15515 return true; 15516 } 15517 } 15518 15519 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 15520 && user.getIdentifier() != UserHandle.USER_ALL)) { 15521 // The caller is asking that the package only be deleted for a single 15522 // user. To do this, we just mark its uninstalled state and delete 15523 // its data. If this is a system app, we only allow this to happen if 15524 // they have set the special DELETE_SYSTEM_APP which requests different 15525 // semantics than normal for uninstalling system apps. 15526 markPackageUninstalledForUserLPw(ps, user); 15527 15528 if (!isSystemApp(ps)) { 15529 // Do not uninstall the APK if an app should be cached 15530 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 15531 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 15532 // Other user still have this package installed, so all 15533 // we need to do is clear this user's data and save that 15534 // it is uninstalled. 15535 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 15536 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 15537 return false; 15538 } 15539 scheduleWritePackageRestrictionsLocked(user); 15540 return true; 15541 } else { 15542 // We need to set it back to 'installed' so the uninstall 15543 // broadcasts will be sent correctly. 15544 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 15545 ps.setInstalled(true, user.getIdentifier()); 15546 } 15547 } else { 15548 // This is a system app, so we assume that the 15549 // other users still have this package installed, so all 15550 // we need to do is clear this user's data and save that 15551 // it is uninstalled. 15552 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 15553 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 15554 return false; 15555 } 15556 scheduleWritePackageRestrictionsLocked(user); 15557 return true; 15558 } 15559 } 15560 15561 // If we are deleting a composite package for all users, keep track 15562 // of result for each child. 15563 if (ps.childPackageNames != null && outInfo != null) { 15564 synchronized (mPackages) { 15565 final int childCount = ps.childPackageNames.size(); 15566 outInfo.removedChildPackages = new ArrayMap<>(childCount); 15567 for (int i = 0; i < childCount; i++) { 15568 String childPackageName = ps.childPackageNames.get(i); 15569 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 15570 childInfo.removedPackage = childPackageName; 15571 outInfo.removedChildPackages.put(childPackageName, childInfo); 15572 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 15573 if (childPs != null) { 15574 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 15575 } 15576 } 15577 } 15578 } 15579 15580 boolean ret = false; 15581 if (isSystemApp(ps)) { 15582 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 15583 // When an updated system application is deleted we delete the existing resources 15584 // as well and fall back to existing code in system partition 15585 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 15586 } else { 15587 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 15588 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 15589 outInfo, writeSettings, replacingPackage); 15590 } 15591 15592 // Take a note whether we deleted the package for all users 15593 if (outInfo != null) { 15594 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 15595 if (outInfo.removedChildPackages != null) { 15596 synchronized (mPackages) { 15597 final int childCount = outInfo.removedChildPackages.size(); 15598 for (int i = 0; i < childCount; i++) { 15599 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 15600 if (childInfo != null) { 15601 childInfo.removedForAllUsers = mPackages.get( 15602 childInfo.removedPackage) == null; 15603 } 15604 } 15605 } 15606 } 15607 // If we uninstalled an update to a system app there may be some 15608 // child packages that appeared as they are declared in the system 15609 // app but were not declared in the update. 15610 if (isSystemApp(ps)) { 15611 synchronized (mPackages) { 15612 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 15613 final int childCount = (updatedPs.childPackageNames != null) 15614 ? updatedPs.childPackageNames.size() : 0; 15615 for (int i = 0; i < childCount; i++) { 15616 String childPackageName = updatedPs.childPackageNames.get(i); 15617 if (outInfo.removedChildPackages == null 15618 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 15619 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 15620 if (childPs == null) { 15621 continue; 15622 } 15623 PackageInstalledInfo installRes = new PackageInstalledInfo(); 15624 installRes.name = childPackageName; 15625 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 15626 installRes.pkg = mPackages.get(childPackageName); 15627 installRes.uid = childPs.pkg.applicationInfo.uid; 15628 if (outInfo.appearedChildPackages == null) { 15629 outInfo.appearedChildPackages = new ArrayMap<>(); 15630 } 15631 outInfo.appearedChildPackages.put(childPackageName, installRes); 15632 } 15633 } 15634 } 15635 } 15636 } 15637 15638 return ret; 15639 } 15640 15641 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 15642 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 15643 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 15644 for (int nextUserId : userIds) { 15645 if (DEBUG_REMOVE) { 15646 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 15647 } 15648 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 15649 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 15650 false /*hidden*/, false /*suspended*/, null, null, null, 15651 false /*blockUninstall*/, 15652 ps.readUserState(nextUserId).domainVerificationStatus, 0); 15653 } 15654 } 15655 15656 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 15657 PackageRemovedInfo outInfo) { 15658 final PackageParser.Package pkg; 15659 synchronized (mPackages) { 15660 pkg = mPackages.get(ps.name); 15661 } 15662 15663 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 15664 : new int[] {userId}; 15665 for (int nextUserId : userIds) { 15666 if (DEBUG_REMOVE) { 15667 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 15668 + nextUserId); 15669 } 15670 15671 destroyAppDataLIF(pkg, userId, 15672 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15673 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 15674 schedulePackageCleaning(ps.name, nextUserId, false); 15675 synchronized (mPackages) { 15676 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 15677 scheduleWritePackageRestrictionsLocked(nextUserId); 15678 } 15679 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 15680 } 15681 } 15682 15683 if (outInfo != null) { 15684 outInfo.removedPackage = ps.name; 15685 outInfo.removedAppId = ps.appId; 15686 outInfo.removedUsers = userIds; 15687 } 15688 15689 return true; 15690 } 15691 15692 private final class ClearStorageConnection implements ServiceConnection { 15693 IMediaContainerService mContainerService; 15694 15695 @Override 15696 public void onServiceConnected(ComponentName name, IBinder service) { 15697 synchronized (this) { 15698 mContainerService = IMediaContainerService.Stub.asInterface(service); 15699 notifyAll(); 15700 } 15701 } 15702 15703 @Override 15704 public void onServiceDisconnected(ComponentName name) { 15705 } 15706 } 15707 15708 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 15709 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 15710 15711 final boolean mounted; 15712 if (Environment.isExternalStorageEmulated()) { 15713 mounted = true; 15714 } else { 15715 final String status = Environment.getExternalStorageState(); 15716 15717 mounted = status.equals(Environment.MEDIA_MOUNTED) 15718 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 15719 } 15720 15721 if (!mounted) { 15722 return; 15723 } 15724 15725 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 15726 int[] users; 15727 if (userId == UserHandle.USER_ALL) { 15728 users = sUserManager.getUserIds(); 15729 } else { 15730 users = new int[] { userId }; 15731 } 15732 final ClearStorageConnection conn = new ClearStorageConnection(); 15733 if (mContext.bindServiceAsUser( 15734 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 15735 try { 15736 for (int curUser : users) { 15737 long timeout = SystemClock.uptimeMillis() + 5000; 15738 synchronized (conn) { 15739 long now = SystemClock.uptimeMillis(); 15740 while (conn.mContainerService == null && now < timeout) { 15741 try { 15742 conn.wait(timeout - now); 15743 } catch (InterruptedException e) { 15744 } 15745 } 15746 } 15747 if (conn.mContainerService == null) { 15748 return; 15749 } 15750 15751 final UserEnvironment userEnv = new UserEnvironment(curUser); 15752 clearDirectory(conn.mContainerService, 15753 userEnv.buildExternalStorageAppCacheDirs(packageName)); 15754 if (allData) { 15755 clearDirectory(conn.mContainerService, 15756 userEnv.buildExternalStorageAppDataDirs(packageName)); 15757 clearDirectory(conn.mContainerService, 15758 userEnv.buildExternalStorageAppMediaDirs(packageName)); 15759 } 15760 } 15761 } finally { 15762 mContext.unbindService(conn); 15763 } 15764 } 15765 } 15766 15767 @Override 15768 public void clearApplicationProfileData(String packageName) { 15769 enforceSystemOrRoot("Only the system can clear all profile data"); 15770 15771 final PackageParser.Package pkg; 15772 synchronized (mPackages) { 15773 pkg = mPackages.get(packageName); 15774 } 15775 15776 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 15777 synchronized (mInstallLock) { 15778 clearAppProfilesLIF(pkg); 15779 } 15780 } 15781 } 15782 15783 @Override 15784 public void clearApplicationUserData(final String packageName, 15785 final IPackageDataObserver observer, final int userId) { 15786 mContext.enforceCallingOrSelfPermission( 15787 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 15788 15789 enforceCrossUserPermission(Binder.getCallingUid(), userId, 15790 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 15791 15792 final DevicePolicyManagerInternal dpmi = LocalServices 15793 .getService(DevicePolicyManagerInternal.class); 15794 if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) { 15795 throw new SecurityException("Cannot clear data for a device owner or a profile owner"); 15796 } 15797 // Queue up an async operation since the package deletion may take a little while. 15798 mHandler.post(new Runnable() { 15799 public void run() { 15800 mHandler.removeCallbacks(this); 15801 final boolean succeeded; 15802 try (PackageFreezer freezer = freezePackage(packageName, 15803 "clearApplicationUserData")) { 15804 synchronized (mInstallLock) { 15805 succeeded = clearApplicationUserDataLIF(packageName, userId); 15806 } 15807 clearExternalStorageDataSync(packageName, userId, true); 15808 } 15809 if (succeeded) { 15810 // invoke DeviceStorageMonitor's update method to clear any notifications 15811 DeviceStorageMonitorInternal dsm = LocalServices 15812 .getService(DeviceStorageMonitorInternal.class); 15813 if (dsm != null) { 15814 dsm.checkMemory(); 15815 } 15816 } 15817 if(observer != null) { 15818 try { 15819 observer.onRemoveCompleted(packageName, succeeded); 15820 } catch (RemoteException e) { 15821 Log.i(TAG, "Observer no longer exists."); 15822 } 15823 } //end if observer 15824 } //end run 15825 }); 15826 } 15827 15828 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 15829 if (packageName == null) { 15830 Slog.w(TAG, "Attempt to delete null packageName."); 15831 return false; 15832 } 15833 15834 // Try finding details about the requested package 15835 PackageParser.Package pkg; 15836 synchronized (mPackages) { 15837 pkg = mPackages.get(packageName); 15838 if (pkg == null) { 15839 final PackageSetting ps = mSettings.mPackages.get(packageName); 15840 if (ps != null) { 15841 pkg = ps.pkg; 15842 } 15843 } 15844 15845 if (pkg == null) { 15846 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 15847 return false; 15848 } 15849 15850 PackageSetting ps = (PackageSetting) pkg.mExtras; 15851 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 15852 } 15853 15854 clearAppDataLIF(pkg, userId, 15855 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15856 15857 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 15858 removeKeystoreDataIfNeeded(userId, appId); 15859 15860 final UserManager um = mContext.getSystemService(UserManager.class); 15861 final int flags; 15862 if (um.isUserUnlocked(userId)) { 15863 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 15864 } else if (um.isUserRunning(userId)) { 15865 flags = StorageManager.FLAG_STORAGE_DE; 15866 } else { 15867 flags = 0; 15868 } 15869 prepareAppDataContentsLIF(pkg, userId, flags); 15870 15871 return true; 15872 } 15873 15874 /** 15875 * Reverts user permission state changes (permissions and flags) in 15876 * all packages for a given user. 15877 * 15878 * @param userId The device user for which to do a reset. 15879 */ 15880 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 15881 final int packageCount = mPackages.size(); 15882 for (int i = 0; i < packageCount; i++) { 15883 PackageParser.Package pkg = mPackages.valueAt(i); 15884 PackageSetting ps = (PackageSetting) pkg.mExtras; 15885 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 15886 } 15887 } 15888 15889 /** 15890 * Reverts user permission state changes (permissions and flags). 15891 * 15892 * @param ps The package for which to reset. 15893 * @param userId The device user for which to do a reset. 15894 */ 15895 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 15896 final PackageSetting ps, final int userId) { 15897 if (ps.pkg == null) { 15898 return; 15899 } 15900 15901 // These are flags that can change base on user actions. 15902 final int userSettableMask = FLAG_PERMISSION_USER_SET 15903 | FLAG_PERMISSION_USER_FIXED 15904 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 15905 | FLAG_PERMISSION_REVIEW_REQUIRED; 15906 15907 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 15908 | FLAG_PERMISSION_POLICY_FIXED; 15909 15910 boolean writeInstallPermissions = false; 15911 boolean writeRuntimePermissions = false; 15912 15913 final int permissionCount = ps.pkg.requestedPermissions.size(); 15914 for (int i = 0; i < permissionCount; i++) { 15915 String permission = ps.pkg.requestedPermissions.get(i); 15916 15917 BasePermission bp = mSettings.mPermissions.get(permission); 15918 if (bp == null) { 15919 continue; 15920 } 15921 15922 // If shared user we just reset the state to which only this app contributed. 15923 if (ps.sharedUser != null) { 15924 boolean used = false; 15925 final int packageCount = ps.sharedUser.packages.size(); 15926 for (int j = 0; j < packageCount; j++) { 15927 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 15928 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 15929 && pkg.pkg.requestedPermissions.contains(permission)) { 15930 used = true; 15931 break; 15932 } 15933 } 15934 if (used) { 15935 continue; 15936 } 15937 } 15938 15939 PermissionsState permissionsState = ps.getPermissionsState(); 15940 15941 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 15942 15943 // Always clear the user settable flags. 15944 final boolean hasInstallState = permissionsState.getInstallPermissionState( 15945 bp.name) != null; 15946 // If permission review is enabled and this is a legacy app, mark the 15947 // permission as requiring a review as this is the initial state. 15948 int flags = 0; 15949 if (Build.PERMISSIONS_REVIEW_REQUIRED 15950 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 15951 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 15952 } 15953 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 15954 if (hasInstallState) { 15955 writeInstallPermissions = true; 15956 } else { 15957 writeRuntimePermissions = true; 15958 } 15959 } 15960 15961 // Below is only runtime permission handling. 15962 if (!bp.isRuntime()) { 15963 continue; 15964 } 15965 15966 // Never clobber system or policy. 15967 if ((oldFlags & policyOrSystemFlags) != 0) { 15968 continue; 15969 } 15970 15971 // If this permission was granted by default, make sure it is. 15972 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 15973 if (permissionsState.grantRuntimePermission(bp, userId) 15974 != PERMISSION_OPERATION_FAILURE) { 15975 writeRuntimePermissions = true; 15976 } 15977 // If permission review is enabled the permissions for a legacy apps 15978 // are represented as constantly granted runtime ones, so don't revoke. 15979 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 15980 // Otherwise, reset the permission. 15981 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 15982 switch (revokeResult) { 15983 case PERMISSION_OPERATION_SUCCESS: 15984 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 15985 writeRuntimePermissions = true; 15986 final int appId = ps.appId; 15987 mHandler.post(new Runnable() { 15988 @Override 15989 public void run() { 15990 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 15991 } 15992 }); 15993 } break; 15994 } 15995 } 15996 } 15997 15998 // Synchronously write as we are taking permissions away. 15999 if (writeRuntimePermissions) { 16000 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 16001 } 16002 16003 // Synchronously write as we are taking permissions away. 16004 if (writeInstallPermissions) { 16005 mSettings.writeLPr(); 16006 } 16007 } 16008 16009 /** 16010 * Remove entries from the keystore daemon. Will only remove it if the 16011 * {@code appId} is valid. 16012 */ 16013 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 16014 if (appId < 0) { 16015 return; 16016 } 16017 16018 final KeyStore keyStore = KeyStore.getInstance(); 16019 if (keyStore != null) { 16020 if (userId == UserHandle.USER_ALL) { 16021 for (final int individual : sUserManager.getUserIds()) { 16022 keyStore.clearUid(UserHandle.getUid(individual, appId)); 16023 } 16024 } else { 16025 keyStore.clearUid(UserHandle.getUid(userId, appId)); 16026 } 16027 } else { 16028 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 16029 } 16030 } 16031 16032 @Override 16033 public void deleteApplicationCacheFiles(final String packageName, 16034 final IPackageDataObserver observer) { 16035 final int userId = UserHandle.getCallingUserId(); 16036 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 16037 } 16038 16039 @Override 16040 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 16041 final IPackageDataObserver observer) { 16042 mContext.enforceCallingOrSelfPermission( 16043 android.Manifest.permission.DELETE_CACHE_FILES, null); 16044 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16045 /* requireFullPermission= */ true, /* checkShell= */ false, 16046 "delete application cache files"); 16047 16048 final PackageParser.Package pkg; 16049 synchronized (mPackages) { 16050 pkg = mPackages.get(packageName); 16051 } 16052 16053 // Queue up an async operation since the package deletion may take a little while. 16054 mHandler.post(new Runnable() { 16055 public void run() { 16056 synchronized (mInstallLock) { 16057 final int flags = StorageManager.FLAG_STORAGE_DE 16058 | StorageManager.FLAG_STORAGE_CE; 16059 // We're only clearing cache files, so we don't care if the 16060 // app is unfrozen and still able to run 16061 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 16062 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16063 } 16064 clearExternalStorageDataSync(packageName, userId, false); 16065 if (observer != null) { 16066 try { 16067 observer.onRemoveCompleted(packageName, true); 16068 } catch (RemoteException e) { 16069 Log.i(TAG, "Observer no longer exists."); 16070 } 16071 } 16072 } 16073 }); 16074 } 16075 16076 @Override 16077 public void getPackageSizeInfo(final String packageName, int userHandle, 16078 final IPackageStatsObserver observer) { 16079 mContext.enforceCallingOrSelfPermission( 16080 android.Manifest.permission.GET_PACKAGE_SIZE, null); 16081 if (packageName == null) { 16082 throw new IllegalArgumentException("Attempt to get size of null packageName"); 16083 } 16084 16085 PackageStats stats = new PackageStats(packageName, userHandle); 16086 16087 /* 16088 * Queue up an async operation since the package measurement may take a 16089 * little while. 16090 */ 16091 Message msg = mHandler.obtainMessage(INIT_COPY); 16092 msg.obj = new MeasureParams(stats, observer); 16093 mHandler.sendMessage(msg); 16094 } 16095 16096 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 16097 final PackageSetting ps; 16098 synchronized (mPackages) { 16099 ps = mSettings.mPackages.get(packageName); 16100 if (ps == null) { 16101 Slog.w(TAG, "Failed to find settings for " + packageName); 16102 return false; 16103 } 16104 } 16105 try { 16106 mInstaller.getAppSize(ps.volumeUuid, packageName, userId, 16107 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 16108 ps.getCeDataInode(userId), ps.codePathString, stats); 16109 } catch (InstallerException e) { 16110 Slog.w(TAG, String.valueOf(e)); 16111 return false; 16112 } 16113 16114 // For now, ignore code size of packages on system partition 16115 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 16116 stats.codeSize = 0; 16117 } 16118 16119 return true; 16120 } 16121 16122 private int getUidTargetSdkVersionLockedLPr(int uid) { 16123 Object obj = mSettings.getUserIdLPr(uid); 16124 if (obj instanceof SharedUserSetting) { 16125 final SharedUserSetting sus = (SharedUserSetting) obj; 16126 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 16127 final Iterator<PackageSetting> it = sus.packages.iterator(); 16128 while (it.hasNext()) { 16129 final PackageSetting ps = it.next(); 16130 if (ps.pkg != null) { 16131 int v = ps.pkg.applicationInfo.targetSdkVersion; 16132 if (v < vers) vers = v; 16133 } 16134 } 16135 return vers; 16136 } else if (obj instanceof PackageSetting) { 16137 final PackageSetting ps = (PackageSetting) obj; 16138 if (ps.pkg != null) { 16139 return ps.pkg.applicationInfo.targetSdkVersion; 16140 } 16141 } 16142 return Build.VERSION_CODES.CUR_DEVELOPMENT; 16143 } 16144 16145 @Override 16146 public void addPreferredActivity(IntentFilter filter, int match, 16147 ComponentName[] set, ComponentName activity, int userId) { 16148 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16149 "Adding preferred"); 16150 } 16151 16152 private void addPreferredActivityInternal(IntentFilter filter, int match, 16153 ComponentName[] set, ComponentName activity, boolean always, int userId, 16154 String opname) { 16155 // writer 16156 int callingUid = Binder.getCallingUid(); 16157 enforceCrossUserPermission(callingUid, userId, 16158 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 16159 if (filter.countActions() == 0) { 16160 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16161 return; 16162 } 16163 synchronized (mPackages) { 16164 if (mContext.checkCallingOrSelfPermission( 16165 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16166 != PackageManager.PERMISSION_GRANTED) { 16167 if (getUidTargetSdkVersionLockedLPr(callingUid) 16168 < Build.VERSION_CODES.FROYO) { 16169 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 16170 + callingUid); 16171 return; 16172 } 16173 mContext.enforceCallingOrSelfPermission( 16174 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16175 } 16176 16177 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 16178 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 16179 + userId + ":"); 16180 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16181 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 16182 scheduleWritePackageRestrictionsLocked(userId); 16183 } 16184 } 16185 16186 @Override 16187 public void replacePreferredActivity(IntentFilter filter, int match, 16188 ComponentName[] set, ComponentName activity, int userId) { 16189 if (filter.countActions() != 1) { 16190 throw new IllegalArgumentException( 16191 "replacePreferredActivity expects filter to have only 1 action."); 16192 } 16193 if (filter.countDataAuthorities() != 0 16194 || filter.countDataPaths() != 0 16195 || filter.countDataSchemes() > 1 16196 || filter.countDataTypes() != 0) { 16197 throw new IllegalArgumentException( 16198 "replacePreferredActivity expects filter to have no data authorities, " + 16199 "paths, or types; and at most one scheme."); 16200 } 16201 16202 final int callingUid = Binder.getCallingUid(); 16203 enforceCrossUserPermission(callingUid, userId, 16204 true /* requireFullPermission */, false /* checkShell */, 16205 "replace preferred activity"); 16206 synchronized (mPackages) { 16207 if (mContext.checkCallingOrSelfPermission( 16208 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16209 != PackageManager.PERMISSION_GRANTED) { 16210 if (getUidTargetSdkVersionLockedLPr(callingUid) 16211 < Build.VERSION_CODES.FROYO) { 16212 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 16213 + Binder.getCallingUid()); 16214 return; 16215 } 16216 mContext.enforceCallingOrSelfPermission( 16217 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16218 } 16219 16220 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16221 if (pir != null) { 16222 // Get all of the existing entries that exactly match this filter. 16223 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 16224 if (existing != null && existing.size() == 1) { 16225 PreferredActivity cur = existing.get(0); 16226 if (DEBUG_PREFERRED) { 16227 Slog.i(TAG, "Checking replace of preferred:"); 16228 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16229 if (!cur.mPref.mAlways) { 16230 Slog.i(TAG, " -- CUR; not mAlways!"); 16231 } else { 16232 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 16233 Slog.i(TAG, " -- CUR: mSet=" 16234 + Arrays.toString(cur.mPref.mSetComponents)); 16235 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 16236 Slog.i(TAG, " -- NEW: mMatch=" 16237 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 16238 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 16239 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 16240 } 16241 } 16242 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 16243 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 16244 && cur.mPref.sameSet(set)) { 16245 // Setting the preferred activity to what it happens to be already 16246 if (DEBUG_PREFERRED) { 16247 Slog.i(TAG, "Replacing with same preferred activity " 16248 + cur.mPref.mShortComponent + " for user " 16249 + userId + ":"); 16250 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16251 } 16252 return; 16253 } 16254 } 16255 16256 if (existing != null) { 16257 if (DEBUG_PREFERRED) { 16258 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 16259 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16260 } 16261 for (int i = 0; i < existing.size(); i++) { 16262 PreferredActivity pa = existing.get(i); 16263 if (DEBUG_PREFERRED) { 16264 Slog.i(TAG, "Removing existing preferred activity " 16265 + pa.mPref.mComponent + ":"); 16266 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 16267 } 16268 pir.removeFilter(pa); 16269 } 16270 } 16271 } 16272 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16273 "Replacing preferred"); 16274 } 16275 } 16276 16277 @Override 16278 public void clearPackagePreferredActivities(String packageName) { 16279 final int uid = Binder.getCallingUid(); 16280 // writer 16281 synchronized (mPackages) { 16282 PackageParser.Package pkg = mPackages.get(packageName); 16283 if (pkg == null || pkg.applicationInfo.uid != uid) { 16284 if (mContext.checkCallingOrSelfPermission( 16285 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16286 != PackageManager.PERMISSION_GRANTED) { 16287 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 16288 < Build.VERSION_CODES.FROYO) { 16289 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 16290 + Binder.getCallingUid()); 16291 return; 16292 } 16293 mContext.enforceCallingOrSelfPermission( 16294 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16295 } 16296 } 16297 16298 int user = UserHandle.getCallingUserId(); 16299 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 16300 scheduleWritePackageRestrictionsLocked(user); 16301 } 16302 } 16303 } 16304 16305 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16306 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 16307 ArrayList<PreferredActivity> removed = null; 16308 boolean changed = false; 16309 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16310 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 16311 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16312 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 16313 continue; 16314 } 16315 Iterator<PreferredActivity> it = pir.filterIterator(); 16316 while (it.hasNext()) { 16317 PreferredActivity pa = it.next(); 16318 // Mark entry for removal only if it matches the package name 16319 // and the entry is of type "always". 16320 if (packageName == null || 16321 (pa.mPref.mComponent.getPackageName().equals(packageName) 16322 && pa.mPref.mAlways)) { 16323 if (removed == null) { 16324 removed = new ArrayList<PreferredActivity>(); 16325 } 16326 removed.add(pa); 16327 } 16328 } 16329 if (removed != null) { 16330 for (int j=0; j<removed.size(); j++) { 16331 PreferredActivity pa = removed.get(j); 16332 pir.removeFilter(pa); 16333 } 16334 changed = true; 16335 } 16336 } 16337 return changed; 16338 } 16339 16340 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16341 private void clearIntentFilterVerificationsLPw(int userId) { 16342 final int packageCount = mPackages.size(); 16343 for (int i = 0; i < packageCount; i++) { 16344 PackageParser.Package pkg = mPackages.valueAt(i); 16345 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 16346 } 16347 } 16348 16349 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16350 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 16351 if (userId == UserHandle.USER_ALL) { 16352 if (mSettings.removeIntentFilterVerificationLPw(packageName, 16353 sUserManager.getUserIds())) { 16354 for (int oneUserId : sUserManager.getUserIds()) { 16355 scheduleWritePackageRestrictionsLocked(oneUserId); 16356 } 16357 } 16358 } else { 16359 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 16360 scheduleWritePackageRestrictionsLocked(userId); 16361 } 16362 } 16363 } 16364 16365 void clearDefaultBrowserIfNeeded(String packageName) { 16366 for (int oneUserId : sUserManager.getUserIds()) { 16367 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 16368 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 16369 if (packageName.equals(defaultBrowserPackageName)) { 16370 setDefaultBrowserPackageName(null, oneUserId); 16371 } 16372 } 16373 } 16374 16375 @Override 16376 public void resetApplicationPreferences(int userId) { 16377 mContext.enforceCallingOrSelfPermission( 16378 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16379 // writer 16380 synchronized (mPackages) { 16381 final long identity = Binder.clearCallingIdentity(); 16382 try { 16383 clearPackagePreferredActivitiesLPw(null, userId); 16384 mSettings.applyDefaultPreferredAppsLPw(this, userId); 16385 // TODO: We have to reset the default SMS and Phone. This requires 16386 // significant refactoring to keep all default apps in the package 16387 // manager (cleaner but more work) or have the services provide 16388 // callbacks to the package manager to request a default app reset. 16389 applyFactoryDefaultBrowserLPw(userId); 16390 clearIntentFilterVerificationsLPw(userId); 16391 primeDomainVerificationsLPw(userId); 16392 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 16393 scheduleWritePackageRestrictionsLocked(userId); 16394 } finally { 16395 Binder.restoreCallingIdentity(identity); 16396 } 16397 } 16398 } 16399 16400 @Override 16401 public int getPreferredActivities(List<IntentFilter> outFilters, 16402 List<ComponentName> outActivities, String packageName) { 16403 16404 int num = 0; 16405 final int userId = UserHandle.getCallingUserId(); 16406 // reader 16407 synchronized (mPackages) { 16408 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16409 if (pir != null) { 16410 final Iterator<PreferredActivity> it = pir.filterIterator(); 16411 while (it.hasNext()) { 16412 final PreferredActivity pa = it.next(); 16413 if (packageName == null 16414 || (pa.mPref.mComponent.getPackageName().equals(packageName) 16415 && pa.mPref.mAlways)) { 16416 if (outFilters != null) { 16417 outFilters.add(new IntentFilter(pa)); 16418 } 16419 if (outActivities != null) { 16420 outActivities.add(pa.mPref.mComponent); 16421 } 16422 } 16423 } 16424 } 16425 } 16426 16427 return num; 16428 } 16429 16430 @Override 16431 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 16432 int userId) { 16433 int callingUid = Binder.getCallingUid(); 16434 if (callingUid != Process.SYSTEM_UID) { 16435 throw new SecurityException( 16436 "addPersistentPreferredActivity can only be run by the system"); 16437 } 16438 if (filter.countActions() == 0) { 16439 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16440 return; 16441 } 16442 synchronized (mPackages) { 16443 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 16444 ":"); 16445 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16446 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 16447 new PersistentPreferredActivity(filter, activity)); 16448 scheduleWritePackageRestrictionsLocked(userId); 16449 } 16450 } 16451 16452 @Override 16453 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 16454 int callingUid = Binder.getCallingUid(); 16455 if (callingUid != Process.SYSTEM_UID) { 16456 throw new SecurityException( 16457 "clearPackagePersistentPreferredActivities can only be run by the system"); 16458 } 16459 ArrayList<PersistentPreferredActivity> removed = null; 16460 boolean changed = false; 16461 synchronized (mPackages) { 16462 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 16463 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 16464 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 16465 .valueAt(i); 16466 if (userId != thisUserId) { 16467 continue; 16468 } 16469 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 16470 while (it.hasNext()) { 16471 PersistentPreferredActivity ppa = it.next(); 16472 // Mark entry for removal only if it matches the package name. 16473 if (ppa.mComponent.getPackageName().equals(packageName)) { 16474 if (removed == null) { 16475 removed = new ArrayList<PersistentPreferredActivity>(); 16476 } 16477 removed.add(ppa); 16478 } 16479 } 16480 if (removed != null) { 16481 for (int j=0; j<removed.size(); j++) { 16482 PersistentPreferredActivity ppa = removed.get(j); 16483 ppir.removeFilter(ppa); 16484 } 16485 changed = true; 16486 } 16487 } 16488 16489 if (changed) { 16490 scheduleWritePackageRestrictionsLocked(userId); 16491 } 16492 } 16493 } 16494 16495 /** 16496 * Common machinery for picking apart a restored XML blob and passing 16497 * it to a caller-supplied functor to be applied to the running system. 16498 */ 16499 private void restoreFromXml(XmlPullParser parser, int userId, 16500 String expectedStartTag, BlobXmlRestorer functor) 16501 throws IOException, XmlPullParserException { 16502 int type; 16503 while ((type = parser.next()) != XmlPullParser.START_TAG 16504 && type != XmlPullParser.END_DOCUMENT) { 16505 } 16506 if (type != XmlPullParser.START_TAG) { 16507 // oops didn't find a start tag?! 16508 if (DEBUG_BACKUP) { 16509 Slog.e(TAG, "Didn't find start tag during restore"); 16510 } 16511 return; 16512 } 16513Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 16514 // this is supposed to be TAG_PREFERRED_BACKUP 16515 if (!expectedStartTag.equals(parser.getName())) { 16516 if (DEBUG_BACKUP) { 16517 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 16518 } 16519 return; 16520 } 16521 16522 // skip interfering stuff, then we're aligned with the backing implementation 16523 while ((type = parser.next()) == XmlPullParser.TEXT) { } 16524Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 16525 functor.apply(parser, userId); 16526 } 16527 16528 private interface BlobXmlRestorer { 16529 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 16530 } 16531 16532 /** 16533 * Non-Binder method, support for the backup/restore mechanism: write the 16534 * full set of preferred activities in its canonical XML format. Returns the 16535 * XML output as a byte array, or null if there is none. 16536 */ 16537 @Override 16538 public byte[] getPreferredActivityBackup(int userId) { 16539 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16540 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 16541 } 16542 16543 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16544 try { 16545 final XmlSerializer serializer = new FastXmlSerializer(); 16546 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16547 serializer.startDocument(null, true); 16548 serializer.startTag(null, TAG_PREFERRED_BACKUP); 16549 16550 synchronized (mPackages) { 16551 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 16552 } 16553 16554 serializer.endTag(null, TAG_PREFERRED_BACKUP); 16555 serializer.endDocument(); 16556 serializer.flush(); 16557 } catch (Exception e) { 16558 if (DEBUG_BACKUP) { 16559 Slog.e(TAG, "Unable to write preferred activities for backup", e); 16560 } 16561 return null; 16562 } 16563 16564 return dataStream.toByteArray(); 16565 } 16566 16567 @Override 16568 public void restorePreferredActivities(byte[] backup, int userId) { 16569 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16570 throw new SecurityException("Only the system may call restorePreferredActivities()"); 16571 } 16572 16573 try { 16574 final XmlPullParser parser = Xml.newPullParser(); 16575 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16576 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 16577 new BlobXmlRestorer() { 16578 @Override 16579 public void apply(XmlPullParser parser, int userId) 16580 throws XmlPullParserException, IOException { 16581 synchronized (mPackages) { 16582 mSettings.readPreferredActivitiesLPw(parser, userId); 16583 } 16584 } 16585 } ); 16586 } catch (Exception e) { 16587 if (DEBUG_BACKUP) { 16588 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16589 } 16590 } 16591 } 16592 16593 /** 16594 * Non-Binder method, support for the backup/restore mechanism: write the 16595 * default browser (etc) settings in its canonical XML format. Returns the default 16596 * browser XML representation as a byte array, or null if there is none. 16597 */ 16598 @Override 16599 public byte[] getDefaultAppsBackup(int userId) { 16600 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16601 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 16602 } 16603 16604 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16605 try { 16606 final XmlSerializer serializer = new FastXmlSerializer(); 16607 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16608 serializer.startDocument(null, true); 16609 serializer.startTag(null, TAG_DEFAULT_APPS); 16610 16611 synchronized (mPackages) { 16612 mSettings.writeDefaultAppsLPr(serializer, userId); 16613 } 16614 16615 serializer.endTag(null, TAG_DEFAULT_APPS); 16616 serializer.endDocument(); 16617 serializer.flush(); 16618 } catch (Exception e) { 16619 if (DEBUG_BACKUP) { 16620 Slog.e(TAG, "Unable to write default apps for backup", e); 16621 } 16622 return null; 16623 } 16624 16625 return dataStream.toByteArray(); 16626 } 16627 16628 @Override 16629 public void restoreDefaultApps(byte[] backup, int userId) { 16630 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16631 throw new SecurityException("Only the system may call restoreDefaultApps()"); 16632 } 16633 16634 try { 16635 final XmlPullParser parser = Xml.newPullParser(); 16636 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16637 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 16638 new BlobXmlRestorer() { 16639 @Override 16640 public void apply(XmlPullParser parser, int userId) 16641 throws XmlPullParserException, IOException { 16642 synchronized (mPackages) { 16643 mSettings.readDefaultAppsLPw(parser, userId); 16644 } 16645 } 16646 } ); 16647 } catch (Exception e) { 16648 if (DEBUG_BACKUP) { 16649 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 16650 } 16651 } 16652 } 16653 16654 @Override 16655 public byte[] getIntentFilterVerificationBackup(int userId) { 16656 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16657 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 16658 } 16659 16660 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16661 try { 16662 final XmlSerializer serializer = new FastXmlSerializer(); 16663 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16664 serializer.startDocument(null, true); 16665 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 16666 16667 synchronized (mPackages) { 16668 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 16669 } 16670 16671 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 16672 serializer.endDocument(); 16673 serializer.flush(); 16674 } catch (Exception e) { 16675 if (DEBUG_BACKUP) { 16676 Slog.e(TAG, "Unable to write default apps for backup", e); 16677 } 16678 return null; 16679 } 16680 16681 return dataStream.toByteArray(); 16682 } 16683 16684 @Override 16685 public void restoreIntentFilterVerification(byte[] backup, int userId) { 16686 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16687 throw new SecurityException("Only the system may call restorePreferredActivities()"); 16688 } 16689 16690 try { 16691 final XmlPullParser parser = Xml.newPullParser(); 16692 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16693 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 16694 new BlobXmlRestorer() { 16695 @Override 16696 public void apply(XmlPullParser parser, int userId) 16697 throws XmlPullParserException, IOException { 16698 synchronized (mPackages) { 16699 mSettings.readAllDomainVerificationsLPr(parser, userId); 16700 mSettings.writeLPr(); 16701 } 16702 } 16703 } ); 16704 } catch (Exception e) { 16705 if (DEBUG_BACKUP) { 16706 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16707 } 16708 } 16709 } 16710 16711 @Override 16712 public byte[] getPermissionGrantBackup(int userId) { 16713 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16714 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 16715 } 16716 16717 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16718 try { 16719 final XmlSerializer serializer = new FastXmlSerializer(); 16720 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16721 serializer.startDocument(null, true); 16722 serializer.startTag(null, TAG_PERMISSION_BACKUP); 16723 16724 synchronized (mPackages) { 16725 serializeRuntimePermissionGrantsLPr(serializer, userId); 16726 } 16727 16728 serializer.endTag(null, TAG_PERMISSION_BACKUP); 16729 serializer.endDocument(); 16730 serializer.flush(); 16731 } catch (Exception e) { 16732 if (DEBUG_BACKUP) { 16733 Slog.e(TAG, "Unable to write default apps for backup", e); 16734 } 16735 return null; 16736 } 16737 16738 return dataStream.toByteArray(); 16739 } 16740 16741 @Override 16742 public void restorePermissionGrants(byte[] backup, int userId) { 16743 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16744 throw new SecurityException("Only the system may call restorePermissionGrants()"); 16745 } 16746 16747 try { 16748 final XmlPullParser parser = Xml.newPullParser(); 16749 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16750 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 16751 new BlobXmlRestorer() { 16752 @Override 16753 public void apply(XmlPullParser parser, int userId) 16754 throws XmlPullParserException, IOException { 16755 synchronized (mPackages) { 16756 processRestoredPermissionGrantsLPr(parser, userId); 16757 } 16758 } 16759 } ); 16760 } catch (Exception e) { 16761 if (DEBUG_BACKUP) { 16762 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16763 } 16764 } 16765 } 16766 16767 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 16768 throws IOException { 16769 serializer.startTag(null, TAG_ALL_GRANTS); 16770 16771 final int N = mSettings.mPackages.size(); 16772 for (int i = 0; i < N; i++) { 16773 final PackageSetting ps = mSettings.mPackages.valueAt(i); 16774 boolean pkgGrantsKnown = false; 16775 16776 PermissionsState packagePerms = ps.getPermissionsState(); 16777 16778 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 16779 final int grantFlags = state.getFlags(); 16780 // only look at grants that are not system/policy fixed 16781 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 16782 final boolean isGranted = state.isGranted(); 16783 // And only back up the user-twiddled state bits 16784 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 16785 final String packageName = mSettings.mPackages.keyAt(i); 16786 if (!pkgGrantsKnown) { 16787 serializer.startTag(null, TAG_GRANT); 16788 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 16789 pkgGrantsKnown = true; 16790 } 16791 16792 final boolean userSet = 16793 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 16794 final boolean userFixed = 16795 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 16796 final boolean revoke = 16797 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 16798 16799 serializer.startTag(null, TAG_PERMISSION); 16800 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 16801 if (isGranted) { 16802 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 16803 } 16804 if (userSet) { 16805 serializer.attribute(null, ATTR_USER_SET, "true"); 16806 } 16807 if (userFixed) { 16808 serializer.attribute(null, ATTR_USER_FIXED, "true"); 16809 } 16810 if (revoke) { 16811 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 16812 } 16813 serializer.endTag(null, TAG_PERMISSION); 16814 } 16815 } 16816 } 16817 16818 if (pkgGrantsKnown) { 16819 serializer.endTag(null, TAG_GRANT); 16820 } 16821 } 16822 16823 serializer.endTag(null, TAG_ALL_GRANTS); 16824 } 16825 16826 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 16827 throws XmlPullParserException, IOException { 16828 String pkgName = null; 16829 int outerDepth = parser.getDepth(); 16830 int type; 16831 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 16832 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 16833 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 16834 continue; 16835 } 16836 16837 final String tagName = parser.getName(); 16838 if (tagName.equals(TAG_GRANT)) { 16839 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 16840 if (DEBUG_BACKUP) { 16841 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 16842 } 16843 } else if (tagName.equals(TAG_PERMISSION)) { 16844 16845 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 16846 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 16847 16848 int newFlagSet = 0; 16849 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 16850 newFlagSet |= FLAG_PERMISSION_USER_SET; 16851 } 16852 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 16853 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 16854 } 16855 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 16856 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 16857 } 16858 if (DEBUG_BACKUP) { 16859 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 16860 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 16861 } 16862 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16863 if (ps != null) { 16864 // Already installed so we apply the grant immediately 16865 if (DEBUG_BACKUP) { 16866 Slog.v(TAG, " + already installed; applying"); 16867 } 16868 PermissionsState perms = ps.getPermissionsState(); 16869 BasePermission bp = mSettings.mPermissions.get(permName); 16870 if (bp != null) { 16871 if (isGranted) { 16872 perms.grantRuntimePermission(bp, userId); 16873 } 16874 if (newFlagSet != 0) { 16875 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 16876 } 16877 } 16878 } else { 16879 // Need to wait for post-restore install to apply the grant 16880 if (DEBUG_BACKUP) { 16881 Slog.v(TAG, " - not yet installed; saving for later"); 16882 } 16883 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 16884 isGranted, newFlagSet, userId); 16885 } 16886 } else { 16887 PackageManagerService.reportSettingsProblem(Log.WARN, 16888 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 16889 XmlUtils.skipCurrentTag(parser); 16890 } 16891 } 16892 16893 scheduleWriteSettingsLocked(); 16894 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 16895 } 16896 16897 @Override 16898 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 16899 int sourceUserId, int targetUserId, int flags) { 16900 mContext.enforceCallingOrSelfPermission( 16901 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 16902 int callingUid = Binder.getCallingUid(); 16903 enforceOwnerRights(ownerPackage, callingUid); 16904 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 16905 if (intentFilter.countActions() == 0) { 16906 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 16907 return; 16908 } 16909 synchronized (mPackages) { 16910 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 16911 ownerPackage, targetUserId, flags); 16912 CrossProfileIntentResolver resolver = 16913 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 16914 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 16915 // We have all those whose filter is equal. Now checking if the rest is equal as well. 16916 if (existing != null) { 16917 int size = existing.size(); 16918 for (int i = 0; i < size; i++) { 16919 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 16920 return; 16921 } 16922 } 16923 } 16924 resolver.addFilter(newFilter); 16925 scheduleWritePackageRestrictionsLocked(sourceUserId); 16926 } 16927 } 16928 16929 @Override 16930 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 16931 mContext.enforceCallingOrSelfPermission( 16932 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 16933 int callingUid = Binder.getCallingUid(); 16934 enforceOwnerRights(ownerPackage, callingUid); 16935 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 16936 synchronized (mPackages) { 16937 CrossProfileIntentResolver resolver = 16938 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 16939 ArraySet<CrossProfileIntentFilter> set = 16940 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 16941 for (CrossProfileIntentFilter filter : set) { 16942 if (filter.getOwnerPackage().equals(ownerPackage)) { 16943 resolver.removeFilter(filter); 16944 } 16945 } 16946 scheduleWritePackageRestrictionsLocked(sourceUserId); 16947 } 16948 } 16949 16950 // Enforcing that callingUid is owning pkg on userId 16951 private void enforceOwnerRights(String pkg, int callingUid) { 16952 // The system owns everything. 16953 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 16954 return; 16955 } 16956 int callingUserId = UserHandle.getUserId(callingUid); 16957 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 16958 if (pi == null) { 16959 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 16960 + callingUserId); 16961 } 16962 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 16963 throw new SecurityException("Calling uid " + callingUid 16964 + " does not own package " + pkg); 16965 } 16966 } 16967 16968 @Override 16969 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 16970 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 16971 } 16972 16973 private Intent getHomeIntent() { 16974 Intent intent = new Intent(Intent.ACTION_MAIN); 16975 intent.addCategory(Intent.CATEGORY_HOME); 16976 return intent; 16977 } 16978 16979 private IntentFilter getHomeFilter() { 16980 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 16981 filter.addCategory(Intent.CATEGORY_HOME); 16982 filter.addCategory(Intent.CATEGORY_DEFAULT); 16983 return filter; 16984 } 16985 16986 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 16987 int userId) { 16988 Intent intent = getHomeIntent(); 16989 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 16990 PackageManager.GET_META_DATA, userId); 16991 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 16992 true, false, false, userId); 16993 16994 allHomeCandidates.clear(); 16995 if (list != null) { 16996 for (ResolveInfo ri : list) { 16997 allHomeCandidates.add(ri); 16998 } 16999 } 17000 return (preferred == null || preferred.activityInfo == null) 17001 ? null 17002 : new ComponentName(preferred.activityInfo.packageName, 17003 preferred.activityInfo.name); 17004 } 17005 17006 @Override 17007 public void setHomeActivity(ComponentName comp, int userId) { 17008 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 17009 getHomeActivitiesAsUser(homeActivities, userId); 17010 17011 boolean found = false; 17012 17013 final int size = homeActivities.size(); 17014 final ComponentName[] set = new ComponentName[size]; 17015 for (int i = 0; i < size; i++) { 17016 final ResolveInfo candidate = homeActivities.get(i); 17017 final ActivityInfo info = candidate.activityInfo; 17018 final ComponentName activityName = new ComponentName(info.packageName, info.name); 17019 set[i] = activityName; 17020 if (!found && activityName.equals(comp)) { 17021 found = true; 17022 } 17023 } 17024 if (!found) { 17025 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 17026 + userId); 17027 } 17028 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 17029 set, comp, userId); 17030 } 17031 17032 private @Nullable String getSetupWizardPackageName() { 17033 final Intent intent = new Intent(Intent.ACTION_MAIN); 17034 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 17035 17036 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 17037 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 17038 | MATCH_DISABLED_COMPONENTS, 17039 UserHandle.myUserId()); 17040 if (matches.size() == 1) { 17041 return matches.get(0).getComponentInfo().packageName; 17042 } else { 17043 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 17044 + ": matches=" + matches); 17045 return null; 17046 } 17047 } 17048 17049 @Override 17050 public void setApplicationEnabledSetting(String appPackageName, 17051 int newState, int flags, int userId, String callingPackage) { 17052 if (!sUserManager.exists(userId)) return; 17053 if (callingPackage == null) { 17054 callingPackage = Integer.toString(Binder.getCallingUid()); 17055 } 17056 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 17057 } 17058 17059 @Override 17060 public void setComponentEnabledSetting(ComponentName componentName, 17061 int newState, int flags, int userId) { 17062 if (!sUserManager.exists(userId)) return; 17063 setEnabledSetting(componentName.getPackageName(), 17064 componentName.getClassName(), newState, flags, userId, null); 17065 } 17066 17067 private void setEnabledSetting(final String packageName, String className, int newState, 17068 final int flags, int userId, String callingPackage) { 17069 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 17070 || newState == COMPONENT_ENABLED_STATE_ENABLED 17071 || newState == COMPONENT_ENABLED_STATE_DISABLED 17072 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17073 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 17074 throw new IllegalArgumentException("Invalid new component state: " 17075 + newState); 17076 } 17077 PackageSetting pkgSetting; 17078 final int uid = Binder.getCallingUid(); 17079 final int permission; 17080 if (uid == Process.SYSTEM_UID) { 17081 permission = PackageManager.PERMISSION_GRANTED; 17082 } else { 17083 permission = mContext.checkCallingOrSelfPermission( 17084 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17085 } 17086 enforceCrossUserPermission(uid, userId, 17087 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 17088 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17089 boolean sendNow = false; 17090 boolean isApp = (className == null); 17091 String componentName = isApp ? packageName : className; 17092 int packageUid = -1; 17093 ArrayList<String> components; 17094 17095 // writer 17096 synchronized (mPackages) { 17097 pkgSetting = mSettings.mPackages.get(packageName); 17098 if (pkgSetting == null) { 17099 if (className == null) { 17100 throw new IllegalArgumentException("Unknown package: " + packageName); 17101 } 17102 throw new IllegalArgumentException( 17103 "Unknown component: " + packageName + "/" + className); 17104 } 17105 // Allow root and verify that userId is not being specified by a different user 17106 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 17107 throw new SecurityException( 17108 "Permission Denial: attempt to change component state from pid=" 17109 + Binder.getCallingPid() 17110 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 17111 } 17112 if (className == null) { 17113 // We're dealing with an application/package level state change 17114 if (pkgSetting.getEnabled(userId) == newState) { 17115 // Nothing to do 17116 return; 17117 } 17118 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 17119 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 17120 // Don't care about who enables an app. 17121 callingPackage = null; 17122 } 17123 pkgSetting.setEnabled(newState, userId, callingPackage); 17124 // pkgSetting.pkg.mSetEnabled = newState; 17125 } else { 17126 // We're dealing with a component level state change 17127 // First, verify that this is a valid class name. 17128 PackageParser.Package pkg = pkgSetting.pkg; 17129 if (pkg == null || !pkg.hasComponentClassName(className)) { 17130 if (pkg != null && 17131 pkg.applicationInfo.targetSdkVersion >= 17132 Build.VERSION_CODES.JELLY_BEAN) { 17133 throw new IllegalArgumentException("Component class " + className 17134 + " does not exist in " + packageName); 17135 } else { 17136 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 17137 + className + " does not exist in " + packageName); 17138 } 17139 } 17140 switch (newState) { 17141 case COMPONENT_ENABLED_STATE_ENABLED: 17142 if (!pkgSetting.enableComponentLPw(className, userId)) { 17143 return; 17144 } 17145 break; 17146 case COMPONENT_ENABLED_STATE_DISABLED: 17147 if (!pkgSetting.disableComponentLPw(className, userId)) { 17148 return; 17149 } 17150 break; 17151 case COMPONENT_ENABLED_STATE_DEFAULT: 17152 if (!pkgSetting.restoreComponentLPw(className, userId)) { 17153 return; 17154 } 17155 break; 17156 default: 17157 Slog.e(TAG, "Invalid new component state: " + newState); 17158 return; 17159 } 17160 } 17161 scheduleWritePackageRestrictionsLocked(userId); 17162 components = mPendingBroadcasts.get(userId, packageName); 17163 final boolean newPackage = components == null; 17164 if (newPackage) { 17165 components = new ArrayList<String>(); 17166 } 17167 if (!components.contains(componentName)) { 17168 components.add(componentName); 17169 } 17170 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 17171 sendNow = true; 17172 // Purge entry from pending broadcast list if another one exists already 17173 // since we are sending one right away. 17174 mPendingBroadcasts.remove(userId, packageName); 17175 } else { 17176 if (newPackage) { 17177 mPendingBroadcasts.put(userId, packageName, components); 17178 } 17179 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 17180 // Schedule a message 17181 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 17182 } 17183 } 17184 } 17185 17186 long callingId = Binder.clearCallingIdentity(); 17187 try { 17188 if (sendNow) { 17189 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 17190 sendPackageChangedBroadcast(packageName, 17191 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 17192 } 17193 } finally { 17194 Binder.restoreCallingIdentity(callingId); 17195 } 17196 } 17197 17198 @Override 17199 public void flushPackageRestrictionsAsUser(int userId) { 17200 if (!sUserManager.exists(userId)) { 17201 return; 17202 } 17203 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 17204 false /* checkShell */, "flushPackageRestrictions"); 17205 synchronized (mPackages) { 17206 mSettings.writePackageRestrictionsLPr(userId); 17207 mDirtyUsers.remove(userId); 17208 if (mDirtyUsers.isEmpty()) { 17209 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 17210 } 17211 } 17212 } 17213 17214 private void sendPackageChangedBroadcast(String packageName, 17215 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 17216 if (DEBUG_INSTALL) 17217 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 17218 + componentNames); 17219 Bundle extras = new Bundle(4); 17220 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 17221 String nameList[] = new String[componentNames.size()]; 17222 componentNames.toArray(nameList); 17223 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 17224 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 17225 extras.putInt(Intent.EXTRA_UID, packageUid); 17226 // If this is not reporting a change of the overall package, then only send it 17227 // to registered receivers. We don't want to launch a swath of apps for every 17228 // little component state change. 17229 final int flags = !componentNames.contains(packageName) 17230 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 17231 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 17232 new int[] {UserHandle.getUserId(packageUid)}); 17233 } 17234 17235 @Override 17236 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 17237 if (!sUserManager.exists(userId)) return; 17238 final int uid = Binder.getCallingUid(); 17239 final int permission = mContext.checkCallingOrSelfPermission( 17240 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17241 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17242 enforceCrossUserPermission(uid, userId, 17243 true /* requireFullPermission */, true /* checkShell */, "stop package"); 17244 // writer 17245 synchronized (mPackages) { 17246 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 17247 allowedByPermission, uid, userId)) { 17248 scheduleWritePackageRestrictionsLocked(userId); 17249 } 17250 } 17251 } 17252 17253 @Override 17254 public String getInstallerPackageName(String packageName) { 17255 // reader 17256 synchronized (mPackages) { 17257 return mSettings.getInstallerPackageNameLPr(packageName); 17258 } 17259 } 17260 17261 @Override 17262 public int getApplicationEnabledSetting(String packageName, int userId) { 17263 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17264 int uid = Binder.getCallingUid(); 17265 enforceCrossUserPermission(uid, userId, 17266 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 17267 // reader 17268 synchronized (mPackages) { 17269 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 17270 } 17271 } 17272 17273 @Override 17274 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 17275 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17276 int uid = Binder.getCallingUid(); 17277 enforceCrossUserPermission(uid, userId, 17278 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 17279 // reader 17280 synchronized (mPackages) { 17281 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 17282 } 17283 } 17284 17285 @Override 17286 public void enterSafeMode() { 17287 enforceSystemOrRoot("Only the system can request entering safe mode"); 17288 17289 if (!mSystemReady) { 17290 mSafeMode = true; 17291 } 17292 } 17293 17294 @Override 17295 public void systemReady() { 17296 mSystemReady = true; 17297 17298 // Read the compatibilty setting when the system is ready. 17299 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 17300 mContext.getContentResolver(), 17301 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 17302 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 17303 if (DEBUG_SETTINGS) { 17304 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 17305 } 17306 17307 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 17308 17309 synchronized (mPackages) { 17310 // Verify that all of the preferred activity components actually 17311 // exist. It is possible for applications to be updated and at 17312 // that point remove a previously declared activity component that 17313 // had been set as a preferred activity. We try to clean this up 17314 // the next time we encounter that preferred activity, but it is 17315 // possible for the user flow to never be able to return to that 17316 // situation so here we do a sanity check to make sure we haven't 17317 // left any junk around. 17318 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 17319 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17320 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17321 removed.clear(); 17322 for (PreferredActivity pa : pir.filterSet()) { 17323 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 17324 removed.add(pa); 17325 } 17326 } 17327 if (removed.size() > 0) { 17328 for (int r=0; r<removed.size(); r++) { 17329 PreferredActivity pa = removed.get(r); 17330 Slog.w(TAG, "Removing dangling preferred activity: " 17331 + pa.mPref.mComponent); 17332 pir.removeFilter(pa); 17333 } 17334 mSettings.writePackageRestrictionsLPr( 17335 mSettings.mPreferredActivities.keyAt(i)); 17336 } 17337 } 17338 17339 for (int userId : UserManagerService.getInstance().getUserIds()) { 17340 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 17341 grantPermissionsUserIds = ArrayUtils.appendInt( 17342 grantPermissionsUserIds, userId); 17343 } 17344 } 17345 } 17346 sUserManager.systemReady(); 17347 17348 // If we upgraded grant all default permissions before kicking off. 17349 for (int userId : grantPermissionsUserIds) { 17350 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 17351 } 17352 17353 // Kick off any messages waiting for system ready 17354 if (mPostSystemReadyMessages != null) { 17355 for (Message msg : mPostSystemReadyMessages) { 17356 msg.sendToTarget(); 17357 } 17358 mPostSystemReadyMessages = null; 17359 } 17360 17361 // Watch for external volumes that come and go over time 17362 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17363 storage.registerListener(mStorageListener); 17364 17365 mInstallerService.systemReady(); 17366 mPackageDexOptimizer.systemReady(); 17367 17368 MountServiceInternal mountServiceInternal = LocalServices.getService( 17369 MountServiceInternal.class); 17370 mountServiceInternal.addExternalStoragePolicy( 17371 new MountServiceInternal.ExternalStorageMountPolicy() { 17372 @Override 17373 public int getMountMode(int uid, String packageName) { 17374 if (Process.isIsolated(uid)) { 17375 return Zygote.MOUNT_EXTERNAL_NONE; 17376 } 17377 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 17378 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17379 } 17380 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17381 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17382 } 17383 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17384 return Zygote.MOUNT_EXTERNAL_READ; 17385 } 17386 return Zygote.MOUNT_EXTERNAL_WRITE; 17387 } 17388 17389 @Override 17390 public boolean hasExternalStorage(int uid, String packageName) { 17391 return true; 17392 } 17393 }); 17394 } 17395 17396 @Override 17397 public boolean isSafeMode() { 17398 return mSafeMode; 17399 } 17400 17401 @Override 17402 public boolean hasSystemUidErrors() { 17403 return mHasSystemUidErrors; 17404 } 17405 17406 static String arrayToString(int[] array) { 17407 StringBuffer buf = new StringBuffer(128); 17408 buf.append('['); 17409 if (array != null) { 17410 for (int i=0; i<array.length; i++) { 17411 if (i > 0) buf.append(", "); 17412 buf.append(array[i]); 17413 } 17414 } 17415 buf.append(']'); 17416 return buf.toString(); 17417 } 17418 17419 static class DumpState { 17420 public static final int DUMP_LIBS = 1 << 0; 17421 public static final int DUMP_FEATURES = 1 << 1; 17422 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 17423 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 17424 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 17425 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 17426 public static final int DUMP_PERMISSIONS = 1 << 6; 17427 public static final int DUMP_PACKAGES = 1 << 7; 17428 public static final int DUMP_SHARED_USERS = 1 << 8; 17429 public static final int DUMP_MESSAGES = 1 << 9; 17430 public static final int DUMP_PROVIDERS = 1 << 10; 17431 public static final int DUMP_VERIFIERS = 1 << 11; 17432 public static final int DUMP_PREFERRED = 1 << 12; 17433 public static final int DUMP_PREFERRED_XML = 1 << 13; 17434 public static final int DUMP_KEYSETS = 1 << 14; 17435 public static final int DUMP_VERSION = 1 << 15; 17436 public static final int DUMP_INSTALLS = 1 << 16; 17437 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 17438 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 17439 public static final int DUMP_FROZEN = 1 << 19; 17440 17441 public static final int OPTION_SHOW_FILTERS = 1 << 0; 17442 17443 private int mTypes; 17444 17445 private int mOptions; 17446 17447 private boolean mTitlePrinted; 17448 17449 private SharedUserSetting mSharedUser; 17450 17451 public boolean isDumping(int type) { 17452 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 17453 return true; 17454 } 17455 17456 return (mTypes & type) != 0; 17457 } 17458 17459 public void setDump(int type) { 17460 mTypes |= type; 17461 } 17462 17463 public boolean isOptionEnabled(int option) { 17464 return (mOptions & option) != 0; 17465 } 17466 17467 public void setOptionEnabled(int option) { 17468 mOptions |= option; 17469 } 17470 17471 public boolean onTitlePrinted() { 17472 final boolean printed = mTitlePrinted; 17473 mTitlePrinted = true; 17474 return printed; 17475 } 17476 17477 public boolean getTitlePrinted() { 17478 return mTitlePrinted; 17479 } 17480 17481 public void setTitlePrinted(boolean enabled) { 17482 mTitlePrinted = enabled; 17483 } 17484 17485 public SharedUserSetting getSharedUser() { 17486 return mSharedUser; 17487 } 17488 17489 public void setSharedUser(SharedUserSetting user) { 17490 mSharedUser = user; 17491 } 17492 } 17493 17494 @Override 17495 public void onShellCommand(FileDescriptor in, FileDescriptor out, 17496 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 17497 (new PackageManagerShellCommand(this)).exec( 17498 this, in, out, err, args, resultReceiver); 17499 } 17500 17501 @Override 17502 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 17503 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 17504 != PackageManager.PERMISSION_GRANTED) { 17505 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 17506 + Binder.getCallingPid() 17507 + ", uid=" + Binder.getCallingUid() 17508 + " without permission " 17509 + android.Manifest.permission.DUMP); 17510 return; 17511 } 17512 17513 DumpState dumpState = new DumpState(); 17514 boolean fullPreferred = false; 17515 boolean checkin = false; 17516 17517 String packageName = null; 17518 ArraySet<String> permissionNames = null; 17519 17520 int opti = 0; 17521 while (opti < args.length) { 17522 String opt = args[opti]; 17523 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 17524 break; 17525 } 17526 opti++; 17527 17528 if ("-a".equals(opt)) { 17529 // Right now we only know how to print all. 17530 } else if ("-h".equals(opt)) { 17531 pw.println("Package manager dump options:"); 17532 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 17533 pw.println(" --checkin: dump for a checkin"); 17534 pw.println(" -f: print details of intent filters"); 17535 pw.println(" -h: print this help"); 17536 pw.println(" cmd may be one of:"); 17537 pw.println(" l[ibraries]: list known shared libraries"); 17538 pw.println(" f[eatures]: list device features"); 17539 pw.println(" k[eysets]: print known keysets"); 17540 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 17541 pw.println(" perm[issions]: dump permissions"); 17542 pw.println(" permission [name ...]: dump declaration and use of given permission"); 17543 pw.println(" pref[erred]: print preferred package settings"); 17544 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 17545 pw.println(" prov[iders]: dump content providers"); 17546 pw.println(" p[ackages]: dump installed packages"); 17547 pw.println(" s[hared-users]: dump shared user IDs"); 17548 pw.println(" m[essages]: print collected runtime messages"); 17549 pw.println(" v[erifiers]: print package verifier info"); 17550 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 17551 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 17552 pw.println(" version: print database version info"); 17553 pw.println(" write: write current settings now"); 17554 pw.println(" installs: details about install sessions"); 17555 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 17556 pw.println(" <package.name>: info about given package"); 17557 return; 17558 } else if ("--checkin".equals(opt)) { 17559 checkin = true; 17560 } else if ("-f".equals(opt)) { 17561 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 17562 } else { 17563 pw.println("Unknown argument: " + opt + "; use -h for help"); 17564 } 17565 } 17566 17567 // Is the caller requesting to dump a particular piece of data? 17568 if (opti < args.length) { 17569 String cmd = args[opti]; 17570 opti++; 17571 // Is this a package name? 17572 if ("android".equals(cmd) || cmd.contains(".")) { 17573 packageName = cmd; 17574 // When dumping a single package, we always dump all of its 17575 // filter information since the amount of data will be reasonable. 17576 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 17577 } else if ("check-permission".equals(cmd)) { 17578 if (opti >= args.length) { 17579 pw.println("Error: check-permission missing permission argument"); 17580 return; 17581 } 17582 String perm = args[opti]; 17583 opti++; 17584 if (opti >= args.length) { 17585 pw.println("Error: check-permission missing package argument"); 17586 return; 17587 } 17588 String pkg = args[opti]; 17589 opti++; 17590 int user = UserHandle.getUserId(Binder.getCallingUid()); 17591 if (opti < args.length) { 17592 try { 17593 user = Integer.parseInt(args[opti]); 17594 } catch (NumberFormatException e) { 17595 pw.println("Error: check-permission user argument is not a number: " 17596 + args[opti]); 17597 return; 17598 } 17599 } 17600 pw.println(checkPermission(perm, pkg, user)); 17601 return; 17602 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 17603 dumpState.setDump(DumpState.DUMP_LIBS); 17604 } else if ("f".equals(cmd) || "features".equals(cmd)) { 17605 dumpState.setDump(DumpState.DUMP_FEATURES); 17606 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 17607 if (opti >= args.length) { 17608 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 17609 | DumpState.DUMP_SERVICE_RESOLVERS 17610 | DumpState.DUMP_RECEIVER_RESOLVERS 17611 | DumpState.DUMP_CONTENT_RESOLVERS); 17612 } else { 17613 while (opti < args.length) { 17614 String name = args[opti]; 17615 if ("a".equals(name) || "activity".equals(name)) { 17616 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 17617 } else if ("s".equals(name) || "service".equals(name)) { 17618 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 17619 } else if ("r".equals(name) || "receiver".equals(name)) { 17620 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 17621 } else if ("c".equals(name) || "content".equals(name)) { 17622 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 17623 } else { 17624 pw.println("Error: unknown resolver table type: " + name); 17625 return; 17626 } 17627 opti++; 17628 } 17629 } 17630 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 17631 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 17632 } else if ("permission".equals(cmd)) { 17633 if (opti >= args.length) { 17634 pw.println("Error: permission requires permission name"); 17635 return; 17636 } 17637 permissionNames = new ArraySet<>(); 17638 while (opti < args.length) { 17639 permissionNames.add(args[opti]); 17640 opti++; 17641 } 17642 dumpState.setDump(DumpState.DUMP_PERMISSIONS 17643 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 17644 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 17645 dumpState.setDump(DumpState.DUMP_PREFERRED); 17646 } else if ("preferred-xml".equals(cmd)) { 17647 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 17648 if (opti < args.length && "--full".equals(args[opti])) { 17649 fullPreferred = true; 17650 opti++; 17651 } 17652 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 17653 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 17654 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 17655 dumpState.setDump(DumpState.DUMP_PACKAGES); 17656 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 17657 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 17658 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 17659 dumpState.setDump(DumpState.DUMP_PROVIDERS); 17660 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 17661 dumpState.setDump(DumpState.DUMP_MESSAGES); 17662 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 17663 dumpState.setDump(DumpState.DUMP_VERIFIERS); 17664 } else if ("i".equals(cmd) || "ifv".equals(cmd) 17665 || "intent-filter-verifiers".equals(cmd)) { 17666 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 17667 } else if ("version".equals(cmd)) { 17668 dumpState.setDump(DumpState.DUMP_VERSION); 17669 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 17670 dumpState.setDump(DumpState.DUMP_KEYSETS); 17671 } else if ("installs".equals(cmd)) { 17672 dumpState.setDump(DumpState.DUMP_INSTALLS); 17673 } else if ("frozen".equals(cmd)) { 17674 dumpState.setDump(DumpState.DUMP_FROZEN); 17675 } else if ("write".equals(cmd)) { 17676 synchronized (mPackages) { 17677 mSettings.writeLPr(); 17678 pw.println("Settings written."); 17679 return; 17680 } 17681 } 17682 } 17683 17684 if (checkin) { 17685 pw.println("vers,1"); 17686 } 17687 17688 // reader 17689 synchronized (mPackages) { 17690 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 17691 if (!checkin) { 17692 if (dumpState.onTitlePrinted()) 17693 pw.println(); 17694 pw.println("Database versions:"); 17695 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 17696 } 17697 } 17698 17699 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 17700 if (!checkin) { 17701 if (dumpState.onTitlePrinted()) 17702 pw.println(); 17703 pw.println("Verifiers:"); 17704 pw.print(" Required: "); 17705 pw.print(mRequiredVerifierPackage); 17706 pw.print(" (uid="); 17707 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 17708 UserHandle.USER_SYSTEM)); 17709 pw.println(")"); 17710 } else if (mRequiredVerifierPackage != null) { 17711 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 17712 pw.print(","); 17713 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 17714 UserHandle.USER_SYSTEM)); 17715 } 17716 } 17717 17718 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 17719 packageName == null) { 17720 if (mIntentFilterVerifierComponent != null) { 17721 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 17722 if (!checkin) { 17723 if (dumpState.onTitlePrinted()) 17724 pw.println(); 17725 pw.println("Intent Filter Verifier:"); 17726 pw.print(" Using: "); 17727 pw.print(verifierPackageName); 17728 pw.print(" (uid="); 17729 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 17730 UserHandle.USER_SYSTEM)); 17731 pw.println(")"); 17732 } else if (verifierPackageName != null) { 17733 pw.print("ifv,"); pw.print(verifierPackageName); 17734 pw.print(","); 17735 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 17736 UserHandle.USER_SYSTEM)); 17737 } 17738 } else { 17739 pw.println(); 17740 pw.println("No Intent Filter Verifier available!"); 17741 } 17742 } 17743 17744 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 17745 boolean printedHeader = false; 17746 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 17747 while (it.hasNext()) { 17748 String name = it.next(); 17749 SharedLibraryEntry ent = mSharedLibraries.get(name); 17750 if (!checkin) { 17751 if (!printedHeader) { 17752 if (dumpState.onTitlePrinted()) 17753 pw.println(); 17754 pw.println("Libraries:"); 17755 printedHeader = true; 17756 } 17757 pw.print(" "); 17758 } else { 17759 pw.print("lib,"); 17760 } 17761 pw.print(name); 17762 if (!checkin) { 17763 pw.print(" -> "); 17764 } 17765 if (ent.path != null) { 17766 if (!checkin) { 17767 pw.print("(jar) "); 17768 pw.print(ent.path); 17769 } else { 17770 pw.print(",jar,"); 17771 pw.print(ent.path); 17772 } 17773 } else { 17774 if (!checkin) { 17775 pw.print("(apk) "); 17776 pw.print(ent.apk); 17777 } else { 17778 pw.print(",apk,"); 17779 pw.print(ent.apk); 17780 } 17781 } 17782 pw.println(); 17783 } 17784 } 17785 17786 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 17787 if (dumpState.onTitlePrinted()) 17788 pw.println(); 17789 if (!checkin) { 17790 pw.println("Features:"); 17791 } 17792 17793 for (FeatureInfo feat : mAvailableFeatures.values()) { 17794 if (checkin) { 17795 pw.print("feat,"); 17796 pw.print(feat.name); 17797 pw.print(","); 17798 pw.println(feat.version); 17799 } else { 17800 pw.print(" "); 17801 pw.print(feat.name); 17802 if (feat.version > 0) { 17803 pw.print(" version="); 17804 pw.print(feat.version); 17805 } 17806 pw.println(); 17807 } 17808 } 17809 } 17810 17811 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 17812 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 17813 : "Activity Resolver Table:", " ", packageName, 17814 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17815 dumpState.setTitlePrinted(true); 17816 } 17817 } 17818 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 17819 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 17820 : "Receiver Resolver Table:", " ", packageName, 17821 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17822 dumpState.setTitlePrinted(true); 17823 } 17824 } 17825 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 17826 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 17827 : "Service Resolver Table:", " ", packageName, 17828 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17829 dumpState.setTitlePrinted(true); 17830 } 17831 } 17832 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 17833 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 17834 : "Provider Resolver Table:", " ", packageName, 17835 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17836 dumpState.setTitlePrinted(true); 17837 } 17838 } 17839 17840 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 17841 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17842 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17843 int user = mSettings.mPreferredActivities.keyAt(i); 17844 if (pir.dump(pw, 17845 dumpState.getTitlePrinted() 17846 ? "\nPreferred Activities User " + user + ":" 17847 : "Preferred Activities User " + user + ":", " ", 17848 packageName, true, false)) { 17849 dumpState.setTitlePrinted(true); 17850 } 17851 } 17852 } 17853 17854 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 17855 pw.flush(); 17856 FileOutputStream fout = new FileOutputStream(fd); 17857 BufferedOutputStream str = new BufferedOutputStream(fout); 17858 XmlSerializer serializer = new FastXmlSerializer(); 17859 try { 17860 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 17861 serializer.startDocument(null, true); 17862 serializer.setFeature( 17863 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 17864 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 17865 serializer.endDocument(); 17866 serializer.flush(); 17867 } catch (IllegalArgumentException e) { 17868 pw.println("Failed writing: " + e); 17869 } catch (IllegalStateException e) { 17870 pw.println("Failed writing: " + e); 17871 } catch (IOException e) { 17872 pw.println("Failed writing: " + e); 17873 } 17874 } 17875 17876 if (!checkin 17877 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 17878 && packageName == null) { 17879 pw.println(); 17880 int count = mSettings.mPackages.size(); 17881 if (count == 0) { 17882 pw.println("No applications!"); 17883 pw.println(); 17884 } else { 17885 final String prefix = " "; 17886 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 17887 if (allPackageSettings.size() == 0) { 17888 pw.println("No domain preferred apps!"); 17889 pw.println(); 17890 } else { 17891 pw.println("App verification status:"); 17892 pw.println(); 17893 count = 0; 17894 for (PackageSetting ps : allPackageSettings) { 17895 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 17896 if (ivi == null || ivi.getPackageName() == null) continue; 17897 pw.println(prefix + "Package: " + ivi.getPackageName()); 17898 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 17899 pw.println(prefix + "Status: " + ivi.getStatusString()); 17900 pw.println(); 17901 count++; 17902 } 17903 if (count == 0) { 17904 pw.println(prefix + "No app verification established."); 17905 pw.println(); 17906 } 17907 for (int userId : sUserManager.getUserIds()) { 17908 pw.println("App linkages for user " + userId + ":"); 17909 pw.println(); 17910 count = 0; 17911 for (PackageSetting ps : allPackageSettings) { 17912 final long status = ps.getDomainVerificationStatusForUser(userId); 17913 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 17914 continue; 17915 } 17916 pw.println(prefix + "Package: " + ps.name); 17917 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 17918 String statusStr = IntentFilterVerificationInfo. 17919 getStatusStringFromValue(status); 17920 pw.println(prefix + "Status: " + statusStr); 17921 pw.println(); 17922 count++; 17923 } 17924 if (count == 0) { 17925 pw.println(prefix + "No configured app linkages."); 17926 pw.println(); 17927 } 17928 } 17929 } 17930 } 17931 } 17932 17933 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 17934 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 17935 if (packageName == null && permissionNames == null) { 17936 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 17937 if (iperm == 0) { 17938 if (dumpState.onTitlePrinted()) 17939 pw.println(); 17940 pw.println("AppOp Permissions:"); 17941 } 17942 pw.print(" AppOp Permission "); 17943 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 17944 pw.println(":"); 17945 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 17946 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 17947 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 17948 } 17949 } 17950 } 17951 } 17952 17953 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 17954 boolean printedSomething = false; 17955 for (PackageParser.Provider p : mProviders.mProviders.values()) { 17956 if (packageName != null && !packageName.equals(p.info.packageName)) { 17957 continue; 17958 } 17959 if (!printedSomething) { 17960 if (dumpState.onTitlePrinted()) 17961 pw.println(); 17962 pw.println("Registered ContentProviders:"); 17963 printedSomething = true; 17964 } 17965 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 17966 pw.print(" "); pw.println(p.toString()); 17967 } 17968 printedSomething = false; 17969 for (Map.Entry<String, PackageParser.Provider> entry : 17970 mProvidersByAuthority.entrySet()) { 17971 PackageParser.Provider p = entry.getValue(); 17972 if (packageName != null && !packageName.equals(p.info.packageName)) { 17973 continue; 17974 } 17975 if (!printedSomething) { 17976 if (dumpState.onTitlePrinted()) 17977 pw.println(); 17978 pw.println("ContentProvider Authorities:"); 17979 printedSomething = true; 17980 } 17981 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 17982 pw.print(" "); pw.println(p.toString()); 17983 if (p.info != null && p.info.applicationInfo != null) { 17984 final String appInfo = p.info.applicationInfo.toString(); 17985 pw.print(" applicationInfo="); pw.println(appInfo); 17986 } 17987 } 17988 } 17989 17990 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 17991 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 17992 } 17993 17994 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 17995 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 17996 } 17997 17998 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 17999 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 18000 } 18001 18002 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 18003 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 18004 } 18005 18006 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 18007 // XXX should handle packageName != null by dumping only install data that 18008 // the given package is involved with. 18009 if (dumpState.onTitlePrinted()) pw.println(); 18010 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 18011 } 18012 18013 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 18014 // XXX should handle packageName != null by dumping only install data that 18015 // the given package is involved with. 18016 if (dumpState.onTitlePrinted()) pw.println(); 18017 18018 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18019 ipw.println(); 18020 ipw.println("Frozen packages:"); 18021 ipw.increaseIndent(); 18022 if (mFrozenPackages.size() == 0) { 18023 ipw.println("(none)"); 18024 } else { 18025 for (int i = 0; i < mFrozenPackages.size(); i++) { 18026 ipw.println(mFrozenPackages.valueAt(i)); 18027 } 18028 } 18029 ipw.decreaseIndent(); 18030 } 18031 18032 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 18033 if (dumpState.onTitlePrinted()) pw.println(); 18034 mSettings.dumpReadMessagesLPr(pw, dumpState); 18035 18036 pw.println(); 18037 pw.println("Package warning messages:"); 18038 BufferedReader in = null; 18039 String line = null; 18040 try { 18041 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18042 while ((line = in.readLine()) != null) { 18043 if (line.contains("ignored: updated version")) continue; 18044 pw.println(line); 18045 } 18046 } catch (IOException ignored) { 18047 } finally { 18048 IoUtils.closeQuietly(in); 18049 } 18050 } 18051 18052 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 18053 BufferedReader in = null; 18054 String line = null; 18055 try { 18056 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18057 while ((line = in.readLine()) != null) { 18058 if (line.contains("ignored: updated version")) continue; 18059 pw.print("msg,"); 18060 pw.println(line); 18061 } 18062 } catch (IOException ignored) { 18063 } finally { 18064 IoUtils.closeQuietly(in); 18065 } 18066 } 18067 } 18068 } 18069 18070 private String dumpDomainString(String packageName) { 18071 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 18072 .getList(); 18073 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 18074 18075 ArraySet<String> result = new ArraySet<>(); 18076 if (iviList.size() > 0) { 18077 for (IntentFilterVerificationInfo ivi : iviList) { 18078 for (String host : ivi.getDomains()) { 18079 result.add(host); 18080 } 18081 } 18082 } 18083 if (filters != null && filters.size() > 0) { 18084 for (IntentFilter filter : filters) { 18085 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 18086 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 18087 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 18088 result.addAll(filter.getHostsList()); 18089 } 18090 } 18091 } 18092 18093 StringBuilder sb = new StringBuilder(result.size() * 16); 18094 for (String domain : result) { 18095 if (sb.length() > 0) sb.append(" "); 18096 sb.append(domain); 18097 } 18098 return sb.toString(); 18099 } 18100 18101 // ------- apps on sdcard specific code ------- 18102 static final boolean DEBUG_SD_INSTALL = false; 18103 18104 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 18105 18106 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 18107 18108 private boolean mMediaMounted = false; 18109 18110 static String getEncryptKey() { 18111 try { 18112 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 18113 SD_ENCRYPTION_KEYSTORE_NAME); 18114 if (sdEncKey == null) { 18115 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 18116 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 18117 if (sdEncKey == null) { 18118 Slog.e(TAG, "Failed to create encryption keys"); 18119 return null; 18120 } 18121 } 18122 return sdEncKey; 18123 } catch (NoSuchAlgorithmException nsae) { 18124 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 18125 return null; 18126 } catch (IOException ioe) { 18127 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 18128 return null; 18129 } 18130 } 18131 18132 /* 18133 * Update media status on PackageManager. 18134 */ 18135 @Override 18136 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 18137 int callingUid = Binder.getCallingUid(); 18138 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 18139 throw new SecurityException("Media status can only be updated by the system"); 18140 } 18141 // reader; this apparently protects mMediaMounted, but should probably 18142 // be a different lock in that case. 18143 synchronized (mPackages) { 18144 Log.i(TAG, "Updating external media status from " 18145 + (mMediaMounted ? "mounted" : "unmounted") + " to " 18146 + (mediaStatus ? "mounted" : "unmounted")); 18147 if (DEBUG_SD_INSTALL) 18148 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 18149 + ", mMediaMounted=" + mMediaMounted); 18150 if (mediaStatus == mMediaMounted) { 18151 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 18152 : 0, -1); 18153 mHandler.sendMessage(msg); 18154 return; 18155 } 18156 mMediaMounted = mediaStatus; 18157 } 18158 // Queue up an async operation since the package installation may take a 18159 // little while. 18160 mHandler.post(new Runnable() { 18161 public void run() { 18162 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 18163 } 18164 }); 18165 } 18166 18167 /** 18168 * Called by MountService when the initial ASECs to scan are available. 18169 * Should block until all the ASEC containers are finished being scanned. 18170 */ 18171 public void scanAvailableAsecs() { 18172 updateExternalMediaStatusInner(true, false, false); 18173 } 18174 18175 /* 18176 * Collect information of applications on external media, map them against 18177 * existing containers and update information based on current mount status. 18178 * Please note that we always have to report status if reportStatus has been 18179 * set to true especially when unloading packages. 18180 */ 18181 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 18182 boolean externalStorage) { 18183 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 18184 int[] uidArr = EmptyArray.INT; 18185 18186 final String[] list = PackageHelper.getSecureContainerList(); 18187 if (ArrayUtils.isEmpty(list)) { 18188 Log.i(TAG, "No secure containers found"); 18189 } else { 18190 // Process list of secure containers and categorize them 18191 // as active or stale based on their package internal state. 18192 18193 // reader 18194 synchronized (mPackages) { 18195 for (String cid : list) { 18196 // Leave stages untouched for now; installer service owns them 18197 if (PackageInstallerService.isStageName(cid)) continue; 18198 18199 if (DEBUG_SD_INSTALL) 18200 Log.i(TAG, "Processing container " + cid); 18201 String pkgName = getAsecPackageName(cid); 18202 if (pkgName == null) { 18203 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 18204 continue; 18205 } 18206 if (DEBUG_SD_INSTALL) 18207 Log.i(TAG, "Looking for pkg : " + pkgName); 18208 18209 final PackageSetting ps = mSettings.mPackages.get(pkgName); 18210 if (ps == null) { 18211 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 18212 continue; 18213 } 18214 18215 /* 18216 * Skip packages that are not external if we're unmounting 18217 * external storage. 18218 */ 18219 if (externalStorage && !isMounted && !isExternal(ps)) { 18220 continue; 18221 } 18222 18223 final AsecInstallArgs args = new AsecInstallArgs(cid, 18224 getAppDexInstructionSets(ps), ps.isForwardLocked()); 18225 // The package status is changed only if the code path 18226 // matches between settings and the container id. 18227 if (ps.codePathString != null 18228 && ps.codePathString.startsWith(args.getCodePath())) { 18229 if (DEBUG_SD_INSTALL) { 18230 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 18231 + " at code path: " + ps.codePathString); 18232 } 18233 18234 // We do have a valid package installed on sdcard 18235 processCids.put(args, ps.codePathString); 18236 final int uid = ps.appId; 18237 if (uid != -1) { 18238 uidArr = ArrayUtils.appendInt(uidArr, uid); 18239 } 18240 } else { 18241 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 18242 + ps.codePathString); 18243 } 18244 } 18245 } 18246 18247 Arrays.sort(uidArr); 18248 } 18249 18250 // Process packages with valid entries. 18251 if (isMounted) { 18252 if (DEBUG_SD_INSTALL) 18253 Log.i(TAG, "Loading packages"); 18254 loadMediaPackages(processCids, uidArr, externalStorage); 18255 startCleaningPackages(); 18256 mInstallerService.onSecureContainersAvailable(); 18257 } else { 18258 if (DEBUG_SD_INSTALL) 18259 Log.i(TAG, "Unloading packages"); 18260 unloadMediaPackages(processCids, uidArr, reportStatus); 18261 } 18262 } 18263 18264 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18265 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 18266 final int size = infos.size(); 18267 final String[] packageNames = new String[size]; 18268 final int[] packageUids = new int[size]; 18269 for (int i = 0; i < size; i++) { 18270 final ApplicationInfo info = infos.get(i); 18271 packageNames[i] = info.packageName; 18272 packageUids[i] = info.uid; 18273 } 18274 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 18275 finishedReceiver); 18276 } 18277 18278 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18279 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18280 sendResourcesChangedBroadcast(mediaStatus, replacing, 18281 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 18282 } 18283 18284 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18285 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18286 int size = pkgList.length; 18287 if (size > 0) { 18288 // Send broadcasts here 18289 Bundle extras = new Bundle(); 18290 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 18291 if (uidArr != null) { 18292 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 18293 } 18294 if (replacing) { 18295 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 18296 } 18297 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 18298 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 18299 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 18300 } 18301 } 18302 18303 /* 18304 * Look at potentially valid container ids from processCids If package 18305 * information doesn't match the one on record or package scanning fails, 18306 * the cid is added to list of removeCids. We currently don't delete stale 18307 * containers. 18308 */ 18309 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 18310 boolean externalStorage) { 18311 ArrayList<String> pkgList = new ArrayList<String>(); 18312 Set<AsecInstallArgs> keys = processCids.keySet(); 18313 18314 for (AsecInstallArgs args : keys) { 18315 String codePath = processCids.get(args); 18316 if (DEBUG_SD_INSTALL) 18317 Log.i(TAG, "Loading container : " + args.cid); 18318 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 18319 try { 18320 // Make sure there are no container errors first. 18321 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 18322 Slog.e(TAG, "Failed to mount cid : " + args.cid 18323 + " when installing from sdcard"); 18324 continue; 18325 } 18326 // Check code path here. 18327 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 18328 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 18329 + " does not match one in settings " + codePath); 18330 continue; 18331 } 18332 // Parse package 18333 int parseFlags = mDefParseFlags; 18334 if (args.isExternalAsec()) { 18335 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 18336 } 18337 if (args.isFwdLocked()) { 18338 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 18339 } 18340 18341 synchronized (mInstallLock) { 18342 PackageParser.Package pkg = null; 18343 try { 18344 // Sadly we don't know the package name yet to freeze it 18345 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 18346 SCAN_IGNORE_FROZEN, 0, null); 18347 } catch (PackageManagerException e) { 18348 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 18349 } 18350 // Scan the package 18351 if (pkg != null) { 18352 /* 18353 * TODO why is the lock being held? doPostInstall is 18354 * called in other places without the lock. This needs 18355 * to be straightened out. 18356 */ 18357 // writer 18358 synchronized (mPackages) { 18359 retCode = PackageManager.INSTALL_SUCCEEDED; 18360 pkgList.add(pkg.packageName); 18361 // Post process args 18362 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 18363 pkg.applicationInfo.uid); 18364 } 18365 } else { 18366 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 18367 } 18368 } 18369 18370 } finally { 18371 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 18372 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 18373 } 18374 } 18375 } 18376 // writer 18377 synchronized (mPackages) { 18378 // If the platform SDK has changed since the last time we booted, 18379 // we need to re-grant app permission to catch any new ones that 18380 // appear. This is really a hack, and means that apps can in some 18381 // cases get permissions that the user didn't initially explicitly 18382 // allow... it would be nice to have some better way to handle 18383 // this situation. 18384 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 18385 : mSettings.getInternalVersion(); 18386 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 18387 : StorageManager.UUID_PRIVATE_INTERNAL; 18388 18389 int updateFlags = UPDATE_PERMISSIONS_ALL; 18390 if (ver.sdkVersion != mSdkVersion) { 18391 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 18392 + mSdkVersion + "; regranting permissions for external"); 18393 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 18394 } 18395 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 18396 18397 // Yay, everything is now upgraded 18398 ver.forceCurrent(); 18399 18400 // can downgrade to reader 18401 // Persist settings 18402 mSettings.writeLPr(); 18403 } 18404 // Send a broadcast to let everyone know we are done processing 18405 if (pkgList.size() > 0) { 18406 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 18407 } 18408 } 18409 18410 /* 18411 * Utility method to unload a list of specified containers 18412 */ 18413 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 18414 // Just unmount all valid containers. 18415 for (AsecInstallArgs arg : cidArgs) { 18416 synchronized (mInstallLock) { 18417 arg.doPostDeleteLI(false); 18418 } 18419 } 18420 } 18421 18422 /* 18423 * Unload packages mounted on external media. This involves deleting package 18424 * data from internal structures, sending broadcasts about disabled packages, 18425 * gc'ing to free up references, unmounting all secure containers 18426 * corresponding to packages on external media, and posting a 18427 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 18428 * that we always have to post this message if status has been requested no 18429 * matter what. 18430 */ 18431 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 18432 final boolean reportStatus) { 18433 if (DEBUG_SD_INSTALL) 18434 Log.i(TAG, "unloading media packages"); 18435 ArrayList<String> pkgList = new ArrayList<String>(); 18436 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 18437 final Set<AsecInstallArgs> keys = processCids.keySet(); 18438 for (AsecInstallArgs args : keys) { 18439 String pkgName = args.getPackageName(); 18440 if (DEBUG_SD_INSTALL) 18441 Log.i(TAG, "Trying to unload pkg : " + pkgName); 18442 // Delete package internally 18443 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 18444 synchronized (mInstallLock) { 18445 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 18446 final boolean res; 18447 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 18448 "unloadMediaPackages")) { 18449 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 18450 null); 18451 } 18452 if (res) { 18453 pkgList.add(pkgName); 18454 } else { 18455 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 18456 failedList.add(args); 18457 } 18458 } 18459 } 18460 18461 // reader 18462 synchronized (mPackages) { 18463 // We didn't update the settings after removing each package; 18464 // write them now for all packages. 18465 mSettings.writeLPr(); 18466 } 18467 18468 // We have to absolutely send UPDATED_MEDIA_STATUS only 18469 // after confirming that all the receivers processed the ordered 18470 // broadcast when packages get disabled, force a gc to clean things up. 18471 // and unload all the containers. 18472 if (pkgList.size() > 0) { 18473 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 18474 new IIntentReceiver.Stub() { 18475 public void performReceive(Intent intent, int resultCode, String data, 18476 Bundle extras, boolean ordered, boolean sticky, 18477 int sendingUser) throws RemoteException { 18478 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 18479 reportStatus ? 1 : 0, 1, keys); 18480 mHandler.sendMessage(msg); 18481 } 18482 }); 18483 } else { 18484 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 18485 keys); 18486 mHandler.sendMessage(msg); 18487 } 18488 } 18489 18490 private void loadPrivatePackages(final VolumeInfo vol) { 18491 mHandler.post(new Runnable() { 18492 @Override 18493 public void run() { 18494 loadPrivatePackagesInner(vol); 18495 } 18496 }); 18497 } 18498 18499 private void loadPrivatePackagesInner(VolumeInfo vol) { 18500 final String volumeUuid = vol.fsUuid; 18501 if (TextUtils.isEmpty(volumeUuid)) { 18502 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 18503 return; 18504 } 18505 18506 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 18507 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 18508 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 18509 18510 final VersionInfo ver; 18511 final List<PackageSetting> packages; 18512 synchronized (mPackages) { 18513 ver = mSettings.findOrCreateVersion(volumeUuid); 18514 packages = mSettings.getVolumePackagesLPr(volumeUuid); 18515 } 18516 18517 for (PackageSetting ps : packages) { 18518 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 18519 synchronized (mInstallLock) { 18520 final PackageParser.Package pkg; 18521 try { 18522 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 18523 loaded.add(pkg.applicationInfo); 18524 18525 } catch (PackageManagerException e) { 18526 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 18527 } 18528 18529 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 18530 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 18531 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 18532 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 18533 } 18534 } 18535 } 18536 18537 // Reconcile app data for all started/unlocked users 18538 final StorageManager sm = mContext.getSystemService(StorageManager.class); 18539 final UserManager um = mContext.getSystemService(UserManager.class); 18540 for (UserInfo user : um.getUsers()) { 18541 final int flags; 18542 if (um.isUserUnlocked(user.id)) { 18543 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18544 } else if (um.isUserRunning(user.id)) { 18545 flags = StorageManager.FLAG_STORAGE_DE; 18546 } else { 18547 continue; 18548 } 18549 18550 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 18551 synchronized (mInstallLock) { 18552 reconcileAppsDataLI(volumeUuid, user.id, flags); 18553 } 18554 } 18555 18556 synchronized (mPackages) { 18557 int updateFlags = UPDATE_PERMISSIONS_ALL; 18558 if (ver.sdkVersion != mSdkVersion) { 18559 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 18560 + mSdkVersion + "; regranting permissions for " + volumeUuid); 18561 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 18562 } 18563 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 18564 18565 // Yay, everything is now upgraded 18566 ver.forceCurrent(); 18567 18568 mSettings.writeLPr(); 18569 } 18570 18571 for (PackageFreezer freezer : freezers) { 18572 freezer.close(); 18573 } 18574 18575 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 18576 sendResourcesChangedBroadcast(true, false, loaded, null); 18577 } 18578 18579 private void unloadPrivatePackages(final VolumeInfo vol) { 18580 mHandler.post(new Runnable() { 18581 @Override 18582 public void run() { 18583 unloadPrivatePackagesInner(vol); 18584 } 18585 }); 18586 } 18587 18588 private void unloadPrivatePackagesInner(VolumeInfo vol) { 18589 final String volumeUuid = vol.fsUuid; 18590 if (TextUtils.isEmpty(volumeUuid)) { 18591 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 18592 return; 18593 } 18594 18595 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 18596 synchronized (mInstallLock) { 18597 synchronized (mPackages) { 18598 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 18599 for (PackageSetting ps : packages) { 18600 if (ps.pkg == null) continue; 18601 18602 final ApplicationInfo info = ps.pkg.applicationInfo; 18603 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 18604 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 18605 18606 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 18607 "unloadPrivatePackagesInner")) { 18608 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 18609 false, null)) { 18610 unloaded.add(info); 18611 } else { 18612 Slog.w(TAG, "Failed to unload " + ps.codePath); 18613 } 18614 } 18615 } 18616 18617 mSettings.writeLPr(); 18618 } 18619 } 18620 18621 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 18622 sendResourcesChangedBroadcast(false, false, unloaded, null); 18623 } 18624 18625 /** 18626 * Examine all users present on given mounted volume, and destroy data 18627 * belonging to users that are no longer valid, or whose user ID has been 18628 * recycled. 18629 */ 18630 private void reconcileUsers(String volumeUuid) { 18631 // TODO: also reconcile DE directories 18632 final File[] files = FileUtils 18633 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)); 18634 for (File file : files) { 18635 if (!file.isDirectory()) continue; 18636 18637 final int userId; 18638 final UserInfo info; 18639 try { 18640 userId = Integer.parseInt(file.getName()); 18641 info = sUserManager.getUserInfo(userId); 18642 } catch (NumberFormatException e) { 18643 Slog.w(TAG, "Invalid user directory " + file); 18644 continue; 18645 } 18646 18647 boolean destroyUser = false; 18648 if (info == null) { 18649 logCriticalInfo(Log.WARN, "Destroying user directory " + file 18650 + " because no matching user was found"); 18651 destroyUser = true; 18652 } else { 18653 try { 18654 UserManagerService.enforceSerialNumber(file, info.serialNumber); 18655 } catch (IOException e) { 18656 logCriticalInfo(Log.WARN, "Destroying user directory " + file 18657 + " because we failed to enforce serial number: " + e); 18658 destroyUser = true; 18659 } 18660 } 18661 18662 if (destroyUser) { 18663 synchronized (mInstallLock) { 18664 try { 18665 mInstaller.removeUserDataDirs(volumeUuid, userId); 18666 } catch (InstallerException e) { 18667 Slog.w(TAG, "Failed to clean up user dirs", e); 18668 } 18669 } 18670 } 18671 } 18672 } 18673 18674 private void assertPackageKnown(String volumeUuid, String packageName) 18675 throws PackageManagerException { 18676 synchronized (mPackages) { 18677 final PackageSetting ps = mSettings.mPackages.get(packageName); 18678 if (ps == null) { 18679 throw new PackageManagerException("Package " + packageName + " is unknown"); 18680 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 18681 throw new PackageManagerException( 18682 "Package " + packageName + " found on unknown volume " + volumeUuid 18683 + "; expected volume " + ps.volumeUuid); 18684 } 18685 } 18686 } 18687 18688 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 18689 throws PackageManagerException { 18690 synchronized (mPackages) { 18691 final PackageSetting ps = mSettings.mPackages.get(packageName); 18692 if (ps == null) { 18693 throw new PackageManagerException("Package " + packageName + " is unknown"); 18694 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 18695 throw new PackageManagerException( 18696 "Package " + packageName + " found on unknown volume " + volumeUuid 18697 + "; expected volume " + ps.volumeUuid); 18698 } else if (!ps.getInstalled(userId)) { 18699 throw new PackageManagerException( 18700 "Package " + packageName + " not installed for user " + userId); 18701 } 18702 } 18703 } 18704 18705 /** 18706 * Examine all apps present on given mounted volume, and destroy apps that 18707 * aren't expected, either due to uninstallation or reinstallation on 18708 * another volume. 18709 */ 18710 private void reconcileApps(String volumeUuid) { 18711 final File[] files = FileUtils 18712 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 18713 for (File file : files) { 18714 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 18715 && !PackageInstallerService.isStageName(file.getName()); 18716 if (!isPackage) { 18717 // Ignore entries which are not packages 18718 continue; 18719 } 18720 18721 try { 18722 final PackageLite pkg = PackageParser.parsePackageLite(file, 18723 PackageParser.PARSE_MUST_BE_APK); 18724 assertPackageKnown(volumeUuid, pkg.packageName); 18725 18726 } catch (PackageParserException | PackageManagerException e) { 18727 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 18728 synchronized (mInstallLock) { 18729 removeCodePathLI(file); 18730 } 18731 } 18732 } 18733 } 18734 18735 /** 18736 * Reconcile all app data for the given user. 18737 * <p> 18738 * Verifies that directories exist and that ownership and labeling is 18739 * correct for all installed apps on all mounted volumes. 18740 */ 18741 void reconcileAppsData(int userId, int flags) { 18742 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18743 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 18744 final String volumeUuid = vol.getFsUuid(); 18745 synchronized (mInstallLock) { 18746 reconcileAppsDataLI(volumeUuid, userId, flags); 18747 } 18748 } 18749 } 18750 18751 /** 18752 * Reconcile all app data on given mounted volume. 18753 * <p> 18754 * Destroys app data that isn't expected, either due to uninstallation or 18755 * reinstallation on another volume. 18756 * <p> 18757 * Verifies that directories exist and that ownership and labeling is 18758 * correct for all installed apps. 18759 */ 18760 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) { 18761 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 18762 + Integer.toHexString(flags)); 18763 18764 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 18765 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 18766 18767 boolean restoreconNeeded = false; 18768 18769 // First look for stale data that doesn't belong, and check if things 18770 // have changed since we did our last restorecon 18771 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18772 if (!isUserKeyUnlocked(userId)) { 18773 throw new RuntimeException( 18774 "Yikes, someone asked us to reconcile CE storage while " + userId 18775 + " was still locked; this would have caused massive data loss!"); 18776 } 18777 18778 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 18779 18780 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 18781 for (File file : files) { 18782 final String packageName = file.getName(); 18783 try { 18784 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 18785 } catch (PackageManagerException e) { 18786 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 18787 try { 18788 mInstaller.destroyAppData(volumeUuid, packageName, userId, 18789 StorageManager.FLAG_STORAGE_CE, 0); 18790 } catch (InstallerException e2) { 18791 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 18792 } 18793 } 18794 } 18795 } 18796 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 18797 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 18798 18799 final File[] files = FileUtils.listFilesOrEmpty(deDir); 18800 for (File file : files) { 18801 final String packageName = file.getName(); 18802 try { 18803 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 18804 } catch (PackageManagerException e) { 18805 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 18806 try { 18807 mInstaller.destroyAppData(volumeUuid, packageName, userId, 18808 StorageManager.FLAG_STORAGE_DE, 0); 18809 } catch (InstallerException e2) { 18810 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 18811 } 18812 } 18813 } 18814 } 18815 18816 // Ensure that data directories are ready to roll for all packages 18817 // installed for this volume and user 18818 final List<PackageSetting> packages; 18819 synchronized (mPackages) { 18820 packages = mSettings.getVolumePackagesLPr(volumeUuid); 18821 } 18822 int preparedCount = 0; 18823 for (PackageSetting ps : packages) { 18824 final String packageName = ps.name; 18825 if (ps.pkg == null) { 18826 Slog.w(TAG, "Odd, missing scanned package " + packageName); 18827 // TODO: might be due to legacy ASEC apps; we should circle back 18828 // and reconcile again once they're scanned 18829 continue; 18830 } 18831 18832 if (ps.getInstalled(userId)) { 18833 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 18834 18835 if (maybeMigrateAppDataLIF(ps.pkg, userId)) { 18836 // We may have just shuffled around app data directories, so 18837 // prepare them one more time 18838 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 18839 } 18840 18841 preparedCount++; 18842 } 18843 } 18844 18845 if (restoreconNeeded) { 18846 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18847 SELinuxMMAC.setRestoreconDone(ceDir); 18848 } 18849 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 18850 SELinuxMMAC.setRestoreconDone(deDir); 18851 } 18852 } 18853 18854 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 18855 + " packages; restoreconNeeded was " + restoreconNeeded); 18856 } 18857 18858 /** 18859 * Prepare app data for the given app just after it was installed or 18860 * upgraded. This method carefully only touches users that it's installed 18861 * for, and it forces a restorecon to handle any seinfo changes. 18862 * <p> 18863 * Verifies that directories exist and that ownership and labeling is 18864 * correct for all installed apps. If there is an ownership mismatch, it 18865 * will try recovering system apps by wiping data; third-party app data is 18866 * left intact. 18867 * <p> 18868 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 18869 */ 18870 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 18871 final PackageSetting ps; 18872 synchronized (mPackages) { 18873 ps = mSettings.mPackages.get(pkg.packageName); 18874 mSettings.writeKernelMappingLPr(ps); 18875 } 18876 18877 final UserManager um = mContext.getSystemService(UserManager.class); 18878 for (UserInfo user : um.getUsers()) { 18879 final int flags; 18880 if (um.isUserUnlocked(user.id)) { 18881 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18882 } else if (um.isUserRunning(user.id)) { 18883 flags = StorageManager.FLAG_STORAGE_DE; 18884 } else { 18885 continue; 18886 } 18887 18888 if (ps.getInstalled(user.id)) { 18889 // Whenever an app changes, force a restorecon of its data 18890 // TODO: when user data is locked, mark that we're still dirty 18891 prepareAppDataLIF(pkg, user.id, flags, true); 18892 } 18893 } 18894 } 18895 18896 /** 18897 * Prepare app data for the given app. 18898 * <p> 18899 * Verifies that directories exist and that ownership and labeling is 18900 * correct for all installed apps. If there is an ownership mismatch, this 18901 * will try recovering system apps by wiping data; third-party app data is 18902 * left intact. 18903 */ 18904 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags, 18905 boolean restoreconNeeded) { 18906 if (pkg == null) { 18907 Slog.wtf(TAG, "Package was null!", new Throwable()); 18908 return; 18909 } 18910 prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded); 18911 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 18912 for (int i = 0; i < childCount; i++) { 18913 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded); 18914 } 18915 } 18916 18917 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags, 18918 boolean restoreconNeeded) { 18919 if (DEBUG_APP_DATA) { 18920 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 18921 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 18922 } 18923 18924 final String volumeUuid = pkg.volumeUuid; 18925 final String packageName = pkg.packageName; 18926 final ApplicationInfo app = pkg.applicationInfo; 18927 final int appId = UserHandle.getAppId(app.uid); 18928 18929 Preconditions.checkNotNull(app.seinfo); 18930 18931 try { 18932 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 18933 appId, app.seinfo, app.targetSdkVersion); 18934 } catch (InstallerException e) { 18935 if (app.isSystemApp()) { 18936 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 18937 + ", but trying to recover: " + e); 18938 destroyAppDataLeafLIF(pkg, userId, flags); 18939 try { 18940 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 18941 appId, app.seinfo, app.targetSdkVersion); 18942 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 18943 } catch (InstallerException e2) { 18944 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 18945 } 18946 } else { 18947 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 18948 } 18949 } 18950 18951 if (restoreconNeeded) { 18952 try { 18953 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, 18954 app.seinfo); 18955 } catch (InstallerException e) { 18956 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 18957 } 18958 } 18959 18960 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18961 try { 18962 // CE storage is unlocked right now, so read out the inode and 18963 // remember for use later when it's locked 18964 // TODO: mark this structure as dirty so we persist it! 18965 final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId, 18966 StorageManager.FLAG_STORAGE_CE); 18967 synchronized (mPackages) { 18968 final PackageSetting ps = mSettings.mPackages.get(packageName); 18969 if (ps != null) { 18970 ps.setCeDataInode(ceDataInode, userId); 18971 } 18972 } 18973 } catch (InstallerException e) { 18974 Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e); 18975 } 18976 } 18977 18978 prepareAppDataContentsLeafLIF(pkg, userId, flags); 18979 } 18980 18981 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 18982 if (pkg == null) { 18983 Slog.wtf(TAG, "Package was null!", new Throwable()); 18984 return; 18985 } 18986 prepareAppDataContentsLeafLIF(pkg, userId, flags); 18987 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 18988 for (int i = 0; i < childCount; i++) { 18989 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 18990 } 18991 } 18992 18993 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 18994 final String volumeUuid = pkg.volumeUuid; 18995 final String packageName = pkg.packageName; 18996 final ApplicationInfo app = pkg.applicationInfo; 18997 18998 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18999 // Create a native library symlink only if we have native libraries 19000 // and if the native libraries are 32 bit libraries. We do not provide 19001 // this symlink for 64 bit libraries. 19002 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 19003 final String nativeLibPath = app.nativeLibraryDir; 19004 try { 19005 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 19006 nativeLibPath, userId); 19007 } catch (InstallerException e) { 19008 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 19009 } 19010 } 19011 } 19012 } 19013 19014 /** 19015 * For system apps on non-FBE devices, this method migrates any existing 19016 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 19017 * requested by the app. 19018 */ 19019 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 19020 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 19021 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 19022 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 19023 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 19024 try { 19025 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 19026 storageTarget); 19027 } catch (InstallerException e) { 19028 logCriticalInfo(Log.WARN, 19029 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 19030 } 19031 return true; 19032 } else { 19033 return false; 19034 } 19035 } 19036 19037 public PackageFreezer freezePackage(String packageName, String killReason) { 19038 return new PackageFreezer(packageName, killReason); 19039 } 19040 19041 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 19042 String killReason) { 19043 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 19044 return new PackageFreezer(); 19045 } else { 19046 return freezePackage(packageName, killReason); 19047 } 19048 } 19049 19050 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 19051 String killReason) { 19052 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 19053 return new PackageFreezer(); 19054 } else { 19055 return freezePackage(packageName, killReason); 19056 } 19057 } 19058 19059 /** 19060 * Class that freezes and kills the given package upon creation, and 19061 * unfreezes it upon closing. This is typically used when doing surgery on 19062 * app code/data to prevent the app from running while you're working. 19063 */ 19064 private class PackageFreezer implements AutoCloseable { 19065 private final String mPackageName; 19066 private final PackageFreezer[] mChildren; 19067 19068 private final boolean mWeFroze; 19069 19070 private final AtomicBoolean mClosed = new AtomicBoolean(); 19071 private final CloseGuard mCloseGuard = CloseGuard.get(); 19072 19073 /** 19074 * Create and return a stub freezer that doesn't actually do anything, 19075 * typically used when someone requested 19076 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 19077 * {@link PackageManager#DELETE_DONT_KILL_APP}. 19078 */ 19079 public PackageFreezer() { 19080 mPackageName = null; 19081 mChildren = null; 19082 mWeFroze = false; 19083 mCloseGuard.open("close"); 19084 } 19085 19086 public PackageFreezer(String packageName, String killReason) { 19087 synchronized (mPackages) { 19088 mPackageName = packageName; 19089 mWeFroze = mFrozenPackages.add(mPackageName); 19090 19091 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 19092 if (ps != null) { 19093 killApplication(ps.name, ps.appId, killReason); 19094 } 19095 19096 final PackageParser.Package p = mPackages.get(packageName); 19097 if (p != null && p.childPackages != null) { 19098 final int N = p.childPackages.size(); 19099 mChildren = new PackageFreezer[N]; 19100 for (int i = 0; i < N; i++) { 19101 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 19102 killReason); 19103 } 19104 } else { 19105 mChildren = null; 19106 } 19107 } 19108 mCloseGuard.open("close"); 19109 } 19110 19111 @Override 19112 protected void finalize() throws Throwable { 19113 try { 19114 mCloseGuard.warnIfOpen(); 19115 close(); 19116 } finally { 19117 super.finalize(); 19118 } 19119 } 19120 19121 @Override 19122 public void close() { 19123 mCloseGuard.close(); 19124 if (mClosed.compareAndSet(false, true)) { 19125 synchronized (mPackages) { 19126 if (mWeFroze) { 19127 mFrozenPackages.remove(mPackageName); 19128 } 19129 19130 if (mChildren != null) { 19131 for (PackageFreezer freezer : mChildren) { 19132 freezer.close(); 19133 } 19134 } 19135 } 19136 } 19137 } 19138 } 19139 19140 /** 19141 * Verify that given package is currently frozen. 19142 */ 19143 private void checkPackageFrozen(String packageName) { 19144 synchronized (mPackages) { 19145 if (!mFrozenPackages.contains(packageName)) { 19146 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 19147 } 19148 } 19149 } 19150 19151 @Override 19152 public int movePackage(final String packageName, final String volumeUuid) { 19153 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19154 19155 final int moveId = mNextMoveId.getAndIncrement(); 19156 mHandler.post(new Runnable() { 19157 @Override 19158 public void run() { 19159 try { 19160 movePackageInternal(packageName, volumeUuid, moveId); 19161 } catch (PackageManagerException e) { 19162 Slog.w(TAG, "Failed to move " + packageName, e); 19163 mMoveCallbacks.notifyStatusChanged(moveId, 19164 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19165 } 19166 } 19167 }); 19168 return moveId; 19169 } 19170 19171 private void movePackageInternal(final String packageName, final String volumeUuid, 19172 final int moveId) throws PackageManagerException { 19173 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 19174 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19175 final PackageManager pm = mContext.getPackageManager(); 19176 19177 final boolean currentAsec; 19178 final String currentVolumeUuid; 19179 final File codeFile; 19180 final String installerPackageName; 19181 final String packageAbiOverride; 19182 final int appId; 19183 final String seinfo; 19184 final String label; 19185 final int targetSdkVersion; 19186 final PackageFreezer freezer; 19187 19188 // reader 19189 synchronized (mPackages) { 19190 final PackageParser.Package pkg = mPackages.get(packageName); 19191 final PackageSetting ps = mSettings.mPackages.get(packageName); 19192 if (pkg == null || ps == null) { 19193 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 19194 } 19195 19196 if (pkg.applicationInfo.isSystemApp()) { 19197 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 19198 "Cannot move system application"); 19199 } 19200 19201 if (pkg.applicationInfo.isExternalAsec()) { 19202 currentAsec = true; 19203 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 19204 } else if (pkg.applicationInfo.isForwardLocked()) { 19205 currentAsec = true; 19206 currentVolumeUuid = "forward_locked"; 19207 } else { 19208 currentAsec = false; 19209 currentVolumeUuid = ps.volumeUuid; 19210 19211 final File probe = new File(pkg.codePath); 19212 final File probeOat = new File(probe, "oat"); 19213 if (!probe.isDirectory() || !probeOat.isDirectory()) { 19214 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19215 "Move only supported for modern cluster style installs"); 19216 } 19217 } 19218 19219 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 19220 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19221 "Package already moved to " + volumeUuid); 19222 } 19223 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 19224 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 19225 "Device admin cannot be moved"); 19226 } 19227 19228 if (mFrozenPackages.contains(packageName)) { 19229 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 19230 "Failed to move already frozen package"); 19231 } 19232 19233 codeFile = new File(pkg.codePath); 19234 installerPackageName = ps.installerPackageName; 19235 packageAbiOverride = ps.cpuAbiOverrideString; 19236 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 19237 seinfo = pkg.applicationInfo.seinfo; 19238 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 19239 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 19240 freezer = new PackageFreezer(packageName, "movePackageInternal"); 19241 } 19242 19243 final Bundle extras = new Bundle(); 19244 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 19245 extras.putString(Intent.EXTRA_TITLE, label); 19246 mMoveCallbacks.notifyCreated(moveId, extras); 19247 19248 int installFlags; 19249 final boolean moveCompleteApp; 19250 final File measurePath; 19251 19252 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 19253 installFlags = INSTALL_INTERNAL; 19254 moveCompleteApp = !currentAsec; 19255 measurePath = Environment.getDataAppDirectory(volumeUuid); 19256 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 19257 installFlags = INSTALL_EXTERNAL; 19258 moveCompleteApp = false; 19259 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 19260 } else { 19261 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 19262 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 19263 || !volume.isMountedWritable()) { 19264 freezer.close(); 19265 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19266 "Move location not mounted private volume"); 19267 } 19268 19269 Preconditions.checkState(!currentAsec); 19270 19271 installFlags = INSTALL_INTERNAL; 19272 moveCompleteApp = true; 19273 measurePath = Environment.getDataAppDirectory(volumeUuid); 19274 } 19275 19276 final PackageStats stats = new PackageStats(null, -1); 19277 synchronized (mInstaller) { 19278 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 19279 freezer.close(); 19280 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19281 "Failed to measure package size"); 19282 } 19283 } 19284 19285 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 19286 + stats.dataSize); 19287 19288 final long startFreeBytes = measurePath.getFreeSpace(); 19289 final long sizeBytes; 19290 if (moveCompleteApp) { 19291 sizeBytes = stats.codeSize + stats.dataSize; 19292 } else { 19293 sizeBytes = stats.codeSize; 19294 } 19295 19296 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 19297 freezer.close(); 19298 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19299 "Not enough free space to move"); 19300 } 19301 19302 mMoveCallbacks.notifyStatusChanged(moveId, 10); 19303 19304 final CountDownLatch installedLatch = new CountDownLatch(1); 19305 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 19306 @Override 19307 public void onUserActionRequired(Intent intent) throws RemoteException { 19308 throw new IllegalStateException(); 19309 } 19310 19311 @Override 19312 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 19313 Bundle extras) throws RemoteException { 19314 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 19315 + PackageManager.installStatusToString(returnCode, msg)); 19316 19317 installedLatch.countDown(); 19318 freezer.close(); 19319 19320 final int status = PackageManager.installStatusToPublicStatus(returnCode); 19321 switch (status) { 19322 case PackageInstaller.STATUS_SUCCESS: 19323 mMoveCallbacks.notifyStatusChanged(moveId, 19324 PackageManager.MOVE_SUCCEEDED); 19325 break; 19326 case PackageInstaller.STATUS_FAILURE_STORAGE: 19327 mMoveCallbacks.notifyStatusChanged(moveId, 19328 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 19329 break; 19330 default: 19331 mMoveCallbacks.notifyStatusChanged(moveId, 19332 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19333 break; 19334 } 19335 } 19336 }; 19337 19338 final MoveInfo move; 19339 if (moveCompleteApp) { 19340 // Kick off a thread to report progress estimates 19341 new Thread() { 19342 @Override 19343 public void run() { 19344 while (true) { 19345 try { 19346 if (installedLatch.await(1, TimeUnit.SECONDS)) { 19347 break; 19348 } 19349 } catch (InterruptedException ignored) { 19350 } 19351 19352 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 19353 final int progress = 10 + (int) MathUtils.constrain( 19354 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 19355 mMoveCallbacks.notifyStatusChanged(moveId, progress); 19356 } 19357 } 19358 }.start(); 19359 19360 final String dataAppName = codeFile.getName(); 19361 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 19362 dataAppName, appId, seinfo, targetSdkVersion); 19363 } else { 19364 move = null; 19365 } 19366 19367 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 19368 19369 final Message msg = mHandler.obtainMessage(INIT_COPY); 19370 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 19371 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 19372 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 19373 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/); 19374 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 19375 msg.obj = params; 19376 19377 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 19378 System.identityHashCode(msg.obj)); 19379 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 19380 System.identityHashCode(msg.obj)); 19381 19382 mHandler.sendMessage(msg); 19383 } 19384 19385 @Override 19386 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 19387 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19388 19389 final int realMoveId = mNextMoveId.getAndIncrement(); 19390 final Bundle extras = new Bundle(); 19391 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 19392 mMoveCallbacks.notifyCreated(realMoveId, extras); 19393 19394 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 19395 @Override 19396 public void onCreated(int moveId, Bundle extras) { 19397 // Ignored 19398 } 19399 19400 @Override 19401 public void onStatusChanged(int moveId, int status, long estMillis) { 19402 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 19403 } 19404 }; 19405 19406 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19407 storage.setPrimaryStorageUuid(volumeUuid, callback); 19408 return realMoveId; 19409 } 19410 19411 @Override 19412 public int getMoveStatus(int moveId) { 19413 mContext.enforceCallingOrSelfPermission( 19414 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19415 return mMoveCallbacks.mLastStatus.get(moveId); 19416 } 19417 19418 @Override 19419 public void registerMoveCallback(IPackageMoveObserver callback) { 19420 mContext.enforceCallingOrSelfPermission( 19421 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19422 mMoveCallbacks.register(callback); 19423 } 19424 19425 @Override 19426 public void unregisterMoveCallback(IPackageMoveObserver callback) { 19427 mContext.enforceCallingOrSelfPermission( 19428 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19429 mMoveCallbacks.unregister(callback); 19430 } 19431 19432 @Override 19433 public boolean setInstallLocation(int loc) { 19434 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 19435 null); 19436 if (getInstallLocation() == loc) { 19437 return true; 19438 } 19439 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 19440 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 19441 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 19442 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 19443 return true; 19444 } 19445 return false; 19446 } 19447 19448 @Override 19449 public int getInstallLocation() { 19450 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 19451 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 19452 PackageHelper.APP_INSTALL_AUTO); 19453 } 19454 19455 /** Called by UserManagerService */ 19456 void cleanUpUser(UserManagerService userManager, int userHandle) { 19457 synchronized (mPackages) { 19458 mDirtyUsers.remove(userHandle); 19459 mUserNeedsBadging.delete(userHandle); 19460 mSettings.removeUserLPw(userHandle); 19461 mPendingBroadcasts.remove(userHandle); 19462 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 19463 } 19464 synchronized (mInstallLock) { 19465 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19466 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19467 final String volumeUuid = vol.getFsUuid(); 19468 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 19469 try { 19470 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 19471 } catch (InstallerException e) { 19472 Slog.w(TAG, "Failed to remove user data", e); 19473 } 19474 } 19475 synchronized (mPackages) { 19476 removeUnusedPackagesLILPw(userManager, userHandle); 19477 } 19478 } 19479 } 19480 19481 /** 19482 * We're removing userHandle and would like to remove any downloaded packages 19483 * that are no longer in use by any other user. 19484 * @param userHandle the user being removed 19485 */ 19486 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 19487 final boolean DEBUG_CLEAN_APKS = false; 19488 int [] users = userManager.getUserIds(); 19489 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 19490 while (psit.hasNext()) { 19491 PackageSetting ps = psit.next(); 19492 if (ps.pkg == null) { 19493 continue; 19494 } 19495 final String packageName = ps.pkg.packageName; 19496 // Skip over if system app 19497 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 19498 continue; 19499 } 19500 if (DEBUG_CLEAN_APKS) { 19501 Slog.i(TAG, "Checking package " + packageName); 19502 } 19503 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 19504 if (keep) { 19505 if (DEBUG_CLEAN_APKS) { 19506 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 19507 } 19508 } else { 19509 for (int i = 0; i < users.length; i++) { 19510 if (users[i] != userHandle && ps.getInstalled(users[i])) { 19511 keep = true; 19512 if (DEBUG_CLEAN_APKS) { 19513 Slog.i(TAG, " Keeping package " + packageName + " for user " 19514 + users[i]); 19515 } 19516 break; 19517 } 19518 } 19519 } 19520 if (!keep) { 19521 if (DEBUG_CLEAN_APKS) { 19522 Slog.i(TAG, " Removing package " + packageName); 19523 } 19524 mHandler.post(new Runnable() { 19525 public void run() { 19526 deletePackageX(packageName, userHandle, 0); 19527 } //end run 19528 }); 19529 } 19530 } 19531 } 19532 19533 /** Called by UserManagerService */ 19534 void createNewUser(int userHandle) { 19535 synchronized (mInstallLock) { 19536 try { 19537 mInstaller.createUserConfig(userHandle); 19538 } catch (InstallerException e) { 19539 Slog.w(TAG, "Failed to create user config", e); 19540 } 19541 mSettings.createNewUserLI(this, mInstaller, userHandle); 19542 } 19543 synchronized (mPackages) { 19544 applyFactoryDefaultBrowserLPw(userHandle); 19545 primeDomainVerificationsLPw(userHandle); 19546 } 19547 } 19548 19549 void newUserCreated(final int userHandle) { 19550 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 19551 // If permission review for legacy apps is required, we represent 19552 // dagerous permissions for such apps as always granted runtime 19553 // permissions to keep per user flag state whether review is needed. 19554 // Hence, if a new user is added we have to propagate dangerous 19555 // permission grants for these legacy apps. 19556 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 19557 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 19558 | UPDATE_PERMISSIONS_REPLACE_ALL); 19559 } 19560 } 19561 19562 @Override 19563 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 19564 mContext.enforceCallingOrSelfPermission( 19565 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 19566 "Only package verification agents can read the verifier device identity"); 19567 19568 synchronized (mPackages) { 19569 return mSettings.getVerifierDeviceIdentityLPw(); 19570 } 19571 } 19572 19573 @Override 19574 public void setPermissionEnforced(String permission, boolean enforced) { 19575 // TODO: Now that we no longer change GID for storage, this should to away. 19576 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 19577 "setPermissionEnforced"); 19578 if (READ_EXTERNAL_STORAGE.equals(permission)) { 19579 synchronized (mPackages) { 19580 if (mSettings.mReadExternalStorageEnforced == null 19581 || mSettings.mReadExternalStorageEnforced != enforced) { 19582 mSettings.mReadExternalStorageEnforced = enforced; 19583 mSettings.writeLPr(); 19584 } 19585 } 19586 // kill any non-foreground processes so we restart them and 19587 // grant/revoke the GID. 19588 final IActivityManager am = ActivityManagerNative.getDefault(); 19589 if (am != null) { 19590 final long token = Binder.clearCallingIdentity(); 19591 try { 19592 am.killProcessesBelowForeground("setPermissionEnforcement"); 19593 } catch (RemoteException e) { 19594 } finally { 19595 Binder.restoreCallingIdentity(token); 19596 } 19597 } 19598 } else { 19599 throw new IllegalArgumentException("No selective enforcement for " + permission); 19600 } 19601 } 19602 19603 @Override 19604 @Deprecated 19605 public boolean isPermissionEnforced(String permission) { 19606 return true; 19607 } 19608 19609 @Override 19610 public boolean isStorageLow() { 19611 final long token = Binder.clearCallingIdentity(); 19612 try { 19613 final DeviceStorageMonitorInternal 19614 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 19615 if (dsm != null) { 19616 return dsm.isMemoryLow(); 19617 } else { 19618 return false; 19619 } 19620 } finally { 19621 Binder.restoreCallingIdentity(token); 19622 } 19623 } 19624 19625 @Override 19626 public IPackageInstaller getPackageInstaller() { 19627 return mInstallerService; 19628 } 19629 19630 private boolean userNeedsBadging(int userId) { 19631 int index = mUserNeedsBadging.indexOfKey(userId); 19632 if (index < 0) { 19633 final UserInfo userInfo; 19634 final long token = Binder.clearCallingIdentity(); 19635 try { 19636 userInfo = sUserManager.getUserInfo(userId); 19637 } finally { 19638 Binder.restoreCallingIdentity(token); 19639 } 19640 final boolean b; 19641 if (userInfo != null && userInfo.isManagedProfile()) { 19642 b = true; 19643 } else { 19644 b = false; 19645 } 19646 mUserNeedsBadging.put(userId, b); 19647 return b; 19648 } 19649 return mUserNeedsBadging.valueAt(index); 19650 } 19651 19652 @Override 19653 public KeySet getKeySetByAlias(String packageName, String alias) { 19654 if (packageName == null || alias == null) { 19655 return null; 19656 } 19657 synchronized(mPackages) { 19658 final PackageParser.Package pkg = mPackages.get(packageName); 19659 if (pkg == null) { 19660 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19661 throw new IllegalArgumentException("Unknown package: " + packageName); 19662 } 19663 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19664 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 19665 } 19666 } 19667 19668 @Override 19669 public KeySet getSigningKeySet(String packageName) { 19670 if (packageName == null) { 19671 return null; 19672 } 19673 synchronized(mPackages) { 19674 final PackageParser.Package pkg = mPackages.get(packageName); 19675 if (pkg == null) { 19676 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19677 throw new IllegalArgumentException("Unknown package: " + packageName); 19678 } 19679 if (pkg.applicationInfo.uid != Binder.getCallingUid() 19680 && Process.SYSTEM_UID != Binder.getCallingUid()) { 19681 throw new SecurityException("May not access signing KeySet of other apps."); 19682 } 19683 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19684 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 19685 } 19686 } 19687 19688 @Override 19689 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 19690 if (packageName == null || ks == null) { 19691 return false; 19692 } 19693 synchronized(mPackages) { 19694 final PackageParser.Package pkg = mPackages.get(packageName); 19695 if (pkg == null) { 19696 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19697 throw new IllegalArgumentException("Unknown package: " + packageName); 19698 } 19699 IBinder ksh = ks.getToken(); 19700 if (ksh instanceof KeySetHandle) { 19701 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19702 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 19703 } 19704 return false; 19705 } 19706 } 19707 19708 @Override 19709 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 19710 if (packageName == null || ks == null) { 19711 return false; 19712 } 19713 synchronized(mPackages) { 19714 final PackageParser.Package pkg = mPackages.get(packageName); 19715 if (pkg == null) { 19716 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19717 throw new IllegalArgumentException("Unknown package: " + packageName); 19718 } 19719 IBinder ksh = ks.getToken(); 19720 if (ksh instanceof KeySetHandle) { 19721 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19722 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 19723 } 19724 return false; 19725 } 19726 } 19727 19728 private void deletePackageIfUnusedLPr(final String packageName) { 19729 PackageSetting ps = mSettings.mPackages.get(packageName); 19730 if (ps == null) { 19731 return; 19732 } 19733 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 19734 // TODO Implement atomic delete if package is unused 19735 // It is currently possible that the package will be deleted even if it is installed 19736 // after this method returns. 19737 mHandler.post(new Runnable() { 19738 public void run() { 19739 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 19740 } 19741 }); 19742 } 19743 } 19744 19745 /** 19746 * Check and throw if the given before/after packages would be considered a 19747 * downgrade. 19748 */ 19749 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 19750 throws PackageManagerException { 19751 if (after.versionCode < before.mVersionCode) { 19752 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 19753 "Update version code " + after.versionCode + " is older than current " 19754 + before.mVersionCode); 19755 } else if (after.versionCode == before.mVersionCode) { 19756 if (after.baseRevisionCode < before.baseRevisionCode) { 19757 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 19758 "Update base revision code " + after.baseRevisionCode 19759 + " is older than current " + before.baseRevisionCode); 19760 } 19761 19762 if (!ArrayUtils.isEmpty(after.splitNames)) { 19763 for (int i = 0; i < after.splitNames.length; i++) { 19764 final String splitName = after.splitNames[i]; 19765 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 19766 if (j != -1) { 19767 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 19768 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 19769 "Update split " + splitName + " revision code " 19770 + after.splitRevisionCodes[i] + " is older than current " 19771 + before.splitRevisionCodes[j]); 19772 } 19773 } 19774 } 19775 } 19776 } 19777 } 19778 19779 private static class MoveCallbacks extends Handler { 19780 private static final int MSG_CREATED = 1; 19781 private static final int MSG_STATUS_CHANGED = 2; 19782 19783 private final RemoteCallbackList<IPackageMoveObserver> 19784 mCallbacks = new RemoteCallbackList<>(); 19785 19786 private final SparseIntArray mLastStatus = new SparseIntArray(); 19787 19788 public MoveCallbacks(Looper looper) { 19789 super(looper); 19790 } 19791 19792 public void register(IPackageMoveObserver callback) { 19793 mCallbacks.register(callback); 19794 } 19795 19796 public void unregister(IPackageMoveObserver callback) { 19797 mCallbacks.unregister(callback); 19798 } 19799 19800 @Override 19801 public void handleMessage(Message msg) { 19802 final SomeArgs args = (SomeArgs) msg.obj; 19803 final int n = mCallbacks.beginBroadcast(); 19804 for (int i = 0; i < n; i++) { 19805 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 19806 try { 19807 invokeCallback(callback, msg.what, args); 19808 } catch (RemoteException ignored) { 19809 } 19810 } 19811 mCallbacks.finishBroadcast(); 19812 args.recycle(); 19813 } 19814 19815 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 19816 throws RemoteException { 19817 switch (what) { 19818 case MSG_CREATED: { 19819 callback.onCreated(args.argi1, (Bundle) args.arg2); 19820 break; 19821 } 19822 case MSG_STATUS_CHANGED: { 19823 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 19824 break; 19825 } 19826 } 19827 } 19828 19829 private void notifyCreated(int moveId, Bundle extras) { 19830 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 19831 19832 final SomeArgs args = SomeArgs.obtain(); 19833 args.argi1 = moveId; 19834 args.arg2 = extras; 19835 obtainMessage(MSG_CREATED, args).sendToTarget(); 19836 } 19837 19838 private void notifyStatusChanged(int moveId, int status) { 19839 notifyStatusChanged(moveId, status, -1); 19840 } 19841 19842 private void notifyStatusChanged(int moveId, int status, long estMillis) { 19843 Slog.v(TAG, "Move " + moveId + " status " + status); 19844 19845 final SomeArgs args = SomeArgs.obtain(); 19846 args.argi1 = moveId; 19847 args.argi2 = status; 19848 args.arg3 = estMillis; 19849 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 19850 19851 synchronized (mLastStatus) { 19852 mLastStatus.put(moveId, status); 19853 } 19854 } 19855 } 19856 19857 private final static class OnPermissionChangeListeners extends Handler { 19858 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 19859 19860 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 19861 new RemoteCallbackList<>(); 19862 19863 public OnPermissionChangeListeners(Looper looper) { 19864 super(looper); 19865 } 19866 19867 @Override 19868 public void handleMessage(Message msg) { 19869 switch (msg.what) { 19870 case MSG_ON_PERMISSIONS_CHANGED: { 19871 final int uid = msg.arg1; 19872 handleOnPermissionsChanged(uid); 19873 } break; 19874 } 19875 } 19876 19877 public void addListenerLocked(IOnPermissionsChangeListener listener) { 19878 mPermissionListeners.register(listener); 19879 19880 } 19881 19882 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 19883 mPermissionListeners.unregister(listener); 19884 } 19885 19886 public void onPermissionsChanged(int uid) { 19887 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 19888 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 19889 } 19890 } 19891 19892 private void handleOnPermissionsChanged(int uid) { 19893 final int count = mPermissionListeners.beginBroadcast(); 19894 try { 19895 for (int i = 0; i < count; i++) { 19896 IOnPermissionsChangeListener callback = mPermissionListeners 19897 .getBroadcastItem(i); 19898 try { 19899 callback.onPermissionsChanged(uid); 19900 } catch (RemoteException e) { 19901 Log.e(TAG, "Permission listener is dead", e); 19902 } 19903 } 19904 } finally { 19905 mPermissionListeners.finishBroadcast(); 19906 } 19907 } 19908 } 19909 19910 private class PackageManagerInternalImpl extends PackageManagerInternal { 19911 @Override 19912 public void setLocationPackagesProvider(PackagesProvider provider) { 19913 synchronized (mPackages) { 19914 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 19915 } 19916 } 19917 19918 @Override 19919 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 19920 synchronized (mPackages) { 19921 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 19922 } 19923 } 19924 19925 @Override 19926 public void setSmsAppPackagesProvider(PackagesProvider provider) { 19927 synchronized (mPackages) { 19928 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 19929 } 19930 } 19931 19932 @Override 19933 public void setDialerAppPackagesProvider(PackagesProvider provider) { 19934 synchronized (mPackages) { 19935 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 19936 } 19937 } 19938 19939 @Override 19940 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 19941 synchronized (mPackages) { 19942 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 19943 } 19944 } 19945 19946 @Override 19947 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 19948 synchronized (mPackages) { 19949 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 19950 } 19951 } 19952 19953 @Override 19954 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 19955 synchronized (mPackages) { 19956 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 19957 packageName, userId); 19958 } 19959 } 19960 19961 @Override 19962 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 19963 synchronized (mPackages) { 19964 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 19965 packageName, userId); 19966 } 19967 } 19968 19969 @Override 19970 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 19971 synchronized (mPackages) { 19972 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 19973 packageName, userId); 19974 } 19975 } 19976 19977 @Override 19978 public void setKeepUninstalledPackages(final List<String> packageList) { 19979 Preconditions.checkNotNull(packageList); 19980 List<String> removedFromList = null; 19981 synchronized (mPackages) { 19982 if (mKeepUninstalledPackages != null) { 19983 final int packagesCount = mKeepUninstalledPackages.size(); 19984 for (int i = 0; i < packagesCount; i++) { 19985 String oldPackage = mKeepUninstalledPackages.get(i); 19986 if (packageList != null && packageList.contains(oldPackage)) { 19987 continue; 19988 } 19989 if (removedFromList == null) { 19990 removedFromList = new ArrayList<>(); 19991 } 19992 removedFromList.add(oldPackage); 19993 } 19994 } 19995 mKeepUninstalledPackages = new ArrayList<>(packageList); 19996 if (removedFromList != null) { 19997 final int removedCount = removedFromList.size(); 19998 for (int i = 0; i < removedCount; i++) { 19999 deletePackageIfUnusedLPr(removedFromList.get(i)); 20000 } 20001 } 20002 } 20003 } 20004 20005 @Override 20006 public boolean isPermissionsReviewRequired(String packageName, int userId) { 20007 synchronized (mPackages) { 20008 // If we do not support permission review, done. 20009 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 20010 return false; 20011 } 20012 20013 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 20014 if (packageSetting == null) { 20015 return false; 20016 } 20017 20018 // Permission review applies only to apps not supporting the new permission model. 20019 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 20020 return false; 20021 } 20022 20023 // Legacy apps have the permission and get user consent on launch. 20024 PermissionsState permissionsState = packageSetting.getPermissionsState(); 20025 return permissionsState.isPermissionReviewRequired(userId); 20026 } 20027 } 20028 20029 @Override 20030 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 20031 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 20032 } 20033 20034 @Override 20035 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 20036 int userId) { 20037 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 20038 } 20039 } 20040 20041 @Override 20042 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 20043 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 20044 synchronized (mPackages) { 20045 final long identity = Binder.clearCallingIdentity(); 20046 try { 20047 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 20048 packageNames, userId); 20049 } finally { 20050 Binder.restoreCallingIdentity(identity); 20051 } 20052 } 20053 } 20054 20055 private static void enforceSystemOrPhoneCaller(String tag) { 20056 int callingUid = Binder.getCallingUid(); 20057 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 20058 throw new SecurityException( 20059 "Cannot call " + tag + " from UID " + callingUid); 20060 } 20061 } 20062 20063 boolean isHistoricalPackageUsageAvailable() { 20064 return mPackageUsage.isHistoricalPackageUsageAvailable(); 20065 } 20066 20067 /** 20068 * Return a <b>copy</b> of the collection of packages known to the package manager. 20069 * @return A copy of the values of mPackages. 20070 */ 20071 Collection<PackageParser.Package> getPackages() { 20072 synchronized (mPackages) { 20073 return new ArrayList<>(mPackages.values()); 20074 } 20075 } 20076 20077 /** 20078 * Logs process start information (including base APK hash) to the security log. 20079 * @hide 20080 */ 20081 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 20082 String apkFile, int pid) { 20083 if (!SecurityLog.isLoggingEnabled()) { 20084 return; 20085 } 20086 Bundle data = new Bundle(); 20087 data.putLong("startTimestamp", System.currentTimeMillis()); 20088 data.putString("processName", processName); 20089 data.putInt("uid", uid); 20090 data.putString("seinfo", seinfo); 20091 data.putString("apkFile", apkFile); 20092 data.putInt("pid", pid); 20093 Message msg = mProcessLoggingHandler.obtainMessage( 20094 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 20095 msg.setData(data); 20096 mProcessLoggingHandler.sendMessage(msg); 20097 } 20098} 20099