PackageManagerService.java revision 6a3b2d2bc63254a412eb546ed371fce8f4337434
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; 21import static android.Manifest.permission.WRITE_MEDIA_STORAGE; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 27import static android.content.pm.PackageManager.DELETE_KEEP_DATA; 28import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 29import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED; 30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 31import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 32import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 34import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET; 35import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 36import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 37import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 38import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 40import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 41import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 42import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 43import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 44import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 45import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 46import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 47import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 48import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 49import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 50import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 51import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 52import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 53import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 54import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 55import static android.content.pm.PackageManager.INSTALL_INTERNAL; 56import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK; 59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 62import static android.content.pm.PackageManager.MATCH_ALL; 63import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 64import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE; 65import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE; 66import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS; 67import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY; 68import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY; 69import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 70import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN; 71import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 72import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 73import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 74import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 75import static android.content.pm.PackageManager.PERMISSION_DENIED; 76import static android.content.pm.PackageManager.PERMISSION_GRANTED; 77import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED; 78import static android.content.pm.PackageParser.isApkFile; 79import static android.os.Process.PACKAGE_INFO_GID; 80import static android.os.Process.SYSTEM_UID; 81import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 82import static android.system.OsConstants.O_CREAT; 83import static android.system.OsConstants.O_RDWR; 84 85import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 86import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 87import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 88import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 89import static com.android.internal.util.ArrayUtils.appendInt; 90import static com.android.server.pm.Installer.DEXOPT_PUBLIC; 91import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 92import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 93import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 94import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 95import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 96import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason; 97import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter; 98import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 99import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 100import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 101 102import android.Manifest; 103import android.annotation.NonNull; 104import android.annotation.Nullable; 105import android.app.ActivityManager; 106import android.app.ActivityManagerNative; 107import android.app.IActivityManager; 108import android.app.admin.DevicePolicyManagerInternal; 109import android.app.admin.IDevicePolicyManager; 110import android.app.admin.SecurityLog; 111import android.app.backup.IBackupManager; 112import android.app.usage.UsageStatsManager; 113import android.content.BroadcastReceiver; 114import android.content.ComponentName; 115import android.content.Context; 116import android.content.IIntentReceiver; 117import android.content.Intent; 118import android.content.IntentFilter; 119import android.content.IntentSender; 120import android.content.IntentSender.SendIntentException; 121import android.content.ServiceConnection; 122import android.content.pm.ActivityInfo; 123import android.content.pm.ApplicationInfo; 124import android.content.pm.AppsQueryHelper; 125import android.content.pm.ComponentInfo; 126import android.content.pm.EphemeralApplicationInfo; 127import android.content.pm.EphemeralResolveInfo; 128import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo; 129import android.content.pm.FeatureInfo; 130import android.content.pm.IOnPermissionsChangeListener; 131import android.content.pm.IPackageDataObserver; 132import android.content.pm.IPackageDeleteObserver; 133import android.content.pm.IPackageDeleteObserver2; 134import android.content.pm.IPackageInstallObserver2; 135import android.content.pm.IPackageInstaller; 136import android.content.pm.IPackageManager; 137import android.content.pm.IPackageMoveObserver; 138import android.content.pm.IPackageStatsObserver; 139import android.content.pm.InstrumentationInfo; 140import android.content.pm.IntentFilterVerificationInfo; 141import android.content.pm.KeySet; 142import android.content.pm.PackageCleanItem; 143import android.content.pm.PackageInfo; 144import android.content.pm.PackageInfoLite; 145import android.content.pm.PackageInstaller; 146import android.content.pm.PackageManager; 147import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 148import android.content.pm.PackageManagerInternal; 149import android.content.pm.PackageParser; 150import android.content.pm.PackageParser.ActivityIntentInfo; 151import android.content.pm.PackageParser.PackageLite; 152import android.content.pm.PackageParser.PackageParserException; 153import android.content.pm.PackageStats; 154import android.content.pm.PackageUserState; 155import android.content.pm.ParceledListSlice; 156import android.content.pm.PermissionGroupInfo; 157import android.content.pm.PermissionInfo; 158import android.content.pm.ProviderInfo; 159import android.content.pm.ResolveInfo; 160import android.content.pm.ServiceInfo; 161import android.content.pm.Signature; 162import android.content.pm.UserInfo; 163import android.content.pm.VerifierDeviceIdentity; 164import android.content.pm.VerifierInfo; 165import android.content.res.Resources; 166import android.graphics.Bitmap; 167import android.hardware.display.DisplayManager; 168import android.net.Uri; 169import android.os.Binder; 170import android.os.Build; 171import android.os.Bundle; 172import android.os.Debug; 173import android.os.Environment; 174import android.os.Environment.UserEnvironment; 175import android.os.FileUtils; 176import android.os.Handler; 177import android.os.IBinder; 178import android.os.Looper; 179import android.os.Message; 180import android.os.Parcel; 181import android.os.ParcelFileDescriptor; 182import android.os.Process; 183import android.os.RemoteCallbackList; 184import android.os.RemoteException; 185import android.os.ResultReceiver; 186import android.os.SELinux; 187import android.os.ServiceManager; 188import android.os.SystemClock; 189import android.os.SystemProperties; 190import android.os.Trace; 191import android.os.UserHandle; 192import android.os.UserManager; 193import android.os.storage.IMountService; 194import android.os.storage.MountServiceInternal; 195import android.os.storage.StorageEventListener; 196import android.os.storage.StorageManager; 197import android.os.storage.VolumeInfo; 198import android.os.storage.VolumeRecord; 199import android.security.KeyStore; 200import android.security.SystemKeyStore; 201import android.system.ErrnoException; 202import android.system.Os; 203import android.text.TextUtils; 204import android.text.format.DateUtils; 205import android.util.ArrayMap; 206import android.util.ArraySet; 207import android.util.AtomicFile; 208import android.util.DisplayMetrics; 209import android.util.EventLog; 210import android.util.ExceptionUtils; 211import android.util.Log; 212import android.util.LogPrinter; 213import android.util.MathUtils; 214import android.util.PrintStreamPrinter; 215import android.util.Slog; 216import android.util.SparseArray; 217import android.util.SparseBooleanArray; 218import android.util.SparseIntArray; 219import android.util.Xml; 220import android.view.Display; 221 222import com.android.internal.R; 223import com.android.internal.annotations.GuardedBy; 224import com.android.internal.app.IMediaContainerService; 225import com.android.internal.app.ResolverActivity; 226import com.android.internal.content.NativeLibraryHelper; 227import com.android.internal.content.PackageHelper; 228import com.android.internal.os.IParcelFileDescriptorFactory; 229import com.android.internal.os.InstallerConnection.InstallerException; 230import com.android.internal.os.SomeArgs; 231import com.android.internal.os.Zygote; 232import com.android.internal.util.ArrayUtils; 233import com.android.internal.util.FastPrintWriter; 234import com.android.internal.util.FastXmlSerializer; 235import com.android.internal.util.IndentingPrintWriter; 236import com.android.internal.util.Preconditions; 237import com.android.internal.util.XmlUtils; 238import com.android.server.EventLogTags; 239import com.android.server.FgThread; 240import com.android.server.IntentResolver; 241import com.android.server.LocalServices; 242import com.android.server.ServiceThread; 243import com.android.server.SystemConfig; 244import com.android.server.Watchdog; 245import com.android.server.pm.PermissionsState.PermissionState; 246import com.android.server.pm.Settings.DatabaseVersion; 247import com.android.server.pm.Settings.VersionInfo; 248import com.android.server.storage.DeviceStorageMonitorInternal; 249 250import dalvik.system.CloseGuard; 251import dalvik.system.DexFile; 252import dalvik.system.VMRuntime; 253 254import libcore.io.IoUtils; 255import libcore.util.EmptyArray; 256 257import org.xmlpull.v1.XmlPullParser; 258import org.xmlpull.v1.XmlPullParserException; 259import org.xmlpull.v1.XmlSerializer; 260 261import java.io.BufferedInputStream; 262import java.io.BufferedOutputStream; 263import java.io.BufferedReader; 264import java.io.ByteArrayInputStream; 265import java.io.ByteArrayOutputStream; 266import java.io.File; 267import java.io.FileDescriptor; 268import java.io.FileNotFoundException; 269import java.io.FileOutputStream; 270import java.io.FileReader; 271import java.io.FilenameFilter; 272import java.io.IOException; 273import java.io.InputStream; 274import java.io.PrintWriter; 275import java.nio.charset.StandardCharsets; 276import java.security.MessageDigest; 277import java.security.NoSuchAlgorithmException; 278import java.security.PublicKey; 279import java.security.cert.Certificate; 280import java.security.cert.CertificateEncodingException; 281import java.security.cert.CertificateException; 282import java.text.SimpleDateFormat; 283import java.util.ArrayList; 284import java.util.Arrays; 285import java.util.Collection; 286import java.util.Collections; 287import java.util.Comparator; 288import java.util.Date; 289import java.util.HashSet; 290import java.util.Iterator; 291import java.util.List; 292import java.util.Map; 293import java.util.Objects; 294import java.util.Set; 295import java.util.concurrent.CountDownLatch; 296import java.util.concurrent.TimeUnit; 297import java.util.concurrent.atomic.AtomicBoolean; 298import java.util.concurrent.atomic.AtomicInteger; 299import java.util.concurrent.atomic.AtomicLong; 300 301/** 302 * Keep track of all those APKs everywhere. 303 * <p> 304 * Internally there are two important locks: 305 * <ul> 306 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 307 * and other related state. It is a fine-grained lock that should only be held 308 * momentarily, as it's one of the most contended locks in the system. 309 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 310 * operations typically involve heavy lifting of application data on disk. Since 311 * {@code installd} is single-threaded, and it's operations can often be slow, 312 * this lock should never be acquired while already holding {@link #mPackages}. 313 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 314 * holding {@link #mInstallLock}. 315 * </ul> 316 * Many internal methods rely on the caller to hold the appropriate locks, and 317 * this contract is expressed through method name suffixes: 318 * <ul> 319 * <li>fooLI(): the caller must hold {@link #mInstallLock} 320 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 321 * being modified must be frozen 322 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 323 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 324 * </ul> 325 * <p> 326 * Because this class is very central to the platform's security; please run all 327 * CTS and unit tests whenever making modifications: 328 * 329 * <pre> 330 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 331 * $ cts-tradefed run commandAndExit cts -m AppSecurityTests 332 * </pre> 333 */ 334public class PackageManagerService extends IPackageManager.Stub { 335 static final String TAG = "PackageManager"; 336 static final boolean DEBUG_SETTINGS = false; 337 static final boolean DEBUG_PREFERRED = false; 338 static final boolean DEBUG_UPGRADE = false; 339 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 340 private static final boolean DEBUG_BACKUP = false; 341 private static final boolean DEBUG_INSTALL = false; 342 private static final boolean DEBUG_REMOVE = false; 343 private static final boolean DEBUG_BROADCASTS = false; 344 private static final boolean DEBUG_SHOW_INFO = false; 345 private static final boolean DEBUG_PACKAGE_INFO = false; 346 private static final boolean DEBUG_INTENT_MATCHING = false; 347 private static final boolean DEBUG_PACKAGE_SCANNING = false; 348 private static final boolean DEBUG_VERIFY = false; 349 private static final boolean DEBUG_FILTERS = false; 350 351 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 352 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 353 // user, but by default initialize to this. 354 static final boolean DEBUG_DEXOPT = false; 355 356 private static final boolean DEBUG_ABI_SELECTION = false; 357 private static final boolean DEBUG_EPHEMERAL = false; 358 private static final boolean DEBUG_TRIAGED_MISSING = false; 359 private static final boolean DEBUG_APP_DATA = false; 360 361 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 362 363 private static final boolean DISABLE_EPHEMERAL_APPS = true; 364 365 private static final int RADIO_UID = Process.PHONE_UID; 366 private static final int LOG_UID = Process.LOG_UID; 367 private static final int NFC_UID = Process.NFC_UID; 368 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 369 private static final int SHELL_UID = Process.SHELL_UID; 370 371 // Cap the size of permission trees that 3rd party apps can define 372 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 373 374 // Suffix used during package installation when copying/moving 375 // package apks to install directory. 376 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 377 378 static final int SCAN_NO_DEX = 1<<1; 379 static final int SCAN_FORCE_DEX = 1<<2; 380 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 381 static final int SCAN_NEW_INSTALL = 1<<4; 382 static final int SCAN_NO_PATHS = 1<<5; 383 static final int SCAN_UPDATE_TIME = 1<<6; 384 static final int SCAN_DEFER_DEX = 1<<7; 385 static final int SCAN_BOOTING = 1<<8; 386 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 387 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 388 static final int SCAN_REPLACING = 1<<11; 389 static final int SCAN_REQUIRE_KNOWN = 1<<12; 390 static final int SCAN_MOVE = 1<<13; 391 static final int SCAN_INITIAL = 1<<14; 392 static final int SCAN_CHECK_ONLY = 1<<15; 393 static final int SCAN_DONT_KILL_APP = 1<<17; 394 static final int SCAN_IGNORE_FROZEN = 1<<18; 395 396 static final int REMOVE_CHATTY = 1<<16; 397 398 private static final int[] EMPTY_INT_ARRAY = new int[0]; 399 400 /** 401 * Timeout (in milliseconds) after which the watchdog should declare that 402 * our handler thread is wedged. The usual default for such things is one 403 * minute but we sometimes do very lengthy I/O operations on this thread, 404 * such as installing multi-gigabyte applications, so ours needs to be longer. 405 */ 406 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 407 408 /** 409 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 410 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 411 * settings entry if available, otherwise we use the hardcoded default. If it's been 412 * more than this long since the last fstrim, we force one during the boot sequence. 413 * 414 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 415 * one gets run at the next available charging+idle time. This final mandatory 416 * no-fstrim check kicks in only of the other scheduling criteria is never met. 417 */ 418 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 419 420 /** 421 * Whether verification is enabled by default. 422 */ 423 private static final boolean DEFAULT_VERIFY_ENABLE = true; 424 425 /** 426 * The default maximum time to wait for the verification agent to return in 427 * milliseconds. 428 */ 429 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 430 431 /** 432 * The default response for package verification timeout. 433 * 434 * This can be either PackageManager.VERIFICATION_ALLOW or 435 * PackageManager.VERIFICATION_REJECT. 436 */ 437 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 438 439 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 440 441 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 442 DEFAULT_CONTAINER_PACKAGE, 443 "com.android.defcontainer.DefaultContainerService"); 444 445 private static final String KILL_APP_REASON_GIDS_CHANGED = 446 "permission grant or revoke changed gids"; 447 448 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 449 "permissions revoked"; 450 451 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 452 453 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 454 455 /** Permission grant: not grant the permission. */ 456 private static final int GRANT_DENIED = 1; 457 458 /** Permission grant: grant the permission as an install permission. */ 459 private static final int GRANT_INSTALL = 2; 460 461 /** Permission grant: grant the permission as a runtime one. */ 462 private static final int GRANT_RUNTIME = 3; 463 464 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 465 private static final int GRANT_UPGRADE = 4; 466 467 /** Canonical intent used to identify what counts as a "web browser" app */ 468 private static final Intent sBrowserIntent; 469 static { 470 sBrowserIntent = new Intent(); 471 sBrowserIntent.setAction(Intent.ACTION_VIEW); 472 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 473 sBrowserIntent.setData(Uri.parse("http:")); 474 } 475 476 /** 477 * The set of all protected actions [i.e. those actions for which a high priority 478 * intent filter is disallowed]. 479 */ 480 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 481 static { 482 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 483 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 484 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 485 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 486 } 487 488 // Compilation reasons. 489 public static final int REASON_FIRST_BOOT = 0; 490 public static final int REASON_BOOT = 1; 491 public static final int REASON_INSTALL = 2; 492 public static final int REASON_BACKGROUND_DEXOPT = 3; 493 public static final int REASON_AB_OTA = 4; 494 public static final int REASON_NON_SYSTEM_LIBRARY = 5; 495 public static final int REASON_SHARED_APK = 6; 496 public static final int REASON_FORCED_DEXOPT = 7; 497 498 public static final int REASON_LAST = REASON_FORCED_DEXOPT; 499 500 final ServiceThread mHandlerThread; 501 502 final PackageHandler mHandler; 503 504 private final ProcessLoggingHandler mProcessLoggingHandler; 505 506 /** 507 * Messages for {@link #mHandler} that need to wait for system ready before 508 * being dispatched. 509 */ 510 private ArrayList<Message> mPostSystemReadyMessages; 511 512 final int mSdkVersion = Build.VERSION.SDK_INT; 513 514 final Context mContext; 515 final boolean mFactoryTest; 516 final boolean mOnlyCore; 517 final DisplayMetrics mMetrics; 518 final int mDefParseFlags; 519 final String[] mSeparateProcesses; 520 final boolean mIsUpgrade; 521 final boolean mIsPreNUpgrade; 522 523 /** The location for ASEC container files on internal storage. */ 524 final String mAsecInternalPath; 525 526 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 527 // LOCK HELD. Can be called with mInstallLock held. 528 @GuardedBy("mInstallLock") 529 final Installer mInstaller; 530 531 /** Directory where installed third-party apps stored */ 532 final File mAppInstallDir; 533 final File mEphemeralInstallDir; 534 535 /** 536 * Directory to which applications installed internally have their 537 * 32 bit native libraries copied. 538 */ 539 private File mAppLib32InstallDir; 540 541 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 542 // apps. 543 final File mDrmAppPrivateInstallDir; 544 545 // ---------------------------------------------------------------- 546 547 // Lock for state used when installing and doing other long running 548 // operations. Methods that must be called with this lock held have 549 // the suffix "LI". 550 final Object mInstallLock = new Object(); 551 552 // ---------------------------------------------------------------- 553 554 // Keys are String (package name), values are Package. This also serves 555 // as the lock for the global state. Methods that must be called with 556 // this lock held have the prefix "LP". 557 @GuardedBy("mPackages") 558 final ArrayMap<String, PackageParser.Package> mPackages = 559 new ArrayMap<String, PackageParser.Package>(); 560 561 final ArrayMap<String, Set<String>> mKnownCodebase = 562 new ArrayMap<String, Set<String>>(); 563 564 // Tracks available target package names -> overlay package paths. 565 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 566 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 567 568 /** 569 * Tracks new system packages [received in an OTA] that we expect to 570 * find updated user-installed versions. Keys are package name, values 571 * are package location. 572 */ 573 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 574 /** 575 * Tracks high priority intent filters for protected actions. During boot, certain 576 * filter actions are protected and should never be allowed to have a high priority 577 * intent filter for them. However, there is one, and only one exception -- the 578 * setup wizard. It must be able to define a high priority intent filter for these 579 * actions to ensure there are no escapes from the wizard. We need to delay processing 580 * of these during boot as we need to look at all of the system packages in order 581 * to know which component is the setup wizard. 582 */ 583 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 584 /** 585 * Whether or not processing protected filters should be deferred. 586 */ 587 private boolean mDeferProtectedFilters = true; 588 589 /** 590 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 591 */ 592 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 593 /** 594 * Whether or not system app permissions should be promoted from install to runtime. 595 */ 596 boolean mPromoteSystemApps; 597 598 @GuardedBy("mPackages") 599 final Settings mSettings; 600 601 /** 602 * Set of package names that are currently "frozen", which means active 603 * surgery is being done on the code/data for that package. The platform 604 * will refuse to launch frozen packages to avoid race conditions. 605 * 606 * @see PackageFreezer 607 */ 608 @GuardedBy("mPackages") 609 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 610 611 boolean mRestoredSettings; 612 613 // System configuration read by SystemConfig. 614 final int[] mGlobalGids; 615 final SparseArray<ArraySet<String>> mSystemPermissions; 616 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 617 618 // If mac_permissions.xml was found for seinfo labeling. 619 boolean mFoundPolicyFile; 620 621 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 622 623 public static final class SharedLibraryEntry { 624 public final String path; 625 public final String apk; 626 627 SharedLibraryEntry(String _path, String _apk) { 628 path = _path; 629 apk = _apk; 630 } 631 } 632 633 // Currently known shared libraries. 634 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 635 new ArrayMap<String, SharedLibraryEntry>(); 636 637 // All available activities, for your resolving pleasure. 638 final ActivityIntentResolver mActivities = 639 new ActivityIntentResolver(); 640 641 // All available receivers, for your resolving pleasure. 642 final ActivityIntentResolver mReceivers = 643 new ActivityIntentResolver(); 644 645 // All available services, for your resolving pleasure. 646 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 647 648 // All available providers, for your resolving pleasure. 649 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 650 651 // Mapping from provider base names (first directory in content URI codePath) 652 // to the provider information. 653 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 654 new ArrayMap<String, PackageParser.Provider>(); 655 656 // Mapping from instrumentation class names to info about them. 657 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 658 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 659 660 // Mapping from permission names to info about them. 661 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 662 new ArrayMap<String, PackageParser.PermissionGroup>(); 663 664 // Packages whose data we have transfered into another package, thus 665 // should no longer exist. 666 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 667 668 // Broadcast actions that are only available to the system. 669 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 670 671 /** List of packages waiting for verification. */ 672 final SparseArray<PackageVerificationState> mPendingVerification 673 = new SparseArray<PackageVerificationState>(); 674 675 /** Set of packages associated with each app op permission. */ 676 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 677 678 final PackageInstallerService mInstallerService; 679 680 private final PackageDexOptimizer mPackageDexOptimizer; 681 682 private AtomicInteger mNextMoveId = new AtomicInteger(); 683 private final MoveCallbacks mMoveCallbacks; 684 685 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 686 687 // Cache of users who need badging. 688 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 689 690 /** Token for keys in mPendingVerification. */ 691 private int mPendingVerificationToken = 0; 692 693 volatile boolean mSystemReady; 694 volatile boolean mSafeMode; 695 volatile boolean mHasSystemUidErrors; 696 697 ApplicationInfo mAndroidApplication; 698 final ActivityInfo mResolveActivity = new ActivityInfo(); 699 final ResolveInfo mResolveInfo = new ResolveInfo(); 700 ComponentName mResolveComponentName; 701 PackageParser.Package mPlatformPackage; 702 ComponentName mCustomResolverComponentName; 703 704 boolean mResolverReplaced = false; 705 706 private final @Nullable ComponentName mIntentFilterVerifierComponent; 707 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 708 709 private int mIntentFilterVerificationToken = 0; 710 711 /** Component that knows whether or not an ephemeral application exists */ 712 final ComponentName mEphemeralResolverComponent; 713 /** The service connection to the ephemeral resolver */ 714 final EphemeralResolverConnection mEphemeralResolverConnection; 715 716 /** Component used to install ephemeral applications */ 717 final ComponentName mEphemeralInstallerComponent; 718 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 719 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 720 721 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 722 = new SparseArray<IntentFilterVerificationState>(); 723 724 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 725 new DefaultPermissionGrantPolicy(this); 726 727 // List of packages names to keep cached, even if they are uninstalled for all users 728 private List<String> mKeepUninstalledPackages; 729 730 private static class IFVerificationParams { 731 PackageParser.Package pkg; 732 boolean replacing; 733 int userId; 734 int verifierUid; 735 736 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 737 int _userId, int _verifierUid) { 738 pkg = _pkg; 739 replacing = _replacing; 740 userId = _userId; 741 replacing = _replacing; 742 verifierUid = _verifierUid; 743 } 744 } 745 746 private interface IntentFilterVerifier<T extends IntentFilter> { 747 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 748 T filter, String packageName); 749 void startVerifications(int userId); 750 void receiveVerificationResponse(int verificationId); 751 } 752 753 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 754 private Context mContext; 755 private ComponentName mIntentFilterVerifierComponent; 756 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 757 758 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 759 mContext = context; 760 mIntentFilterVerifierComponent = verifierComponent; 761 } 762 763 private String getDefaultScheme() { 764 return IntentFilter.SCHEME_HTTPS; 765 } 766 767 @Override 768 public void startVerifications(int userId) { 769 // Launch verifications requests 770 int count = mCurrentIntentFilterVerifications.size(); 771 for (int n=0; n<count; n++) { 772 int verificationId = mCurrentIntentFilterVerifications.get(n); 773 final IntentFilterVerificationState ivs = 774 mIntentFilterVerificationStates.get(verificationId); 775 776 String packageName = ivs.getPackageName(); 777 778 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 779 final int filterCount = filters.size(); 780 ArraySet<String> domainsSet = new ArraySet<>(); 781 for (int m=0; m<filterCount; m++) { 782 PackageParser.ActivityIntentInfo filter = filters.get(m); 783 domainsSet.addAll(filter.getHostsList()); 784 } 785 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 786 synchronized (mPackages) { 787 if (mSettings.createIntentFilterVerificationIfNeededLPw( 788 packageName, domainsList) != null) { 789 scheduleWriteSettingsLocked(); 790 } 791 } 792 sendVerificationRequest(userId, verificationId, ivs); 793 } 794 mCurrentIntentFilterVerifications.clear(); 795 } 796 797 private void sendVerificationRequest(int userId, int verificationId, 798 IntentFilterVerificationState ivs) { 799 800 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 801 verificationIntent.putExtra( 802 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 803 verificationId); 804 verificationIntent.putExtra( 805 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 806 getDefaultScheme()); 807 verificationIntent.putExtra( 808 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 809 ivs.getHostsString()); 810 verificationIntent.putExtra( 811 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 812 ivs.getPackageName()); 813 verificationIntent.setComponent(mIntentFilterVerifierComponent); 814 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 815 816 UserHandle user = new UserHandle(userId); 817 mContext.sendBroadcastAsUser(verificationIntent, user); 818 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 819 "Sending IntentFilter verification broadcast"); 820 } 821 822 public void receiveVerificationResponse(int verificationId) { 823 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 824 825 final boolean verified = ivs.isVerified(); 826 827 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 828 final int count = filters.size(); 829 if (DEBUG_DOMAIN_VERIFICATION) { 830 Slog.i(TAG, "Received verification response " + verificationId 831 + " for " + count + " filters, verified=" + verified); 832 } 833 for (int n=0; n<count; n++) { 834 PackageParser.ActivityIntentInfo filter = filters.get(n); 835 filter.setVerified(verified); 836 837 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 838 + " verified with result:" + verified + " and hosts:" 839 + ivs.getHostsString()); 840 } 841 842 mIntentFilterVerificationStates.remove(verificationId); 843 844 final String packageName = ivs.getPackageName(); 845 IntentFilterVerificationInfo ivi = null; 846 847 synchronized (mPackages) { 848 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 849 } 850 if (ivi == null) { 851 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 852 + verificationId + " packageName:" + packageName); 853 return; 854 } 855 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 856 "Updating IntentFilterVerificationInfo for package " + packageName 857 +" verificationId:" + verificationId); 858 859 synchronized (mPackages) { 860 if (verified) { 861 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 862 } else { 863 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 864 } 865 scheduleWriteSettingsLocked(); 866 867 final int userId = ivs.getUserId(); 868 if (userId != UserHandle.USER_ALL) { 869 final int userStatus = 870 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 871 872 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 873 boolean needUpdate = false; 874 875 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 876 // already been set by the User thru the Disambiguation dialog 877 switch (userStatus) { 878 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 879 if (verified) { 880 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 881 } else { 882 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 883 } 884 needUpdate = true; 885 break; 886 887 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 888 if (verified) { 889 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 890 needUpdate = true; 891 } 892 break; 893 894 default: 895 // Nothing to do 896 } 897 898 if (needUpdate) { 899 mSettings.updateIntentFilterVerificationStatusLPw( 900 packageName, updatedStatus, userId); 901 scheduleWritePackageRestrictionsLocked(userId); 902 } 903 } 904 } 905 } 906 907 @Override 908 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 909 ActivityIntentInfo filter, String packageName) { 910 if (!hasValidDomains(filter)) { 911 return false; 912 } 913 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 914 if (ivs == null) { 915 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 916 packageName); 917 } 918 if (DEBUG_DOMAIN_VERIFICATION) { 919 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 920 } 921 ivs.addFilter(filter); 922 return true; 923 } 924 925 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 926 int userId, int verificationId, String packageName) { 927 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 928 verifierUid, userId, packageName); 929 ivs.setPendingState(); 930 synchronized (mPackages) { 931 mIntentFilterVerificationStates.append(verificationId, ivs); 932 mCurrentIntentFilterVerifications.add(verificationId); 933 } 934 return ivs; 935 } 936 } 937 938 private static boolean hasValidDomains(ActivityIntentInfo filter) { 939 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 940 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 941 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 942 } 943 944 // Set of pending broadcasts for aggregating enable/disable of components. 945 static class PendingPackageBroadcasts { 946 // for each user id, a map of <package name -> components within that package> 947 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 948 949 public PendingPackageBroadcasts() { 950 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 951 } 952 953 public ArrayList<String> get(int userId, String packageName) { 954 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 955 return packages.get(packageName); 956 } 957 958 public void put(int userId, String packageName, ArrayList<String> components) { 959 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 960 packages.put(packageName, components); 961 } 962 963 public void remove(int userId, String packageName) { 964 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 965 if (packages != null) { 966 packages.remove(packageName); 967 } 968 } 969 970 public void remove(int userId) { 971 mUidMap.remove(userId); 972 } 973 974 public int userIdCount() { 975 return mUidMap.size(); 976 } 977 978 public int userIdAt(int n) { 979 return mUidMap.keyAt(n); 980 } 981 982 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 983 return mUidMap.get(userId); 984 } 985 986 public int size() { 987 // total number of pending broadcast entries across all userIds 988 int num = 0; 989 for (int i = 0; i< mUidMap.size(); i++) { 990 num += mUidMap.valueAt(i).size(); 991 } 992 return num; 993 } 994 995 public void clear() { 996 mUidMap.clear(); 997 } 998 999 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1000 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1001 if (map == null) { 1002 map = new ArrayMap<String, ArrayList<String>>(); 1003 mUidMap.put(userId, map); 1004 } 1005 return map; 1006 } 1007 } 1008 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1009 1010 // Service Connection to remote media container service to copy 1011 // package uri's from external media onto secure containers 1012 // or internal storage. 1013 private IMediaContainerService mContainerService = null; 1014 1015 static final int SEND_PENDING_BROADCAST = 1; 1016 static final int MCS_BOUND = 3; 1017 static final int END_COPY = 4; 1018 static final int INIT_COPY = 5; 1019 static final int MCS_UNBIND = 6; 1020 static final int START_CLEANING_PACKAGE = 7; 1021 static final int FIND_INSTALL_LOC = 8; 1022 static final int POST_INSTALL = 9; 1023 static final int MCS_RECONNECT = 10; 1024 static final int MCS_GIVE_UP = 11; 1025 static final int UPDATED_MEDIA_STATUS = 12; 1026 static final int WRITE_SETTINGS = 13; 1027 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1028 static final int PACKAGE_VERIFIED = 15; 1029 static final int CHECK_PENDING_VERIFICATION = 16; 1030 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1031 static final int INTENT_FILTER_VERIFIED = 18; 1032 1033 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1034 1035 // Delay time in millisecs 1036 static final int BROADCAST_DELAY = 10 * 1000; 1037 1038 static UserManagerService sUserManager; 1039 1040 // Stores a list of users whose package restrictions file needs to be updated 1041 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1042 1043 final private DefaultContainerConnection mDefContainerConn = 1044 new DefaultContainerConnection(); 1045 class DefaultContainerConnection implements ServiceConnection { 1046 public void onServiceConnected(ComponentName name, IBinder service) { 1047 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1048 IMediaContainerService imcs = 1049 IMediaContainerService.Stub.asInterface(service); 1050 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1051 } 1052 1053 public void onServiceDisconnected(ComponentName name) { 1054 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1055 } 1056 } 1057 1058 // Recordkeeping of restore-after-install operations that are currently in flight 1059 // between the Package Manager and the Backup Manager 1060 static class PostInstallData { 1061 public InstallArgs args; 1062 public PackageInstalledInfo res; 1063 1064 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1065 args = _a; 1066 res = _r; 1067 } 1068 } 1069 1070 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1071 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1072 1073 // XML tags for backup/restore of various bits of state 1074 private static final String TAG_PREFERRED_BACKUP = "pa"; 1075 private static final String TAG_DEFAULT_APPS = "da"; 1076 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1077 1078 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1079 private static final String TAG_ALL_GRANTS = "rt-grants"; 1080 private static final String TAG_GRANT = "grant"; 1081 private static final String ATTR_PACKAGE_NAME = "pkg"; 1082 1083 private static final String TAG_PERMISSION = "perm"; 1084 private static final String ATTR_PERMISSION_NAME = "name"; 1085 private static final String ATTR_IS_GRANTED = "g"; 1086 private static final String ATTR_USER_SET = "set"; 1087 private static final String ATTR_USER_FIXED = "fixed"; 1088 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1089 1090 // System/policy permission grants are not backed up 1091 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1092 FLAG_PERMISSION_POLICY_FIXED 1093 | FLAG_PERMISSION_SYSTEM_FIXED 1094 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1095 1096 // And we back up these user-adjusted states 1097 private static final int USER_RUNTIME_GRANT_MASK = 1098 FLAG_PERMISSION_USER_SET 1099 | FLAG_PERMISSION_USER_FIXED 1100 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1101 1102 final @Nullable String mRequiredVerifierPackage; 1103 final @NonNull String mRequiredInstallerPackage; 1104 final @Nullable String mSetupWizardPackage; 1105 final @NonNull String mServicesSystemSharedLibraryPackageName; 1106 1107 private final PackageUsage mPackageUsage = new PackageUsage(); 1108 1109 private class PackageUsage { 1110 private static final int WRITE_INTERVAL 1111 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 1112 1113 private final Object mFileLock = new Object(); 1114 private final AtomicLong mLastWritten = new AtomicLong(0); 1115 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 1116 1117 private boolean mIsHistoricalPackageUsageAvailable = true; 1118 1119 boolean isHistoricalPackageUsageAvailable() { 1120 return mIsHistoricalPackageUsageAvailable; 1121 } 1122 1123 void write(boolean force) { 1124 if (force) { 1125 writeInternal(); 1126 return; 1127 } 1128 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 1129 && !DEBUG_DEXOPT) { 1130 return; 1131 } 1132 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 1133 new Thread("PackageUsage_DiskWriter") { 1134 @Override 1135 public void run() { 1136 try { 1137 writeInternal(); 1138 } finally { 1139 mBackgroundWriteRunning.set(false); 1140 } 1141 } 1142 }.start(); 1143 } 1144 } 1145 1146 private void writeInternal() { 1147 synchronized (mPackages) { 1148 synchronized (mFileLock) { 1149 AtomicFile file = getFile(); 1150 FileOutputStream f = null; 1151 try { 1152 f = file.startWrite(); 1153 BufferedOutputStream out = new BufferedOutputStream(f); 1154 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1155 StringBuilder sb = new StringBuilder(); 1156 for (PackageParser.Package pkg : mPackages.values()) { 1157 if (pkg.mLastPackageUsageTimeInMills == 0) { 1158 continue; 1159 } 1160 sb.setLength(0); 1161 sb.append(pkg.packageName); 1162 sb.append(' '); 1163 sb.append((long)pkg.mLastPackageUsageTimeInMills); 1164 sb.append('\n'); 1165 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1166 } 1167 out.flush(); 1168 file.finishWrite(f); 1169 } catch (IOException e) { 1170 if (f != null) { 1171 file.failWrite(f); 1172 } 1173 Log.e(TAG, "Failed to write package usage times", e); 1174 } 1175 } 1176 } 1177 mLastWritten.set(SystemClock.elapsedRealtime()); 1178 } 1179 1180 void readLP() { 1181 synchronized (mFileLock) { 1182 AtomicFile file = getFile(); 1183 BufferedInputStream in = null; 1184 try { 1185 in = new BufferedInputStream(file.openRead()); 1186 StringBuffer sb = new StringBuffer(); 1187 while (true) { 1188 String packageName = readToken(in, sb, ' '); 1189 if (packageName == null) { 1190 break; 1191 } 1192 String timeInMillisString = readToken(in, sb, '\n'); 1193 if (timeInMillisString == null) { 1194 throw new IOException("Failed to find last usage time for package " 1195 + packageName); 1196 } 1197 PackageParser.Package pkg = mPackages.get(packageName); 1198 if (pkg == null) { 1199 continue; 1200 } 1201 long timeInMillis; 1202 try { 1203 timeInMillis = Long.parseLong(timeInMillisString); 1204 } catch (NumberFormatException e) { 1205 throw new IOException("Failed to parse " + timeInMillisString 1206 + " as a long.", e); 1207 } 1208 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1209 } 1210 } catch (FileNotFoundException expected) { 1211 mIsHistoricalPackageUsageAvailable = false; 1212 } catch (IOException e) { 1213 Log.w(TAG, "Failed to read package usage times", e); 1214 } finally { 1215 IoUtils.closeQuietly(in); 1216 } 1217 } 1218 mLastWritten.set(SystemClock.elapsedRealtime()); 1219 } 1220 1221 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1222 throws IOException { 1223 sb.setLength(0); 1224 while (true) { 1225 int ch = in.read(); 1226 if (ch == -1) { 1227 if (sb.length() == 0) { 1228 return null; 1229 } 1230 throw new IOException("Unexpected EOF"); 1231 } 1232 if (ch == endOfToken) { 1233 return sb.toString(); 1234 } 1235 sb.append((char)ch); 1236 } 1237 } 1238 1239 private AtomicFile getFile() { 1240 File dataDir = Environment.getDataDirectory(); 1241 File systemDir = new File(dataDir, "system"); 1242 File fname = new File(systemDir, "package-usage.list"); 1243 return new AtomicFile(fname); 1244 } 1245 } 1246 1247 class PackageHandler extends Handler { 1248 private boolean mBound = false; 1249 final ArrayList<HandlerParams> mPendingInstalls = 1250 new ArrayList<HandlerParams>(); 1251 1252 private boolean connectToService() { 1253 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1254 " DefaultContainerService"); 1255 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1256 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1257 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1258 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1259 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1260 mBound = true; 1261 return true; 1262 } 1263 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1264 return false; 1265 } 1266 1267 private void disconnectService() { 1268 mContainerService = null; 1269 mBound = false; 1270 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1271 mContext.unbindService(mDefContainerConn); 1272 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1273 } 1274 1275 PackageHandler(Looper looper) { 1276 super(looper); 1277 } 1278 1279 public void handleMessage(Message msg) { 1280 try { 1281 doHandleMessage(msg); 1282 } finally { 1283 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1284 } 1285 } 1286 1287 void doHandleMessage(Message msg) { 1288 switch (msg.what) { 1289 case INIT_COPY: { 1290 HandlerParams params = (HandlerParams) msg.obj; 1291 int idx = mPendingInstalls.size(); 1292 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1293 // If a bind was already initiated we dont really 1294 // need to do anything. The pending install 1295 // will be processed later on. 1296 if (!mBound) { 1297 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1298 System.identityHashCode(mHandler)); 1299 // If this is the only one pending we might 1300 // have to bind to the service again. 1301 if (!connectToService()) { 1302 Slog.e(TAG, "Failed to bind to media container service"); 1303 params.serviceError(); 1304 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1305 System.identityHashCode(mHandler)); 1306 if (params.traceMethod != null) { 1307 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1308 params.traceCookie); 1309 } 1310 return; 1311 } else { 1312 // Once we bind to the service, the first 1313 // pending request will be processed. 1314 mPendingInstalls.add(idx, params); 1315 } 1316 } else { 1317 mPendingInstalls.add(idx, params); 1318 // Already bound to the service. Just make 1319 // sure we trigger off processing the first request. 1320 if (idx == 0) { 1321 mHandler.sendEmptyMessage(MCS_BOUND); 1322 } 1323 } 1324 break; 1325 } 1326 case MCS_BOUND: { 1327 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1328 if (msg.obj != null) { 1329 mContainerService = (IMediaContainerService) msg.obj; 1330 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1331 System.identityHashCode(mHandler)); 1332 } 1333 if (mContainerService == null) { 1334 if (!mBound) { 1335 // Something seriously wrong since we are not bound and we are not 1336 // waiting for connection. Bail out. 1337 Slog.e(TAG, "Cannot bind to media container service"); 1338 for (HandlerParams params : mPendingInstalls) { 1339 // Indicate service bind error 1340 params.serviceError(); 1341 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1342 System.identityHashCode(params)); 1343 if (params.traceMethod != null) { 1344 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1345 params.traceMethod, params.traceCookie); 1346 } 1347 return; 1348 } 1349 mPendingInstalls.clear(); 1350 } else { 1351 Slog.w(TAG, "Waiting to connect to media container service"); 1352 } 1353 } else if (mPendingInstalls.size() > 0) { 1354 HandlerParams params = mPendingInstalls.get(0); 1355 if (params != null) { 1356 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1357 System.identityHashCode(params)); 1358 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1359 if (params.startCopy()) { 1360 // We are done... look for more work or to 1361 // go idle. 1362 if (DEBUG_SD_INSTALL) Log.i(TAG, 1363 "Checking for more work or unbind..."); 1364 // Delete pending install 1365 if (mPendingInstalls.size() > 0) { 1366 mPendingInstalls.remove(0); 1367 } 1368 if (mPendingInstalls.size() == 0) { 1369 if (mBound) { 1370 if (DEBUG_SD_INSTALL) Log.i(TAG, 1371 "Posting delayed MCS_UNBIND"); 1372 removeMessages(MCS_UNBIND); 1373 Message ubmsg = obtainMessage(MCS_UNBIND); 1374 // Unbind after a little delay, to avoid 1375 // continual thrashing. 1376 sendMessageDelayed(ubmsg, 10000); 1377 } 1378 } else { 1379 // There are more pending requests in queue. 1380 // Just post MCS_BOUND message to trigger processing 1381 // of next pending install. 1382 if (DEBUG_SD_INSTALL) Log.i(TAG, 1383 "Posting MCS_BOUND for next work"); 1384 mHandler.sendEmptyMessage(MCS_BOUND); 1385 } 1386 } 1387 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1388 } 1389 } else { 1390 // Should never happen ideally. 1391 Slog.w(TAG, "Empty queue"); 1392 } 1393 break; 1394 } 1395 case MCS_RECONNECT: { 1396 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1397 if (mPendingInstalls.size() > 0) { 1398 if (mBound) { 1399 disconnectService(); 1400 } 1401 if (!connectToService()) { 1402 Slog.e(TAG, "Failed to bind to media container service"); 1403 for (HandlerParams params : mPendingInstalls) { 1404 // Indicate service bind error 1405 params.serviceError(); 1406 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1407 System.identityHashCode(params)); 1408 } 1409 mPendingInstalls.clear(); 1410 } 1411 } 1412 break; 1413 } 1414 case MCS_UNBIND: { 1415 // If there is no actual work left, then time to unbind. 1416 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1417 1418 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1419 if (mBound) { 1420 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1421 1422 disconnectService(); 1423 } 1424 } else if (mPendingInstalls.size() > 0) { 1425 // There are more pending requests in queue. 1426 // Just post MCS_BOUND message to trigger processing 1427 // of next pending install. 1428 mHandler.sendEmptyMessage(MCS_BOUND); 1429 } 1430 1431 break; 1432 } 1433 case MCS_GIVE_UP: { 1434 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1435 HandlerParams params = mPendingInstalls.remove(0); 1436 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1437 System.identityHashCode(params)); 1438 break; 1439 } 1440 case SEND_PENDING_BROADCAST: { 1441 String packages[]; 1442 ArrayList<String> components[]; 1443 int size = 0; 1444 int uids[]; 1445 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1446 synchronized (mPackages) { 1447 if (mPendingBroadcasts == null) { 1448 return; 1449 } 1450 size = mPendingBroadcasts.size(); 1451 if (size <= 0) { 1452 // Nothing to be done. Just return 1453 return; 1454 } 1455 packages = new String[size]; 1456 components = new ArrayList[size]; 1457 uids = new int[size]; 1458 int i = 0; // filling out the above arrays 1459 1460 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1461 int packageUserId = mPendingBroadcasts.userIdAt(n); 1462 Iterator<Map.Entry<String, ArrayList<String>>> it 1463 = mPendingBroadcasts.packagesForUserId(packageUserId) 1464 .entrySet().iterator(); 1465 while (it.hasNext() && i < size) { 1466 Map.Entry<String, ArrayList<String>> ent = it.next(); 1467 packages[i] = ent.getKey(); 1468 components[i] = ent.getValue(); 1469 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1470 uids[i] = (ps != null) 1471 ? UserHandle.getUid(packageUserId, ps.appId) 1472 : -1; 1473 i++; 1474 } 1475 } 1476 size = i; 1477 mPendingBroadcasts.clear(); 1478 } 1479 // Send broadcasts 1480 for (int i = 0; i < size; i++) { 1481 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1482 } 1483 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1484 break; 1485 } 1486 case START_CLEANING_PACKAGE: { 1487 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1488 final String packageName = (String)msg.obj; 1489 final int userId = msg.arg1; 1490 final boolean andCode = msg.arg2 != 0; 1491 synchronized (mPackages) { 1492 if (userId == UserHandle.USER_ALL) { 1493 int[] users = sUserManager.getUserIds(); 1494 for (int user : users) { 1495 mSettings.addPackageToCleanLPw( 1496 new PackageCleanItem(user, packageName, andCode)); 1497 } 1498 } else { 1499 mSettings.addPackageToCleanLPw( 1500 new PackageCleanItem(userId, packageName, andCode)); 1501 } 1502 } 1503 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1504 startCleaningPackages(); 1505 } break; 1506 case POST_INSTALL: { 1507 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1508 1509 PostInstallData data = mRunningInstalls.get(msg.arg1); 1510 mRunningInstalls.delete(msg.arg1); 1511 1512 if (data != null) { 1513 InstallArgs args = data.args; 1514 PackageInstalledInfo parentRes = data.res; 1515 1516 final boolean grantPermissions = (args.installFlags 1517 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1518 final boolean killApp = (args.installFlags 1519 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1520 final String[] grantedPermissions = args.installGrantPermissions; 1521 1522 // Handle the parent package 1523 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1524 grantedPermissions, args.observer); 1525 1526 // Handle the child packages 1527 final int childCount = (parentRes.addedChildPackages != null) 1528 ? parentRes.addedChildPackages.size() : 0; 1529 for (int i = 0; i < childCount; i++) { 1530 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1531 handlePackagePostInstall(childRes, grantPermissions, killApp, 1532 grantedPermissions, args.observer); 1533 } 1534 1535 // Log tracing if needed 1536 if (args.traceMethod != null) { 1537 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1538 args.traceCookie); 1539 } 1540 } else { 1541 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1542 } 1543 1544 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1545 } break; 1546 case UPDATED_MEDIA_STATUS: { 1547 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1548 boolean reportStatus = msg.arg1 == 1; 1549 boolean doGc = msg.arg2 == 1; 1550 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1551 if (doGc) { 1552 // Force a gc to clear up stale containers. 1553 Runtime.getRuntime().gc(); 1554 } 1555 if (msg.obj != null) { 1556 @SuppressWarnings("unchecked") 1557 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1558 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1559 // Unload containers 1560 unloadAllContainers(args); 1561 } 1562 if (reportStatus) { 1563 try { 1564 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1565 PackageHelper.getMountService().finishMediaUpdate(); 1566 } catch (RemoteException e) { 1567 Log.e(TAG, "MountService not running?"); 1568 } 1569 } 1570 } break; 1571 case WRITE_SETTINGS: { 1572 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1573 synchronized (mPackages) { 1574 removeMessages(WRITE_SETTINGS); 1575 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1576 mSettings.writeLPr(); 1577 mDirtyUsers.clear(); 1578 } 1579 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1580 } break; 1581 case WRITE_PACKAGE_RESTRICTIONS: { 1582 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1583 synchronized (mPackages) { 1584 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1585 for (int userId : mDirtyUsers) { 1586 mSettings.writePackageRestrictionsLPr(userId); 1587 } 1588 mDirtyUsers.clear(); 1589 } 1590 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1591 } break; 1592 case CHECK_PENDING_VERIFICATION: { 1593 final int verificationId = msg.arg1; 1594 final PackageVerificationState state = mPendingVerification.get(verificationId); 1595 1596 if ((state != null) && !state.timeoutExtended()) { 1597 final InstallArgs args = state.getInstallArgs(); 1598 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1599 1600 Slog.i(TAG, "Verification timed out for " + originUri); 1601 mPendingVerification.remove(verificationId); 1602 1603 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1604 1605 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1606 Slog.i(TAG, "Continuing with installation of " + originUri); 1607 state.setVerifierResponse(Binder.getCallingUid(), 1608 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1609 broadcastPackageVerified(verificationId, originUri, 1610 PackageManager.VERIFICATION_ALLOW, 1611 state.getInstallArgs().getUser()); 1612 try { 1613 ret = args.copyApk(mContainerService, true); 1614 } catch (RemoteException e) { 1615 Slog.e(TAG, "Could not contact the ContainerService"); 1616 } 1617 } else { 1618 broadcastPackageVerified(verificationId, originUri, 1619 PackageManager.VERIFICATION_REJECT, 1620 state.getInstallArgs().getUser()); 1621 } 1622 1623 Trace.asyncTraceEnd( 1624 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1625 1626 processPendingInstall(args, ret); 1627 mHandler.sendEmptyMessage(MCS_UNBIND); 1628 } 1629 break; 1630 } 1631 case PACKAGE_VERIFIED: { 1632 final int verificationId = msg.arg1; 1633 1634 final PackageVerificationState state = mPendingVerification.get(verificationId); 1635 if (state == null) { 1636 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1637 break; 1638 } 1639 1640 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1641 1642 state.setVerifierResponse(response.callerUid, response.code); 1643 1644 if (state.isVerificationComplete()) { 1645 mPendingVerification.remove(verificationId); 1646 1647 final InstallArgs args = state.getInstallArgs(); 1648 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1649 1650 int ret; 1651 if (state.isInstallAllowed()) { 1652 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1653 broadcastPackageVerified(verificationId, originUri, 1654 response.code, state.getInstallArgs().getUser()); 1655 try { 1656 ret = args.copyApk(mContainerService, true); 1657 } catch (RemoteException e) { 1658 Slog.e(TAG, "Could not contact the ContainerService"); 1659 } 1660 } else { 1661 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1662 } 1663 1664 Trace.asyncTraceEnd( 1665 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1666 1667 processPendingInstall(args, ret); 1668 mHandler.sendEmptyMessage(MCS_UNBIND); 1669 } 1670 1671 break; 1672 } 1673 case START_INTENT_FILTER_VERIFICATIONS: { 1674 IFVerificationParams params = (IFVerificationParams) msg.obj; 1675 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1676 params.replacing, params.pkg); 1677 break; 1678 } 1679 case INTENT_FILTER_VERIFIED: { 1680 final int verificationId = msg.arg1; 1681 1682 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1683 verificationId); 1684 if (state == null) { 1685 Slog.w(TAG, "Invalid IntentFilter verification token " 1686 + verificationId + " received"); 1687 break; 1688 } 1689 1690 final int userId = state.getUserId(); 1691 1692 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1693 "Processing IntentFilter verification with token:" 1694 + verificationId + " and userId:" + userId); 1695 1696 final IntentFilterVerificationResponse response = 1697 (IntentFilterVerificationResponse) msg.obj; 1698 1699 state.setVerifierResponse(response.callerUid, response.code); 1700 1701 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1702 "IntentFilter verification with token:" + verificationId 1703 + " and userId:" + userId 1704 + " is settings verifier response with response code:" 1705 + response.code); 1706 1707 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1708 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1709 + response.getFailedDomainsString()); 1710 } 1711 1712 if (state.isVerificationComplete()) { 1713 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1714 } else { 1715 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1716 "IntentFilter verification with token:" + verificationId 1717 + " was not said to be complete"); 1718 } 1719 1720 break; 1721 } 1722 } 1723 } 1724 } 1725 1726 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1727 boolean killApp, String[] grantedPermissions, 1728 IPackageInstallObserver2 installObserver) { 1729 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1730 // Send the removed broadcasts 1731 if (res.removedInfo != null) { 1732 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1733 } 1734 1735 // Now that we successfully installed the package, grant runtime 1736 // permissions if requested before broadcasting the install. 1737 if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion 1738 >= Build.VERSION_CODES.M) { 1739 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1740 } 1741 1742 final boolean update = res.removedInfo != null 1743 && res.removedInfo.removedPackage != null; 1744 1745 // If this is the first time we have child packages for a disabled privileged 1746 // app that had no children, we grant requested runtime permissions to the new 1747 // children if the parent on the system image had them already granted. 1748 if (res.pkg.parentPackage != null) { 1749 synchronized (mPackages) { 1750 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1751 } 1752 } 1753 1754 synchronized (mPackages) { 1755 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1756 } 1757 1758 final String packageName = res.pkg.applicationInfo.packageName; 1759 Bundle extras = new Bundle(1); 1760 extras.putInt(Intent.EXTRA_UID, res.uid); 1761 1762 // Determine the set of users who are adding this package for 1763 // the first time vs. those who are seeing an update. 1764 int[] firstUsers = EMPTY_INT_ARRAY; 1765 int[] updateUsers = EMPTY_INT_ARRAY; 1766 if (res.origUsers == null || res.origUsers.length == 0) { 1767 firstUsers = res.newUsers; 1768 } else { 1769 for (int newUser : res.newUsers) { 1770 boolean isNew = true; 1771 for (int origUser : res.origUsers) { 1772 if (origUser == newUser) { 1773 isNew = false; 1774 break; 1775 } 1776 } 1777 if (isNew) { 1778 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1779 } else { 1780 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1781 } 1782 } 1783 } 1784 1785 // Send installed broadcasts if the install/update is not ephemeral 1786 if (!isEphemeral(res.pkg)) { 1787 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1788 1789 // Send added for users that see the package for the first time 1790 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1791 extras, 0 /*flags*/, null /*targetPackage*/, 1792 null /*finishedReceiver*/, firstUsers); 1793 1794 // Send added for users that don't see the package for the first time 1795 if (update) { 1796 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1797 } 1798 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1799 extras, 0 /*flags*/, null /*targetPackage*/, 1800 null /*finishedReceiver*/, updateUsers); 1801 1802 // Send replaced for users that don't see the package for the first time 1803 if (update) { 1804 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1805 packageName, extras, 0 /*flags*/, 1806 null /*targetPackage*/, null /*finishedReceiver*/, 1807 updateUsers); 1808 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1809 null /*package*/, null /*extras*/, 0 /*flags*/, 1810 packageName /*targetPackage*/, 1811 null /*finishedReceiver*/, updateUsers); 1812 } 1813 1814 // Send broadcast package appeared if forward locked/external for all users 1815 // treat asec-hosted packages like removable media on upgrade 1816 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1817 if (DEBUG_INSTALL) { 1818 Slog.i(TAG, "upgrading pkg " + res.pkg 1819 + " is ASEC-hosted -> AVAILABLE"); 1820 } 1821 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1822 ArrayList<String> pkgList = new ArrayList<>(1); 1823 pkgList.add(packageName); 1824 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1825 } 1826 } 1827 1828 // Work that needs to happen on first install within each user 1829 if (firstUsers != null && firstUsers.length > 0) { 1830 synchronized (mPackages) { 1831 for (int userId : firstUsers) { 1832 // If this app is a browser and it's newly-installed for some 1833 // users, clear any default-browser state in those users. The 1834 // app's nature doesn't depend on the user, so we can just check 1835 // its browser nature in any user and generalize. 1836 if (packageIsBrowser(packageName, userId)) { 1837 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1838 } 1839 1840 // We may also need to apply pending (restored) runtime 1841 // permission grants within these users. 1842 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1843 } 1844 } 1845 } 1846 1847 // Log current value of "unknown sources" setting 1848 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1849 getUnknownSourcesSettings()); 1850 1851 // Force a gc to clear up things 1852 Runtime.getRuntime().gc(); 1853 1854 // Remove the replaced package's older resources safely now 1855 // We delete after a gc for applications on sdcard. 1856 if (res.removedInfo != null && res.removedInfo.args != null) { 1857 synchronized (mInstallLock) { 1858 res.removedInfo.args.doPostDeleteLI(true); 1859 } 1860 } 1861 } 1862 1863 // If someone is watching installs - notify them 1864 if (installObserver != null) { 1865 try { 1866 Bundle extras = extrasForInstallResult(res); 1867 installObserver.onPackageInstalled(res.name, res.returnCode, 1868 res.returnMsg, extras); 1869 } catch (RemoteException e) { 1870 Slog.i(TAG, "Observer no longer exists."); 1871 } 1872 } 1873 } 1874 1875 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1876 PackageParser.Package pkg) { 1877 if (pkg.parentPackage == null) { 1878 return; 1879 } 1880 if (pkg.requestedPermissions == null) { 1881 return; 1882 } 1883 final PackageSetting disabledSysParentPs = mSettings 1884 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1885 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1886 || !disabledSysParentPs.isPrivileged() 1887 || (disabledSysParentPs.childPackageNames != null 1888 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1889 return; 1890 } 1891 final int[] allUserIds = sUserManager.getUserIds(); 1892 final int permCount = pkg.requestedPermissions.size(); 1893 for (int i = 0; i < permCount; i++) { 1894 String permission = pkg.requestedPermissions.get(i); 1895 BasePermission bp = mSettings.mPermissions.get(permission); 1896 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1897 continue; 1898 } 1899 for (int userId : allUserIds) { 1900 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1901 permission, userId)) { 1902 grantRuntimePermission(pkg.packageName, permission, userId); 1903 } 1904 } 1905 } 1906 } 1907 1908 private StorageEventListener mStorageListener = new StorageEventListener() { 1909 @Override 1910 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1911 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1912 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1913 final String volumeUuid = vol.getFsUuid(); 1914 1915 // Clean up any users or apps that were removed or recreated 1916 // while this volume was missing 1917 reconcileUsers(volumeUuid); 1918 reconcileApps(volumeUuid); 1919 1920 // Clean up any install sessions that expired or were 1921 // cancelled while this volume was missing 1922 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1923 1924 loadPrivatePackages(vol); 1925 1926 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1927 unloadPrivatePackages(vol); 1928 } 1929 } 1930 1931 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1932 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1933 updateExternalMediaStatus(true, false); 1934 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1935 updateExternalMediaStatus(false, false); 1936 } 1937 } 1938 } 1939 1940 @Override 1941 public void onVolumeForgotten(String fsUuid) { 1942 if (TextUtils.isEmpty(fsUuid)) { 1943 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1944 return; 1945 } 1946 1947 // Remove any apps installed on the forgotten volume 1948 synchronized (mPackages) { 1949 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1950 for (PackageSetting ps : packages) { 1951 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1952 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1953 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 1954 } 1955 1956 mSettings.onVolumeForgotten(fsUuid); 1957 mSettings.writeLPr(); 1958 } 1959 } 1960 }; 1961 1962 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 1963 String[] grantedPermissions) { 1964 for (int userId : userIds) { 1965 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1966 } 1967 1968 // We could have touched GID membership, so flush out packages.list 1969 synchronized (mPackages) { 1970 mSettings.writePackageListLPr(); 1971 } 1972 } 1973 1974 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1975 String[] grantedPermissions) { 1976 SettingBase sb = (SettingBase) pkg.mExtras; 1977 if (sb == null) { 1978 return; 1979 } 1980 1981 PermissionsState permissionsState = sb.getPermissionsState(); 1982 1983 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 1984 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 1985 1986 synchronized (mPackages) { 1987 for (String permission : pkg.requestedPermissions) { 1988 BasePermission bp = mSettings.mPermissions.get(permission); 1989 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 1990 && (grantedPermissions == null 1991 || ArrayUtils.contains(grantedPermissions, permission))) { 1992 final int flags = permissionsState.getPermissionFlags(permission, userId); 1993 // Installer cannot change immutable permissions. 1994 if ((flags & immutableFlags) == 0) { 1995 grantRuntimePermission(pkg.packageName, permission, userId); 1996 } 1997 } 1998 } 1999 } 2000 } 2001 2002 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2003 Bundle extras = null; 2004 switch (res.returnCode) { 2005 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2006 extras = new Bundle(); 2007 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2008 res.origPermission); 2009 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2010 res.origPackage); 2011 break; 2012 } 2013 case PackageManager.INSTALL_SUCCEEDED: { 2014 extras = new Bundle(); 2015 extras.putBoolean(Intent.EXTRA_REPLACING, 2016 res.removedInfo != null && res.removedInfo.removedPackage != null); 2017 break; 2018 } 2019 } 2020 return extras; 2021 } 2022 2023 void scheduleWriteSettingsLocked() { 2024 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2025 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2026 } 2027 } 2028 2029 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2030 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2031 scheduleWritePackageRestrictionsLocked(userId); 2032 } 2033 2034 void scheduleWritePackageRestrictionsLocked(int userId) { 2035 final int[] userIds = (userId == UserHandle.USER_ALL) 2036 ? sUserManager.getUserIds() : new int[]{userId}; 2037 for (int nextUserId : userIds) { 2038 if (!sUserManager.exists(nextUserId)) return; 2039 mDirtyUsers.add(nextUserId); 2040 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2041 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2042 } 2043 } 2044 } 2045 2046 public static PackageManagerService main(Context context, Installer installer, 2047 boolean factoryTest, boolean onlyCore) { 2048 // Self-check for initial settings. 2049 PackageManagerServiceCompilerMapping.checkProperties(); 2050 2051 PackageManagerService m = new PackageManagerService(context, installer, 2052 factoryTest, onlyCore); 2053 m.enableSystemUserPackages(); 2054 ServiceManager.addService("package", m); 2055 return m; 2056 } 2057 2058 private void enableSystemUserPackages() { 2059 if (!UserManager.isSplitSystemUser()) { 2060 return; 2061 } 2062 // For system user, enable apps based on the following conditions: 2063 // - app is whitelisted or belong to one of these groups: 2064 // -- system app which has no launcher icons 2065 // -- system app which has INTERACT_ACROSS_USERS permission 2066 // -- system IME app 2067 // - app is not in the blacklist 2068 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2069 Set<String> enableApps = new ArraySet<>(); 2070 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2071 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2072 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2073 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2074 enableApps.addAll(wlApps); 2075 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2076 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2077 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2078 enableApps.removeAll(blApps); 2079 Log.i(TAG, "Applications installed for system user: " + enableApps); 2080 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2081 UserHandle.SYSTEM); 2082 final int allAppsSize = allAps.size(); 2083 synchronized (mPackages) { 2084 for (int i = 0; i < allAppsSize; i++) { 2085 String pName = allAps.get(i); 2086 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2087 // Should not happen, but we shouldn't be failing if it does 2088 if (pkgSetting == null) { 2089 continue; 2090 } 2091 boolean install = enableApps.contains(pName); 2092 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2093 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2094 + " for system user"); 2095 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2096 } 2097 } 2098 } 2099 } 2100 2101 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2102 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2103 Context.DISPLAY_SERVICE); 2104 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2105 } 2106 2107 public PackageManagerService(Context context, Installer installer, 2108 boolean factoryTest, boolean onlyCore) { 2109 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2110 SystemClock.uptimeMillis()); 2111 2112 if (mSdkVersion <= 0) { 2113 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2114 } 2115 2116 mContext = context; 2117 mFactoryTest = factoryTest; 2118 mOnlyCore = onlyCore; 2119 mMetrics = new DisplayMetrics(); 2120 mSettings = new Settings(mPackages); 2121 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2122 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2123 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2124 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2125 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2126 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2127 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2128 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2129 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2130 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2131 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2132 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2133 2134 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2135 if (separateProcesses != null && separateProcesses.length() > 0) { 2136 if ("*".equals(separateProcesses)) { 2137 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2138 mSeparateProcesses = null; 2139 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2140 } else { 2141 mDefParseFlags = 0; 2142 mSeparateProcesses = separateProcesses.split(","); 2143 Slog.w(TAG, "Running with debug.separate_processes: " 2144 + separateProcesses); 2145 } 2146 } else { 2147 mDefParseFlags = 0; 2148 mSeparateProcesses = null; 2149 } 2150 2151 mInstaller = installer; 2152 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2153 "*dexopt*"); 2154 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2155 2156 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2157 FgThread.get().getLooper()); 2158 2159 getDefaultDisplayMetrics(context, mMetrics); 2160 2161 SystemConfig systemConfig = SystemConfig.getInstance(); 2162 mGlobalGids = systemConfig.getGlobalGids(); 2163 mSystemPermissions = systemConfig.getSystemPermissions(); 2164 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2165 2166 synchronized (mInstallLock) { 2167 // writer 2168 synchronized (mPackages) { 2169 mHandlerThread = new ServiceThread(TAG, 2170 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2171 mHandlerThread.start(); 2172 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2173 mProcessLoggingHandler = new ProcessLoggingHandler(); 2174 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2175 2176 File dataDir = Environment.getDataDirectory(); 2177 mAppInstallDir = new File(dataDir, "app"); 2178 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2179 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2180 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2181 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2182 2183 sUserManager = new UserManagerService(context, this, mPackages); 2184 2185 // Propagate permission configuration in to package manager. 2186 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2187 = systemConfig.getPermissions(); 2188 for (int i=0; i<permConfig.size(); i++) { 2189 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2190 BasePermission bp = mSettings.mPermissions.get(perm.name); 2191 if (bp == null) { 2192 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2193 mSettings.mPermissions.put(perm.name, bp); 2194 } 2195 if (perm.gids != null) { 2196 bp.setGids(perm.gids, perm.perUser); 2197 } 2198 } 2199 2200 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2201 for (int i=0; i<libConfig.size(); i++) { 2202 mSharedLibraries.put(libConfig.keyAt(i), 2203 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2204 } 2205 2206 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2207 2208 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 2209 2210 String customResolverActivity = Resources.getSystem().getString( 2211 R.string.config_customResolverActivity); 2212 if (TextUtils.isEmpty(customResolverActivity)) { 2213 customResolverActivity = null; 2214 } else { 2215 mCustomResolverComponentName = ComponentName.unflattenFromString( 2216 customResolverActivity); 2217 } 2218 2219 long startTime = SystemClock.uptimeMillis(); 2220 2221 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2222 startTime); 2223 2224 // Set flag to monitor and not change apk file paths when 2225 // scanning install directories. 2226 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2227 2228 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2229 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2230 2231 if (bootClassPath == null) { 2232 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2233 } 2234 2235 if (systemServerClassPath == null) { 2236 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2237 } 2238 2239 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2240 final String[] dexCodeInstructionSets = 2241 getDexCodeInstructionSets( 2242 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2243 2244 /** 2245 * Ensure all external libraries have had dexopt run on them. 2246 */ 2247 if (mSharedLibraries.size() > 0) { 2248 // NOTE: For now, we're compiling these system "shared libraries" 2249 // (and framework jars) into all available architectures. It's possible 2250 // to compile them only when we come across an app that uses them (there's 2251 // already logic for that in scanPackageLI) but that adds some complexity. 2252 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2253 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2254 final String lib = libEntry.path; 2255 if (lib == null) { 2256 continue; 2257 } 2258 2259 try { 2260 // Shared libraries do not have profiles so we perform a full 2261 // AOT compilation (if needed). 2262 int dexoptNeeded = DexFile.getDexOptNeeded( 2263 lib, dexCodeInstructionSet, 2264 getCompilerFilterForReason(REASON_SHARED_APK), 2265 false /* newProfile */); 2266 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2267 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2268 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/, 2269 getCompilerFilterForReason(REASON_SHARED_APK), 2270 StorageManager.UUID_PRIVATE_INTERNAL); 2271 } 2272 } catch (FileNotFoundException e) { 2273 Slog.w(TAG, "Library not found: " + lib); 2274 } catch (IOException | InstallerException e) { 2275 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2276 + e.getMessage()); 2277 } 2278 } 2279 } 2280 } 2281 2282 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2283 2284 final VersionInfo ver = mSettings.getInternalVersion(); 2285 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2286 2287 // when upgrading from pre-M, promote system app permissions from install to runtime 2288 mPromoteSystemApps = 2289 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2290 2291 // save off the names of pre-existing system packages prior to scanning; we don't 2292 // want to automatically grant runtime permissions for new system apps 2293 if (mPromoteSystemApps) { 2294 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2295 while (pkgSettingIter.hasNext()) { 2296 PackageSetting ps = pkgSettingIter.next(); 2297 if (isSystemApp(ps)) { 2298 mExistingSystemPackages.add(ps.name); 2299 } 2300 } 2301 } 2302 2303 // When upgrading from pre-N, we need to handle package extraction like first boot, 2304 // as there is no profiling data available. 2305 mIsPreNUpgrade = !mSettings.isNWorkDone(); 2306 mSettings.setNWorkDone(); 2307 2308 // Collect vendor overlay packages. 2309 // (Do this before scanning any apps.) 2310 // For security and version matching reason, only consider 2311 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2312 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2313 scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 2314 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2315 2316 // Find base frameworks (resource packages without code). 2317 scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 2318 | PackageParser.PARSE_IS_SYSTEM_DIR 2319 | PackageParser.PARSE_IS_PRIVILEGED, 2320 scanFlags | SCAN_NO_DEX, 0); 2321 2322 // Collected privileged system packages. 2323 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2324 scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 2325 | PackageParser.PARSE_IS_SYSTEM_DIR 2326 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2327 2328 // Collect ordinary system packages. 2329 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2330 scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2331 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2332 2333 // Collect all vendor packages. 2334 File vendorAppDir = new File("/vendor/app"); 2335 try { 2336 vendorAppDir = vendorAppDir.getCanonicalFile(); 2337 } catch (IOException e) { 2338 // failed to look up canonical path, continue with original one 2339 } 2340 scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2341 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2342 2343 // Collect all OEM packages. 2344 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2345 scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2346 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2347 2348 // Prune any system packages that no longer exist. 2349 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2350 if (!mOnlyCore) { 2351 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2352 while (psit.hasNext()) { 2353 PackageSetting ps = psit.next(); 2354 2355 /* 2356 * If this is not a system app, it can't be a 2357 * disable system app. 2358 */ 2359 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2360 continue; 2361 } 2362 2363 /* 2364 * If the package is scanned, it's not erased. 2365 */ 2366 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2367 if (scannedPkg != null) { 2368 /* 2369 * If the system app is both scanned and in the 2370 * disabled packages list, then it must have been 2371 * added via OTA. Remove it from the currently 2372 * scanned package so the previously user-installed 2373 * application can be scanned. 2374 */ 2375 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2376 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2377 + ps.name + "; removing system app. Last known codePath=" 2378 + ps.codePathString + ", installStatus=" + ps.installStatus 2379 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2380 + scannedPkg.mVersionCode); 2381 removePackageLI(scannedPkg, true); 2382 mExpectingBetter.put(ps.name, ps.codePath); 2383 } 2384 2385 continue; 2386 } 2387 2388 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2389 psit.remove(); 2390 logCriticalInfo(Log.WARN, "System package " + ps.name 2391 + " no longer exists; it's data will be wiped"); 2392 // Actual deletion of code and data will be handled by later 2393 // reconciliation step 2394 } else { 2395 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2396 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2397 possiblyDeletedUpdatedSystemApps.add(ps.name); 2398 } 2399 } 2400 } 2401 } 2402 2403 //look for any incomplete package installations 2404 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2405 for (int i = 0; i < deletePkgsList.size(); i++) { 2406 // Actual deletion of code and data will be handled by later 2407 // reconciliation step 2408 final String packageName = deletePkgsList.get(i).name; 2409 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2410 synchronized (mPackages) { 2411 mSettings.removePackageLPw(packageName); 2412 } 2413 } 2414 2415 //delete tmp files 2416 deleteTempPackageFiles(); 2417 2418 // Remove any shared userIDs that have no associated packages 2419 mSettings.pruneSharedUsersLPw(); 2420 2421 if (!mOnlyCore) { 2422 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2423 SystemClock.uptimeMillis()); 2424 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2425 2426 scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2427 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2428 2429 scanDirLI(mEphemeralInstallDir, PackageParser.PARSE_IS_EPHEMERAL, 2430 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2431 2432 /** 2433 * Remove disable package settings for any updated system 2434 * apps that were removed via an OTA. If they're not a 2435 * previously-updated app, remove them completely. 2436 * Otherwise, just revoke their system-level permissions. 2437 */ 2438 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2439 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2440 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2441 2442 String msg; 2443 if (deletedPkg == null) { 2444 msg = "Updated system package " + deletedAppName 2445 + " no longer exists; it's data will be wiped"; 2446 // Actual deletion of code and data will be handled by later 2447 // reconciliation step 2448 } else { 2449 msg = "Updated system app + " + deletedAppName 2450 + " no longer present; removing system privileges for " 2451 + deletedAppName; 2452 2453 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2454 2455 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2456 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2457 } 2458 logCriticalInfo(Log.WARN, msg); 2459 } 2460 2461 /** 2462 * Make sure all system apps that we expected to appear on 2463 * the userdata partition actually showed up. If they never 2464 * appeared, crawl back and revive the system version. 2465 */ 2466 for (int i = 0; i < mExpectingBetter.size(); i++) { 2467 final String packageName = mExpectingBetter.keyAt(i); 2468 if (!mPackages.containsKey(packageName)) { 2469 final File scanFile = mExpectingBetter.valueAt(i); 2470 2471 logCriticalInfo(Log.WARN, "Expected better " + packageName 2472 + " but never showed up; reverting to system"); 2473 2474 final int reparseFlags; 2475 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2476 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2477 | PackageParser.PARSE_IS_SYSTEM_DIR 2478 | PackageParser.PARSE_IS_PRIVILEGED; 2479 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2480 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2481 | PackageParser.PARSE_IS_SYSTEM_DIR; 2482 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2483 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2484 | PackageParser.PARSE_IS_SYSTEM_DIR; 2485 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2486 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2487 | PackageParser.PARSE_IS_SYSTEM_DIR; 2488 } else { 2489 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2490 continue; 2491 } 2492 2493 mSettings.enableSystemPackageLPw(packageName); 2494 2495 try { 2496 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2497 } catch (PackageManagerException e) { 2498 Slog.e(TAG, "Failed to parse original system package: " 2499 + e.getMessage()); 2500 } 2501 } 2502 } 2503 } 2504 mExpectingBetter.clear(); 2505 2506 // Resolve protected action filters. Only the setup wizard is allowed to 2507 // have a high priority filter for these actions. 2508 mSetupWizardPackage = getSetupWizardPackageName(); 2509 if (mProtectedFilters.size() > 0) { 2510 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2511 Slog.i(TAG, "No setup wizard;" 2512 + " All protected intents capped to priority 0"); 2513 } 2514 for (ActivityIntentInfo filter : mProtectedFilters) { 2515 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2516 if (DEBUG_FILTERS) { 2517 Slog.i(TAG, "Found setup wizard;" 2518 + " allow priority " + filter.getPriority() + ";" 2519 + " package: " + filter.activity.info.packageName 2520 + " activity: " + filter.activity.className 2521 + " priority: " + filter.getPriority()); 2522 } 2523 // skip setup wizard; allow it to keep the high priority filter 2524 continue; 2525 } 2526 Slog.w(TAG, "Protected action; cap priority to 0;" 2527 + " package: " + filter.activity.info.packageName 2528 + " activity: " + filter.activity.className 2529 + " origPrio: " + filter.getPriority()); 2530 filter.setPriority(0); 2531 } 2532 } 2533 mDeferProtectedFilters = false; 2534 mProtectedFilters.clear(); 2535 2536 // Now that we know all of the shared libraries, update all clients to have 2537 // the correct library paths. 2538 updateAllSharedLibrariesLPw(); 2539 2540 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2541 // NOTE: We ignore potential failures here during a system scan (like 2542 // the rest of the commands above) because there's precious little we 2543 // can do about it. A settings error is reported, though. 2544 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2545 false /* boot complete */); 2546 } 2547 2548 // Now that we know all the packages we are keeping, 2549 // read and update their last usage times. 2550 mPackageUsage.readLP(); 2551 2552 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2553 SystemClock.uptimeMillis()); 2554 Slog.i(TAG, "Time to scan packages: " 2555 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2556 + " seconds"); 2557 2558 // If the platform SDK has changed since the last time we booted, 2559 // we need to re-grant app permission to catch any new ones that 2560 // appear. This is really a hack, and means that apps can in some 2561 // cases get permissions that the user didn't initially explicitly 2562 // allow... it would be nice to have some better way to handle 2563 // this situation. 2564 int updateFlags = UPDATE_PERMISSIONS_ALL; 2565 if (ver.sdkVersion != mSdkVersion) { 2566 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2567 + mSdkVersion + "; regranting permissions for internal storage"); 2568 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2569 } 2570 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2571 ver.sdkVersion = mSdkVersion; 2572 2573 // If this is the first boot or an update from pre-M, and it is a normal 2574 // boot, then we need to initialize the default preferred apps across 2575 // all defined users. 2576 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2577 for (UserInfo user : sUserManager.getUsers(true)) { 2578 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2579 applyFactoryDefaultBrowserLPw(user.id); 2580 primeDomainVerificationsLPw(user.id); 2581 } 2582 } 2583 2584 // Prepare storage for system user really early during boot, 2585 // since core system apps like SettingsProvider and SystemUI 2586 // can't wait for user to start 2587 final int storageFlags; 2588 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2589 storageFlags = StorageManager.FLAG_STORAGE_DE; 2590 } else { 2591 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2592 } 2593 reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2594 storageFlags); 2595 2596 // If this is first boot after an OTA, and a normal boot, then 2597 // we need to clear code cache directories. 2598 if (mIsUpgrade && !onlyCore) { 2599 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2600 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2601 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2602 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2603 // No apps are running this early, so no need to freeze 2604 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2605 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2606 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2607 } 2608 clearAppProfilesLIF(ps.pkg); 2609 } 2610 ver.fingerprint = Build.FINGERPRINT; 2611 } 2612 2613 checkDefaultBrowser(); 2614 2615 // clear only after permissions and other defaults have been updated 2616 mExistingSystemPackages.clear(); 2617 mPromoteSystemApps = false; 2618 2619 // All the changes are done during package scanning. 2620 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2621 2622 // can downgrade to reader 2623 mSettings.writeLPr(); 2624 2625 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2626 SystemClock.uptimeMillis()); 2627 2628 if (!mOnlyCore) { 2629 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2630 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2631 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2632 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2633 mIntentFilterVerifierComponent); 2634 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2635 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 2636 getRequiredSharedLibraryLPr( 2637 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED); 2638 } else { 2639 mRequiredVerifierPackage = null; 2640 mRequiredInstallerPackage = null; 2641 mIntentFilterVerifierComponent = null; 2642 mIntentFilterVerifier = null; 2643 mServicesSystemSharedLibraryPackageName = null; 2644 } 2645 2646 mInstallerService = new PackageInstallerService(context, this); 2647 2648 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2649 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2650 // both the installer and resolver must be present to enable ephemeral 2651 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2652 if (DEBUG_EPHEMERAL) { 2653 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2654 + " installer:" + ephemeralInstallerComponent); 2655 } 2656 mEphemeralResolverComponent = ephemeralResolverComponent; 2657 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2658 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2659 mEphemeralResolverConnection = 2660 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2661 } else { 2662 if (DEBUG_EPHEMERAL) { 2663 final String missingComponent = 2664 (ephemeralResolverComponent == null) 2665 ? (ephemeralInstallerComponent == null) 2666 ? "resolver and installer" 2667 : "resolver" 2668 : "installer"; 2669 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2670 } 2671 mEphemeralResolverComponent = null; 2672 mEphemeralInstallerComponent = null; 2673 mEphemeralResolverConnection = null; 2674 } 2675 2676 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2677 } // synchronized (mPackages) 2678 } // synchronized (mInstallLock) 2679 2680 // Now after opening every single application zip, make sure they 2681 // are all flushed. Not really needed, but keeps things nice and 2682 // tidy. 2683 Runtime.getRuntime().gc(); 2684 2685 // The initial scanning above does many calls into installd while 2686 // holding the mPackages lock, but we're mostly interested in yelling 2687 // once we have a booted system. 2688 mInstaller.setWarnIfHeld(mPackages); 2689 2690 // Expose private service for system components to use. 2691 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2692 } 2693 2694 @Override 2695 public boolean isFirstBoot() { 2696 return !mRestoredSettings; 2697 } 2698 2699 @Override 2700 public boolean isOnlyCoreApps() { 2701 return mOnlyCore; 2702 } 2703 2704 @Override 2705 public boolean isUpgrade() { 2706 return mIsUpgrade; 2707 } 2708 2709 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2710 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2711 2712 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2713 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2714 UserHandle.USER_SYSTEM); 2715 if (matches.size() == 1) { 2716 return matches.get(0).getComponentInfo().packageName; 2717 } else { 2718 Log.e(TAG, "There should probably be exactly one verifier; found " + matches); 2719 return null; 2720 } 2721 } 2722 2723 private @NonNull String getRequiredSharedLibraryLPr(String libraryName) { 2724 synchronized (mPackages) { 2725 SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName); 2726 if (libraryEntry == null) { 2727 throw new IllegalStateException("Missing required shared library:" + libraryName); 2728 } 2729 return libraryEntry.apk; 2730 } 2731 } 2732 2733 private @NonNull String getRequiredInstallerLPr() { 2734 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2735 intent.addCategory(Intent.CATEGORY_DEFAULT); 2736 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2737 2738 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2739 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2740 UserHandle.USER_SYSTEM); 2741 if (matches.size() == 1) { 2742 ResolveInfo resolveInfo = matches.get(0); 2743 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 2744 throw new RuntimeException("The installer must be a privileged app"); 2745 } 2746 return matches.get(0).getComponentInfo().packageName; 2747 } else { 2748 throw new RuntimeException("There must be exactly one installer; found " + matches); 2749 } 2750 } 2751 2752 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2753 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2754 2755 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2756 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2757 UserHandle.USER_SYSTEM); 2758 ResolveInfo best = null; 2759 final int N = matches.size(); 2760 for (int i = 0; i < N; i++) { 2761 final ResolveInfo cur = matches.get(i); 2762 final String packageName = cur.getComponentInfo().packageName; 2763 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2764 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2765 continue; 2766 } 2767 2768 if (best == null || cur.priority > best.priority) { 2769 best = cur; 2770 } 2771 } 2772 2773 if (best != null) { 2774 return best.getComponentInfo().getComponentName(); 2775 } else { 2776 throw new RuntimeException("There must be at least one intent filter verifier"); 2777 } 2778 } 2779 2780 private @Nullable ComponentName getEphemeralResolverLPr() { 2781 final String[] packageArray = 2782 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2783 if (packageArray.length == 0) { 2784 if (DEBUG_EPHEMERAL) { 2785 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2786 } 2787 return null; 2788 } 2789 2790 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2791 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 2792 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2793 UserHandle.USER_SYSTEM); 2794 2795 final int N = resolvers.size(); 2796 if (N == 0) { 2797 if (DEBUG_EPHEMERAL) { 2798 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2799 } 2800 return null; 2801 } 2802 2803 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2804 for (int i = 0; i < N; i++) { 2805 final ResolveInfo info = resolvers.get(i); 2806 2807 if (info.serviceInfo == null) { 2808 continue; 2809 } 2810 2811 final String packageName = info.serviceInfo.packageName; 2812 if (!possiblePackages.contains(packageName)) { 2813 if (DEBUG_EPHEMERAL) { 2814 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2815 + " pkg: " + packageName + ", info:" + info); 2816 } 2817 continue; 2818 } 2819 2820 if (DEBUG_EPHEMERAL) { 2821 Slog.v(TAG, "Ephemeral resolver found;" 2822 + " pkg: " + packageName + ", info:" + info); 2823 } 2824 return new ComponentName(packageName, info.serviceInfo.name); 2825 } 2826 if (DEBUG_EPHEMERAL) { 2827 Slog.v(TAG, "Ephemeral resolver NOT found"); 2828 } 2829 return null; 2830 } 2831 2832 private @Nullable ComponentName getEphemeralInstallerLPr() { 2833 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2834 intent.addCategory(Intent.CATEGORY_DEFAULT); 2835 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2836 2837 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2838 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2839 UserHandle.USER_SYSTEM); 2840 if (matches.size() == 0) { 2841 return null; 2842 } else if (matches.size() == 1) { 2843 return matches.get(0).getComponentInfo().getComponentName(); 2844 } else { 2845 throw new RuntimeException( 2846 "There must be at most one ephemeral installer; found " + matches); 2847 } 2848 } 2849 2850 private void primeDomainVerificationsLPw(int userId) { 2851 if (DEBUG_DOMAIN_VERIFICATION) { 2852 Slog.d(TAG, "Priming domain verifications in user " + userId); 2853 } 2854 2855 SystemConfig systemConfig = SystemConfig.getInstance(); 2856 ArraySet<String> packages = systemConfig.getLinkedApps(); 2857 ArraySet<String> domains = new ArraySet<String>(); 2858 2859 for (String packageName : packages) { 2860 PackageParser.Package pkg = mPackages.get(packageName); 2861 if (pkg != null) { 2862 if (!pkg.isSystemApp()) { 2863 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2864 continue; 2865 } 2866 2867 domains.clear(); 2868 for (PackageParser.Activity a : pkg.activities) { 2869 for (ActivityIntentInfo filter : a.intents) { 2870 if (hasValidDomains(filter)) { 2871 domains.addAll(filter.getHostsList()); 2872 } 2873 } 2874 } 2875 2876 if (domains.size() > 0) { 2877 if (DEBUG_DOMAIN_VERIFICATION) { 2878 Slog.v(TAG, " + " + packageName); 2879 } 2880 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2881 // state w.r.t. the formal app-linkage "no verification attempted" state; 2882 // and then 'always' in the per-user state actually used for intent resolution. 2883 final IntentFilterVerificationInfo ivi; 2884 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2885 new ArrayList<String>(domains)); 2886 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2887 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2888 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2889 } else { 2890 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2891 + "' does not handle web links"); 2892 } 2893 } else { 2894 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 2895 } 2896 } 2897 2898 scheduleWritePackageRestrictionsLocked(userId); 2899 scheduleWriteSettingsLocked(); 2900 } 2901 2902 private void applyFactoryDefaultBrowserLPw(int userId) { 2903 // The default browser app's package name is stored in a string resource, 2904 // with a product-specific overlay used for vendor customization. 2905 String browserPkg = mContext.getResources().getString( 2906 com.android.internal.R.string.default_browser); 2907 if (!TextUtils.isEmpty(browserPkg)) { 2908 // non-empty string => required to be a known package 2909 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2910 if (ps == null) { 2911 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2912 browserPkg = null; 2913 } else { 2914 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2915 } 2916 } 2917 2918 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2919 // default. If there's more than one, just leave everything alone. 2920 if (browserPkg == null) { 2921 calculateDefaultBrowserLPw(userId); 2922 } 2923 } 2924 2925 private void calculateDefaultBrowserLPw(int userId) { 2926 List<String> allBrowsers = resolveAllBrowserApps(userId); 2927 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2928 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2929 } 2930 2931 private List<String> resolveAllBrowserApps(int userId) { 2932 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2933 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 2934 PackageManager.MATCH_ALL, userId); 2935 2936 final int count = list.size(); 2937 List<String> result = new ArrayList<String>(count); 2938 for (int i=0; i<count; i++) { 2939 ResolveInfo info = list.get(i); 2940 if (info.activityInfo == null 2941 || !info.handleAllWebDataURI 2942 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2943 || result.contains(info.activityInfo.packageName)) { 2944 continue; 2945 } 2946 result.add(info.activityInfo.packageName); 2947 } 2948 2949 return result; 2950 } 2951 2952 private boolean packageIsBrowser(String packageName, int userId) { 2953 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 2954 PackageManager.MATCH_ALL, userId); 2955 final int N = list.size(); 2956 for (int i = 0; i < N; i++) { 2957 ResolveInfo info = list.get(i); 2958 if (packageName.equals(info.activityInfo.packageName)) { 2959 return true; 2960 } 2961 } 2962 return false; 2963 } 2964 2965 private void checkDefaultBrowser() { 2966 final int myUserId = UserHandle.myUserId(); 2967 final String packageName = getDefaultBrowserPackageName(myUserId); 2968 if (packageName != null) { 2969 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2970 if (info == null) { 2971 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2972 synchronized (mPackages) { 2973 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2974 } 2975 } 2976 } 2977 } 2978 2979 @Override 2980 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2981 throws RemoteException { 2982 try { 2983 return super.onTransact(code, data, reply, flags); 2984 } catch (RuntimeException e) { 2985 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2986 Slog.wtf(TAG, "Package Manager Crash", e); 2987 } 2988 throw e; 2989 } 2990 } 2991 2992 static int[] appendInts(int[] cur, int[] add) { 2993 if (add == null) return cur; 2994 if (cur == null) return add; 2995 final int N = add.length; 2996 for (int i=0; i<N; i++) { 2997 cur = appendInt(cur, add[i]); 2998 } 2999 return cur; 3000 } 3001 3002 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3003 if (!sUserManager.exists(userId)) return null; 3004 if (ps == null) { 3005 return null; 3006 } 3007 final PackageParser.Package p = ps.pkg; 3008 if (p == null) { 3009 return null; 3010 } 3011 3012 final PermissionsState permissionsState = ps.getPermissionsState(); 3013 3014 final int[] gids = permissionsState.computeGids(userId); 3015 final Set<String> permissions = permissionsState.getPermissions(userId); 3016 final PackageUserState state = ps.readUserState(userId); 3017 3018 return PackageParser.generatePackageInfo(p, gids, flags, 3019 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3020 } 3021 3022 @Override 3023 public void checkPackageStartable(String packageName, int userId) { 3024 final boolean userKeyUnlocked = isUserKeyUnlocked(userId); 3025 3026 synchronized (mPackages) { 3027 final PackageSetting ps = mSettings.mPackages.get(packageName); 3028 if (ps == null) { 3029 throw new SecurityException("Package " + packageName + " was not found!"); 3030 } 3031 3032 if (!ps.getInstalled(userId)) { 3033 throw new SecurityException( 3034 "Package " + packageName + " was not installed for user " + userId + "!"); 3035 } 3036 3037 if (mSafeMode && !ps.isSystem()) { 3038 throw new SecurityException("Package " + packageName + " not a system app!"); 3039 } 3040 3041 if (mFrozenPackages.contains(packageName)) { 3042 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3043 } 3044 3045 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3046 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3047 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3048 } 3049 } 3050 } 3051 3052 @Override 3053 public boolean isPackageAvailable(String packageName, int userId) { 3054 if (!sUserManager.exists(userId)) return false; 3055 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3056 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3057 synchronized (mPackages) { 3058 PackageParser.Package p = mPackages.get(packageName); 3059 if (p != null) { 3060 final PackageSetting ps = (PackageSetting) p.mExtras; 3061 if (ps != null) { 3062 final PackageUserState state = ps.readUserState(userId); 3063 if (state != null) { 3064 return PackageParser.isAvailable(state); 3065 } 3066 } 3067 } 3068 } 3069 return false; 3070 } 3071 3072 @Override 3073 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3074 if (!sUserManager.exists(userId)) return null; 3075 flags = updateFlagsForPackage(flags, userId, packageName); 3076 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3077 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3078 // reader 3079 synchronized (mPackages) { 3080 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3081 PackageParser.Package p = null; 3082 if (matchFactoryOnly) { 3083 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3084 if (ps != null) { 3085 return generatePackageInfo(ps, flags, userId); 3086 } 3087 } 3088 if (p == null) { 3089 p = mPackages.get(packageName); 3090 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3091 return null; 3092 } 3093 } 3094 if (DEBUG_PACKAGE_INFO) 3095 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3096 if (p != null) { 3097 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3098 } 3099 if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3100 final PackageSetting ps = mSettings.mPackages.get(packageName); 3101 return generatePackageInfo(ps, flags, userId); 3102 } 3103 } 3104 return null; 3105 } 3106 3107 @Override 3108 public String[] currentToCanonicalPackageNames(String[] names) { 3109 String[] out = new String[names.length]; 3110 // reader 3111 synchronized (mPackages) { 3112 for (int i=names.length-1; i>=0; i--) { 3113 PackageSetting ps = mSettings.mPackages.get(names[i]); 3114 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3115 } 3116 } 3117 return out; 3118 } 3119 3120 @Override 3121 public String[] canonicalToCurrentPackageNames(String[] names) { 3122 String[] out = new String[names.length]; 3123 // reader 3124 synchronized (mPackages) { 3125 for (int i=names.length-1; i>=0; i--) { 3126 String cur = mSettings.mRenamedPackages.get(names[i]); 3127 out[i] = cur != null ? cur : names[i]; 3128 } 3129 } 3130 return out; 3131 } 3132 3133 @Override 3134 public int getPackageUid(String packageName, int flags, int userId) { 3135 if (!sUserManager.exists(userId)) return -1; 3136 flags = updateFlagsForPackage(flags, userId, packageName); 3137 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3138 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3139 3140 // reader 3141 synchronized (mPackages) { 3142 final PackageParser.Package p = mPackages.get(packageName); 3143 if (p != null && p.isMatch(flags)) { 3144 return UserHandle.getUid(userId, p.applicationInfo.uid); 3145 } 3146 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3147 final PackageSetting ps = mSettings.mPackages.get(packageName); 3148 if (ps != null && ps.isMatch(flags)) { 3149 return UserHandle.getUid(userId, ps.appId); 3150 } 3151 } 3152 } 3153 3154 return -1; 3155 } 3156 3157 @Override 3158 public int[] getPackageGids(String packageName, int flags, int userId) { 3159 if (!sUserManager.exists(userId)) return null; 3160 flags = updateFlagsForPackage(flags, userId, packageName); 3161 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3162 false /* requireFullPermission */, false /* checkShell */, 3163 "getPackageGids"); 3164 3165 // reader 3166 synchronized (mPackages) { 3167 final PackageParser.Package p = mPackages.get(packageName); 3168 if (p != null && p.isMatch(flags)) { 3169 PackageSetting ps = (PackageSetting) p.mExtras; 3170 return ps.getPermissionsState().computeGids(userId); 3171 } 3172 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3173 final PackageSetting ps = mSettings.mPackages.get(packageName); 3174 if (ps != null && ps.isMatch(flags)) { 3175 return ps.getPermissionsState().computeGids(userId); 3176 } 3177 } 3178 } 3179 3180 return null; 3181 } 3182 3183 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3184 if (bp.perm != null) { 3185 return PackageParser.generatePermissionInfo(bp.perm, flags); 3186 } 3187 PermissionInfo pi = new PermissionInfo(); 3188 pi.name = bp.name; 3189 pi.packageName = bp.sourcePackage; 3190 pi.nonLocalizedLabel = bp.name; 3191 pi.protectionLevel = bp.protectionLevel; 3192 return pi; 3193 } 3194 3195 @Override 3196 public PermissionInfo getPermissionInfo(String name, int flags) { 3197 // reader 3198 synchronized (mPackages) { 3199 final BasePermission p = mSettings.mPermissions.get(name); 3200 if (p != null) { 3201 return generatePermissionInfo(p, flags); 3202 } 3203 return null; 3204 } 3205 } 3206 3207 @Override 3208 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3209 int flags) { 3210 // reader 3211 synchronized (mPackages) { 3212 if (group != null && !mPermissionGroups.containsKey(group)) { 3213 // This is thrown as NameNotFoundException 3214 return null; 3215 } 3216 3217 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3218 for (BasePermission p : mSettings.mPermissions.values()) { 3219 if (group == null) { 3220 if (p.perm == null || p.perm.info.group == null) { 3221 out.add(generatePermissionInfo(p, flags)); 3222 } 3223 } else { 3224 if (p.perm != null && group.equals(p.perm.info.group)) { 3225 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3226 } 3227 } 3228 } 3229 return new ParceledListSlice<>(out); 3230 } 3231 } 3232 3233 @Override 3234 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3235 // reader 3236 synchronized (mPackages) { 3237 return PackageParser.generatePermissionGroupInfo( 3238 mPermissionGroups.get(name), flags); 3239 } 3240 } 3241 3242 @Override 3243 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3244 // reader 3245 synchronized (mPackages) { 3246 final int N = mPermissionGroups.size(); 3247 ArrayList<PermissionGroupInfo> out 3248 = new ArrayList<PermissionGroupInfo>(N); 3249 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3250 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3251 } 3252 return new ParceledListSlice<>(out); 3253 } 3254 } 3255 3256 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3257 int userId) { 3258 if (!sUserManager.exists(userId)) return null; 3259 PackageSetting ps = mSettings.mPackages.get(packageName); 3260 if (ps != null) { 3261 if (ps.pkg == null) { 3262 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3263 if (pInfo != null) { 3264 return pInfo.applicationInfo; 3265 } 3266 return null; 3267 } 3268 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3269 ps.readUserState(userId), userId); 3270 } 3271 return null; 3272 } 3273 3274 @Override 3275 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3276 if (!sUserManager.exists(userId)) return null; 3277 flags = updateFlagsForApplication(flags, userId, packageName); 3278 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3279 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3280 // writer 3281 synchronized (mPackages) { 3282 PackageParser.Package p = mPackages.get(packageName); 3283 if (DEBUG_PACKAGE_INFO) Log.v( 3284 TAG, "getApplicationInfo " + packageName 3285 + ": " + p); 3286 if (p != null) { 3287 PackageSetting ps = mSettings.mPackages.get(packageName); 3288 if (ps == null) return null; 3289 // Note: isEnabledLP() does not apply here - always return info 3290 return PackageParser.generateApplicationInfo( 3291 p, flags, ps.readUserState(userId), userId); 3292 } 3293 if ("android".equals(packageName)||"system".equals(packageName)) { 3294 return mAndroidApplication; 3295 } 3296 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3297 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3298 } 3299 } 3300 return null; 3301 } 3302 3303 @Override 3304 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3305 final IPackageDataObserver observer) { 3306 mContext.enforceCallingOrSelfPermission( 3307 android.Manifest.permission.CLEAR_APP_CACHE, null); 3308 // Queue up an async operation since clearing cache may take a little while. 3309 mHandler.post(new Runnable() { 3310 public void run() { 3311 mHandler.removeCallbacks(this); 3312 boolean success = true; 3313 synchronized (mInstallLock) { 3314 try { 3315 mInstaller.freeCache(volumeUuid, freeStorageSize); 3316 } catch (InstallerException e) { 3317 Slog.w(TAG, "Couldn't clear application caches: " + e); 3318 success = false; 3319 } 3320 } 3321 if (observer != null) { 3322 try { 3323 observer.onRemoveCompleted(null, success); 3324 } catch (RemoteException e) { 3325 Slog.w(TAG, "RemoveException when invoking call back"); 3326 } 3327 } 3328 } 3329 }); 3330 } 3331 3332 @Override 3333 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3334 final IntentSender pi) { 3335 mContext.enforceCallingOrSelfPermission( 3336 android.Manifest.permission.CLEAR_APP_CACHE, null); 3337 // Queue up an async operation since clearing cache may take a little while. 3338 mHandler.post(new Runnable() { 3339 public void run() { 3340 mHandler.removeCallbacks(this); 3341 boolean success = true; 3342 synchronized (mInstallLock) { 3343 try { 3344 mInstaller.freeCache(volumeUuid, freeStorageSize); 3345 } catch (InstallerException e) { 3346 Slog.w(TAG, "Couldn't clear application caches: " + e); 3347 success = false; 3348 } 3349 } 3350 if(pi != null) { 3351 try { 3352 // Callback via pending intent 3353 int code = success ? 1 : 0; 3354 pi.sendIntent(null, code, null, 3355 null, null); 3356 } catch (SendIntentException e1) { 3357 Slog.i(TAG, "Failed to send pending intent"); 3358 } 3359 } 3360 } 3361 }); 3362 } 3363 3364 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3365 synchronized (mInstallLock) { 3366 try { 3367 mInstaller.freeCache(volumeUuid, freeStorageSize); 3368 } catch (InstallerException e) { 3369 throw new IOException("Failed to free enough space", e); 3370 } 3371 } 3372 } 3373 3374 /** 3375 * Return if the user key is currently unlocked. 3376 */ 3377 private boolean isUserKeyUnlocked(int userId) { 3378 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 3379 final IMountService mount = IMountService.Stub 3380 .asInterface(ServiceManager.getService("mount")); 3381 if (mount == null) { 3382 Slog.w(TAG, "Early during boot, assuming locked"); 3383 return false; 3384 } 3385 final long token = Binder.clearCallingIdentity(); 3386 try { 3387 return mount.isUserKeyUnlocked(userId); 3388 } catch (RemoteException e) { 3389 throw e.rethrowAsRuntimeException(); 3390 } finally { 3391 Binder.restoreCallingIdentity(token); 3392 } 3393 } else { 3394 return true; 3395 } 3396 } 3397 3398 /** 3399 * Update given flags based on encryption status of current user. 3400 */ 3401 private int updateFlags(int flags, int userId) { 3402 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3403 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3404 // Caller expressed an explicit opinion about what encryption 3405 // aware/unaware components they want to see, so fall through and 3406 // give them what they want 3407 } else { 3408 // Caller expressed no opinion, so match based on user state 3409 if (isUserKeyUnlocked(userId)) { 3410 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3411 } else { 3412 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3413 } 3414 } 3415 return flags; 3416 } 3417 3418 /** 3419 * Update given flags when being used to request {@link PackageInfo}. 3420 */ 3421 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3422 boolean triaged = true; 3423 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3424 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3425 // Caller is asking for component details, so they'd better be 3426 // asking for specific encryption matching behavior, or be triaged 3427 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3428 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3429 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3430 triaged = false; 3431 } 3432 } 3433 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3434 | PackageManager.MATCH_SYSTEM_ONLY 3435 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3436 triaged = false; 3437 } 3438 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3439 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3440 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3441 } 3442 return updateFlags(flags, userId); 3443 } 3444 3445 /** 3446 * Update given flags when being used to request {@link ApplicationInfo}. 3447 */ 3448 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3449 return updateFlagsForPackage(flags, userId, cookie); 3450 } 3451 3452 /** 3453 * Update given flags when being used to request {@link ComponentInfo}. 3454 */ 3455 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3456 if (cookie instanceof Intent) { 3457 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3458 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3459 } 3460 } 3461 3462 boolean triaged = true; 3463 // Caller is asking for component details, so they'd better be 3464 // asking for specific encryption matching behavior, or be triaged 3465 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3466 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3467 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3468 triaged = false; 3469 } 3470 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3471 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3472 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3473 } 3474 3475 return updateFlags(flags, userId); 3476 } 3477 3478 /** 3479 * Update given flags when being used to request {@link ResolveInfo}. 3480 */ 3481 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3482 // Safe mode means we shouldn't match any third-party components 3483 if (mSafeMode) { 3484 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3485 } 3486 3487 return updateFlagsForComponent(flags, userId, cookie); 3488 } 3489 3490 @Override 3491 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3492 if (!sUserManager.exists(userId)) return null; 3493 flags = updateFlagsForComponent(flags, userId, component); 3494 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3495 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3496 synchronized (mPackages) { 3497 PackageParser.Activity a = mActivities.mActivities.get(component); 3498 3499 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3500 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3501 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3502 if (ps == null) return null; 3503 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3504 userId); 3505 } 3506 if (mResolveComponentName.equals(component)) { 3507 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3508 new PackageUserState(), userId); 3509 } 3510 } 3511 return null; 3512 } 3513 3514 @Override 3515 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3516 String resolvedType) { 3517 synchronized (mPackages) { 3518 if (component.equals(mResolveComponentName)) { 3519 // The resolver supports EVERYTHING! 3520 return true; 3521 } 3522 PackageParser.Activity a = mActivities.mActivities.get(component); 3523 if (a == null) { 3524 return false; 3525 } 3526 for (int i=0; i<a.intents.size(); i++) { 3527 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3528 intent.getData(), intent.getCategories(), TAG) >= 0) { 3529 return true; 3530 } 3531 } 3532 return false; 3533 } 3534 } 3535 3536 @Override 3537 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3538 if (!sUserManager.exists(userId)) return null; 3539 flags = updateFlagsForComponent(flags, userId, component); 3540 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3541 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3542 synchronized (mPackages) { 3543 PackageParser.Activity a = mReceivers.mActivities.get(component); 3544 if (DEBUG_PACKAGE_INFO) Log.v( 3545 TAG, "getReceiverInfo " + component + ": " + a); 3546 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3547 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3548 if (ps == null) return null; 3549 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3550 userId); 3551 } 3552 } 3553 return null; 3554 } 3555 3556 @Override 3557 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3558 if (!sUserManager.exists(userId)) return null; 3559 flags = updateFlagsForComponent(flags, userId, component); 3560 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3561 false /* requireFullPermission */, false /* checkShell */, "get service info"); 3562 synchronized (mPackages) { 3563 PackageParser.Service s = mServices.mServices.get(component); 3564 if (DEBUG_PACKAGE_INFO) Log.v( 3565 TAG, "getServiceInfo " + component + ": " + s); 3566 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3567 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3568 if (ps == null) return null; 3569 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3570 userId); 3571 } 3572 } 3573 return null; 3574 } 3575 3576 @Override 3577 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3578 if (!sUserManager.exists(userId)) return null; 3579 flags = updateFlagsForComponent(flags, userId, component); 3580 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3581 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 3582 synchronized (mPackages) { 3583 PackageParser.Provider p = mProviders.mProviders.get(component); 3584 if (DEBUG_PACKAGE_INFO) Log.v( 3585 TAG, "getProviderInfo " + component + ": " + p); 3586 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3587 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3588 if (ps == null) return null; 3589 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3590 userId); 3591 } 3592 } 3593 return null; 3594 } 3595 3596 @Override 3597 public String[] getSystemSharedLibraryNames() { 3598 Set<String> libSet; 3599 synchronized (mPackages) { 3600 libSet = mSharedLibraries.keySet(); 3601 int size = libSet.size(); 3602 if (size > 0) { 3603 String[] libs = new String[size]; 3604 libSet.toArray(libs); 3605 return libs; 3606 } 3607 } 3608 return null; 3609 } 3610 3611 @Override 3612 public @NonNull String getServicesSystemSharedLibraryPackageName() { 3613 synchronized (mPackages) { 3614 return mServicesSystemSharedLibraryPackageName; 3615 } 3616 } 3617 3618 @Override 3619 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 3620 synchronized (mPackages) { 3621 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values()); 3622 3623 final FeatureInfo fi = new FeatureInfo(); 3624 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3625 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3626 res.add(fi); 3627 3628 return new ParceledListSlice<>(res); 3629 } 3630 } 3631 3632 @Override 3633 public boolean hasSystemFeature(String name, int version) { 3634 synchronized (mPackages) { 3635 final FeatureInfo feat = mAvailableFeatures.get(name); 3636 if (feat == null) { 3637 return false; 3638 } else { 3639 return feat.version >= version; 3640 } 3641 } 3642 } 3643 3644 @Override 3645 public int checkPermission(String permName, String pkgName, int userId) { 3646 if (!sUserManager.exists(userId)) { 3647 return PackageManager.PERMISSION_DENIED; 3648 } 3649 3650 synchronized (mPackages) { 3651 final PackageParser.Package p = mPackages.get(pkgName); 3652 if (p != null && p.mExtras != null) { 3653 final PackageSetting ps = (PackageSetting) p.mExtras; 3654 final PermissionsState permissionsState = ps.getPermissionsState(); 3655 if (permissionsState.hasPermission(permName, userId)) { 3656 return PackageManager.PERMISSION_GRANTED; 3657 } 3658 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3659 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3660 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3661 return PackageManager.PERMISSION_GRANTED; 3662 } 3663 } 3664 } 3665 3666 return PackageManager.PERMISSION_DENIED; 3667 } 3668 3669 @Override 3670 public int checkUidPermission(String permName, int uid) { 3671 final int userId = UserHandle.getUserId(uid); 3672 3673 if (!sUserManager.exists(userId)) { 3674 return PackageManager.PERMISSION_DENIED; 3675 } 3676 3677 synchronized (mPackages) { 3678 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3679 if (obj != null) { 3680 final SettingBase ps = (SettingBase) obj; 3681 final PermissionsState permissionsState = ps.getPermissionsState(); 3682 if (permissionsState.hasPermission(permName, userId)) { 3683 return PackageManager.PERMISSION_GRANTED; 3684 } 3685 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3686 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3687 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3688 return PackageManager.PERMISSION_GRANTED; 3689 } 3690 } else { 3691 ArraySet<String> perms = mSystemPermissions.get(uid); 3692 if (perms != null) { 3693 if (perms.contains(permName)) { 3694 return PackageManager.PERMISSION_GRANTED; 3695 } 3696 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3697 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3698 return PackageManager.PERMISSION_GRANTED; 3699 } 3700 } 3701 } 3702 } 3703 3704 return PackageManager.PERMISSION_DENIED; 3705 } 3706 3707 @Override 3708 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3709 if (UserHandle.getCallingUserId() != userId) { 3710 mContext.enforceCallingPermission( 3711 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3712 "isPermissionRevokedByPolicy for user " + userId); 3713 } 3714 3715 if (checkPermission(permission, packageName, userId) 3716 == PackageManager.PERMISSION_GRANTED) { 3717 return false; 3718 } 3719 3720 final long identity = Binder.clearCallingIdentity(); 3721 try { 3722 final int flags = getPermissionFlags(permission, packageName, userId); 3723 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3724 } finally { 3725 Binder.restoreCallingIdentity(identity); 3726 } 3727 } 3728 3729 @Override 3730 public String getPermissionControllerPackageName() { 3731 synchronized (mPackages) { 3732 return mRequiredInstallerPackage; 3733 } 3734 } 3735 3736 /** 3737 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3738 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3739 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3740 * @param message the message to log on security exception 3741 */ 3742 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3743 boolean checkShell, String message) { 3744 if (userId < 0) { 3745 throw new IllegalArgumentException("Invalid userId " + userId); 3746 } 3747 if (checkShell) { 3748 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3749 } 3750 if (userId == UserHandle.getUserId(callingUid)) return; 3751 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3752 if (requireFullPermission) { 3753 mContext.enforceCallingOrSelfPermission( 3754 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3755 } else { 3756 try { 3757 mContext.enforceCallingOrSelfPermission( 3758 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3759 } catch (SecurityException se) { 3760 mContext.enforceCallingOrSelfPermission( 3761 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3762 } 3763 } 3764 } 3765 } 3766 3767 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3768 if (callingUid == Process.SHELL_UID) { 3769 if (userHandle >= 0 3770 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3771 throw new SecurityException("Shell does not have permission to access user " 3772 + userHandle); 3773 } else if (userHandle < 0) { 3774 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3775 + Debug.getCallers(3)); 3776 } 3777 } 3778 } 3779 3780 private BasePermission findPermissionTreeLP(String permName) { 3781 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3782 if (permName.startsWith(bp.name) && 3783 permName.length() > bp.name.length() && 3784 permName.charAt(bp.name.length()) == '.') { 3785 return bp; 3786 } 3787 } 3788 return null; 3789 } 3790 3791 private BasePermission checkPermissionTreeLP(String permName) { 3792 if (permName != null) { 3793 BasePermission bp = findPermissionTreeLP(permName); 3794 if (bp != null) { 3795 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3796 return bp; 3797 } 3798 throw new SecurityException("Calling uid " 3799 + Binder.getCallingUid() 3800 + " is not allowed to add to permission tree " 3801 + bp.name + " owned by uid " + bp.uid); 3802 } 3803 } 3804 throw new SecurityException("No permission tree found for " + permName); 3805 } 3806 3807 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3808 if (s1 == null) { 3809 return s2 == null; 3810 } 3811 if (s2 == null) { 3812 return false; 3813 } 3814 if (s1.getClass() != s2.getClass()) { 3815 return false; 3816 } 3817 return s1.equals(s2); 3818 } 3819 3820 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3821 if (pi1.icon != pi2.icon) return false; 3822 if (pi1.logo != pi2.logo) return false; 3823 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3824 if (!compareStrings(pi1.name, pi2.name)) return false; 3825 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3826 // We'll take care of setting this one. 3827 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3828 // These are not currently stored in settings. 3829 //if (!compareStrings(pi1.group, pi2.group)) return false; 3830 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3831 //if (pi1.labelRes != pi2.labelRes) return false; 3832 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3833 return true; 3834 } 3835 3836 int permissionInfoFootprint(PermissionInfo info) { 3837 int size = info.name.length(); 3838 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3839 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3840 return size; 3841 } 3842 3843 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3844 int size = 0; 3845 for (BasePermission perm : mSettings.mPermissions.values()) { 3846 if (perm.uid == tree.uid) { 3847 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3848 } 3849 } 3850 return size; 3851 } 3852 3853 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3854 // We calculate the max size of permissions defined by this uid and throw 3855 // if that plus the size of 'info' would exceed our stated maximum. 3856 if (tree.uid != Process.SYSTEM_UID) { 3857 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3858 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3859 throw new SecurityException("Permission tree size cap exceeded"); 3860 } 3861 } 3862 } 3863 3864 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3865 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3866 throw new SecurityException("Label must be specified in permission"); 3867 } 3868 BasePermission tree = checkPermissionTreeLP(info.name); 3869 BasePermission bp = mSettings.mPermissions.get(info.name); 3870 boolean added = bp == null; 3871 boolean changed = true; 3872 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3873 if (added) { 3874 enforcePermissionCapLocked(info, tree); 3875 bp = new BasePermission(info.name, tree.sourcePackage, 3876 BasePermission.TYPE_DYNAMIC); 3877 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3878 throw new SecurityException( 3879 "Not allowed to modify non-dynamic permission " 3880 + info.name); 3881 } else { 3882 if (bp.protectionLevel == fixedLevel 3883 && bp.perm.owner.equals(tree.perm.owner) 3884 && bp.uid == tree.uid 3885 && comparePermissionInfos(bp.perm.info, info)) { 3886 changed = false; 3887 } 3888 } 3889 bp.protectionLevel = fixedLevel; 3890 info = new PermissionInfo(info); 3891 info.protectionLevel = fixedLevel; 3892 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3893 bp.perm.info.packageName = tree.perm.info.packageName; 3894 bp.uid = tree.uid; 3895 if (added) { 3896 mSettings.mPermissions.put(info.name, bp); 3897 } 3898 if (changed) { 3899 if (!async) { 3900 mSettings.writeLPr(); 3901 } else { 3902 scheduleWriteSettingsLocked(); 3903 } 3904 } 3905 return added; 3906 } 3907 3908 @Override 3909 public boolean addPermission(PermissionInfo info) { 3910 synchronized (mPackages) { 3911 return addPermissionLocked(info, false); 3912 } 3913 } 3914 3915 @Override 3916 public boolean addPermissionAsync(PermissionInfo info) { 3917 synchronized (mPackages) { 3918 return addPermissionLocked(info, true); 3919 } 3920 } 3921 3922 @Override 3923 public void removePermission(String name) { 3924 synchronized (mPackages) { 3925 checkPermissionTreeLP(name); 3926 BasePermission bp = mSettings.mPermissions.get(name); 3927 if (bp != null) { 3928 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3929 throw new SecurityException( 3930 "Not allowed to modify non-dynamic permission " 3931 + name); 3932 } 3933 mSettings.mPermissions.remove(name); 3934 mSettings.writeLPr(); 3935 } 3936 } 3937 } 3938 3939 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 3940 BasePermission bp) { 3941 int index = pkg.requestedPermissions.indexOf(bp.name); 3942 if (index == -1) { 3943 throw new SecurityException("Package " + pkg.packageName 3944 + " has not requested permission " + bp.name); 3945 } 3946 if (!bp.isRuntime() && !bp.isDevelopment()) { 3947 throw new SecurityException("Permission " + bp.name 3948 + " is not a changeable permission type"); 3949 } 3950 } 3951 3952 @Override 3953 public void grantRuntimePermission(String packageName, String name, final int userId) { 3954 if (!sUserManager.exists(userId)) { 3955 Log.e(TAG, "No such user:" + userId); 3956 return; 3957 } 3958 3959 mContext.enforceCallingOrSelfPermission( 3960 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 3961 "grantRuntimePermission"); 3962 3963 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3964 true /* requireFullPermission */, true /* checkShell */, 3965 "grantRuntimePermission"); 3966 3967 final int uid; 3968 final SettingBase sb; 3969 3970 synchronized (mPackages) { 3971 final PackageParser.Package pkg = mPackages.get(packageName); 3972 if (pkg == null) { 3973 throw new IllegalArgumentException("Unknown package: " + packageName); 3974 } 3975 3976 final BasePermission bp = mSettings.mPermissions.get(name); 3977 if (bp == null) { 3978 throw new IllegalArgumentException("Unknown permission: " + name); 3979 } 3980 3981 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3982 3983 // If a permission review is required for legacy apps we represent 3984 // their permissions as always granted runtime ones since we need 3985 // to keep the review required permission flag per user while an 3986 // install permission's state is shared across all users. 3987 if (Build.PERMISSIONS_REVIEW_REQUIRED 3988 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 3989 && bp.isRuntime()) { 3990 return; 3991 } 3992 3993 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3994 sb = (SettingBase) pkg.mExtras; 3995 if (sb == null) { 3996 throw new IllegalArgumentException("Unknown package: " + packageName); 3997 } 3998 3999 final PermissionsState permissionsState = sb.getPermissionsState(); 4000 4001 final int flags = permissionsState.getPermissionFlags(name, userId); 4002 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4003 throw new SecurityException("Cannot grant system fixed permission " 4004 + name + " for package " + packageName); 4005 } 4006 4007 if (bp.isDevelopment()) { 4008 // Development permissions must be handled specially, since they are not 4009 // normal runtime permissions. For now they apply to all users. 4010 if (permissionsState.grantInstallPermission(bp) != 4011 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4012 scheduleWriteSettingsLocked(); 4013 } 4014 return; 4015 } 4016 4017 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4018 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4019 return; 4020 } 4021 4022 final int result = permissionsState.grantRuntimePermission(bp, userId); 4023 switch (result) { 4024 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4025 return; 4026 } 4027 4028 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4029 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4030 mHandler.post(new Runnable() { 4031 @Override 4032 public void run() { 4033 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4034 } 4035 }); 4036 } 4037 break; 4038 } 4039 4040 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4041 4042 // Not critical if that is lost - app has to request again. 4043 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4044 } 4045 4046 // Only need to do this if user is initialized. Otherwise it's a new user 4047 // and there are no processes running as the user yet and there's no need 4048 // to make an expensive call to remount processes for the changed permissions. 4049 if (READ_EXTERNAL_STORAGE.equals(name) 4050 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4051 final long token = Binder.clearCallingIdentity(); 4052 try { 4053 if (sUserManager.isInitialized(userId)) { 4054 MountServiceInternal mountServiceInternal = LocalServices.getService( 4055 MountServiceInternal.class); 4056 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 4057 } 4058 } finally { 4059 Binder.restoreCallingIdentity(token); 4060 } 4061 } 4062 } 4063 4064 @Override 4065 public void revokeRuntimePermission(String packageName, String name, int userId) { 4066 if (!sUserManager.exists(userId)) { 4067 Log.e(TAG, "No such user:" + userId); 4068 return; 4069 } 4070 4071 mContext.enforceCallingOrSelfPermission( 4072 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4073 "revokeRuntimePermission"); 4074 4075 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4076 true /* requireFullPermission */, true /* checkShell */, 4077 "revokeRuntimePermission"); 4078 4079 final int appId; 4080 4081 synchronized (mPackages) { 4082 final PackageParser.Package pkg = mPackages.get(packageName); 4083 if (pkg == null) { 4084 throw new IllegalArgumentException("Unknown package: " + packageName); 4085 } 4086 4087 final BasePermission bp = mSettings.mPermissions.get(name); 4088 if (bp == null) { 4089 throw new IllegalArgumentException("Unknown permission: " + name); 4090 } 4091 4092 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4093 4094 // If a permission review is required for legacy apps we represent 4095 // their permissions as always granted runtime ones since we need 4096 // to keep the review required permission flag per user while an 4097 // install permission's state is shared across all users. 4098 if (Build.PERMISSIONS_REVIEW_REQUIRED 4099 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4100 && bp.isRuntime()) { 4101 return; 4102 } 4103 4104 SettingBase sb = (SettingBase) pkg.mExtras; 4105 if (sb == null) { 4106 throw new IllegalArgumentException("Unknown package: " + packageName); 4107 } 4108 4109 final PermissionsState permissionsState = sb.getPermissionsState(); 4110 4111 final int flags = permissionsState.getPermissionFlags(name, userId); 4112 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4113 throw new SecurityException("Cannot revoke system fixed permission " 4114 + name + " for package " + packageName); 4115 } 4116 4117 if (bp.isDevelopment()) { 4118 // Development permissions must be handled specially, since they are not 4119 // normal runtime permissions. For now they apply to all users. 4120 if (permissionsState.revokeInstallPermission(bp) != 4121 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4122 scheduleWriteSettingsLocked(); 4123 } 4124 return; 4125 } 4126 4127 if (permissionsState.revokeRuntimePermission(bp, userId) == 4128 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4129 return; 4130 } 4131 4132 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4133 4134 // Critical, after this call app should never have the permission. 4135 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4136 4137 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4138 } 4139 4140 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4141 } 4142 4143 @Override 4144 public void resetRuntimePermissions() { 4145 mContext.enforceCallingOrSelfPermission( 4146 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4147 "revokeRuntimePermission"); 4148 4149 int callingUid = Binder.getCallingUid(); 4150 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4151 mContext.enforceCallingOrSelfPermission( 4152 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4153 "resetRuntimePermissions"); 4154 } 4155 4156 synchronized (mPackages) { 4157 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4158 for (int userId : UserManagerService.getInstance().getUserIds()) { 4159 final int packageCount = mPackages.size(); 4160 for (int i = 0; i < packageCount; i++) { 4161 PackageParser.Package pkg = mPackages.valueAt(i); 4162 if (!(pkg.mExtras instanceof PackageSetting)) { 4163 continue; 4164 } 4165 PackageSetting ps = (PackageSetting) pkg.mExtras; 4166 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4167 } 4168 } 4169 } 4170 } 4171 4172 @Override 4173 public int getPermissionFlags(String name, String packageName, int userId) { 4174 if (!sUserManager.exists(userId)) { 4175 return 0; 4176 } 4177 4178 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4179 4180 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4181 true /* requireFullPermission */, false /* checkShell */, 4182 "getPermissionFlags"); 4183 4184 synchronized (mPackages) { 4185 final PackageParser.Package pkg = mPackages.get(packageName); 4186 if (pkg == null) { 4187 throw new IllegalArgumentException("Unknown package: " + packageName); 4188 } 4189 4190 final BasePermission bp = mSettings.mPermissions.get(name); 4191 if (bp == null) { 4192 throw new IllegalArgumentException("Unknown permission: " + name); 4193 } 4194 4195 SettingBase sb = (SettingBase) pkg.mExtras; 4196 if (sb == null) { 4197 throw new IllegalArgumentException("Unknown package: " + packageName); 4198 } 4199 4200 PermissionsState permissionsState = sb.getPermissionsState(); 4201 return permissionsState.getPermissionFlags(name, userId); 4202 } 4203 } 4204 4205 @Override 4206 public void updatePermissionFlags(String name, String packageName, int flagMask, 4207 int flagValues, int userId) { 4208 if (!sUserManager.exists(userId)) { 4209 return; 4210 } 4211 4212 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4213 4214 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4215 true /* requireFullPermission */, true /* checkShell */, 4216 "updatePermissionFlags"); 4217 4218 // Only the system can change these flags and nothing else. 4219 if (getCallingUid() != Process.SYSTEM_UID) { 4220 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4221 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4222 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4223 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4224 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4225 } 4226 4227 synchronized (mPackages) { 4228 final PackageParser.Package pkg = mPackages.get(packageName); 4229 if (pkg == null) { 4230 throw new IllegalArgumentException("Unknown package: " + packageName); 4231 } 4232 4233 final BasePermission bp = mSettings.mPermissions.get(name); 4234 if (bp == null) { 4235 throw new IllegalArgumentException("Unknown permission: " + name); 4236 } 4237 4238 SettingBase sb = (SettingBase) pkg.mExtras; 4239 if (sb == null) { 4240 throw new IllegalArgumentException("Unknown package: " + packageName); 4241 } 4242 4243 PermissionsState permissionsState = sb.getPermissionsState(); 4244 4245 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4246 4247 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4248 // Install and runtime permissions are stored in different places, 4249 // so figure out what permission changed and persist the change. 4250 if (permissionsState.getInstallPermissionState(name) != null) { 4251 scheduleWriteSettingsLocked(); 4252 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4253 || hadState) { 4254 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4255 } 4256 } 4257 } 4258 } 4259 4260 /** 4261 * Update the permission flags for all packages and runtime permissions of a user in order 4262 * to allow device or profile owner to remove POLICY_FIXED. 4263 */ 4264 @Override 4265 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4266 if (!sUserManager.exists(userId)) { 4267 return; 4268 } 4269 4270 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4271 4272 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4273 true /* requireFullPermission */, true /* checkShell */, 4274 "updatePermissionFlagsForAllApps"); 4275 4276 // Only the system can change system fixed flags. 4277 if (getCallingUid() != Process.SYSTEM_UID) { 4278 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4279 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4280 } 4281 4282 synchronized (mPackages) { 4283 boolean changed = false; 4284 final int packageCount = mPackages.size(); 4285 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4286 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4287 SettingBase sb = (SettingBase) pkg.mExtras; 4288 if (sb == null) { 4289 continue; 4290 } 4291 PermissionsState permissionsState = sb.getPermissionsState(); 4292 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4293 userId, flagMask, flagValues); 4294 } 4295 if (changed) { 4296 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4297 } 4298 } 4299 } 4300 4301 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4302 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4303 != PackageManager.PERMISSION_GRANTED 4304 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4305 != PackageManager.PERMISSION_GRANTED) { 4306 throw new SecurityException(message + " requires " 4307 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4308 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4309 } 4310 } 4311 4312 @Override 4313 public boolean shouldShowRequestPermissionRationale(String permissionName, 4314 String packageName, int userId) { 4315 if (UserHandle.getCallingUserId() != userId) { 4316 mContext.enforceCallingPermission( 4317 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4318 "canShowRequestPermissionRationale for user " + userId); 4319 } 4320 4321 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4322 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4323 return false; 4324 } 4325 4326 if (checkPermission(permissionName, packageName, userId) 4327 == PackageManager.PERMISSION_GRANTED) { 4328 return false; 4329 } 4330 4331 final int flags; 4332 4333 final long identity = Binder.clearCallingIdentity(); 4334 try { 4335 flags = getPermissionFlags(permissionName, 4336 packageName, userId); 4337 } finally { 4338 Binder.restoreCallingIdentity(identity); 4339 } 4340 4341 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4342 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4343 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4344 4345 if ((flags & fixedFlags) != 0) { 4346 return false; 4347 } 4348 4349 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4350 } 4351 4352 @Override 4353 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4354 mContext.enforceCallingOrSelfPermission( 4355 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4356 "addOnPermissionsChangeListener"); 4357 4358 synchronized (mPackages) { 4359 mOnPermissionChangeListeners.addListenerLocked(listener); 4360 } 4361 } 4362 4363 @Override 4364 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4365 synchronized (mPackages) { 4366 mOnPermissionChangeListeners.removeListenerLocked(listener); 4367 } 4368 } 4369 4370 @Override 4371 public boolean isProtectedBroadcast(String actionName) { 4372 synchronized (mPackages) { 4373 if (mProtectedBroadcasts.contains(actionName)) { 4374 return true; 4375 } else if (actionName != null) { 4376 // TODO: remove these terrible hacks 4377 if (actionName.startsWith("android.net.netmon.lingerExpired") 4378 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4379 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 4380 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 4381 return true; 4382 } 4383 } 4384 } 4385 return false; 4386 } 4387 4388 @Override 4389 public int checkSignatures(String pkg1, String pkg2) { 4390 synchronized (mPackages) { 4391 final PackageParser.Package p1 = mPackages.get(pkg1); 4392 final PackageParser.Package p2 = mPackages.get(pkg2); 4393 if (p1 == null || p1.mExtras == null 4394 || p2 == null || p2.mExtras == null) { 4395 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4396 } 4397 return compareSignatures(p1.mSignatures, p2.mSignatures); 4398 } 4399 } 4400 4401 @Override 4402 public int checkUidSignatures(int uid1, int uid2) { 4403 // Map to base uids. 4404 uid1 = UserHandle.getAppId(uid1); 4405 uid2 = UserHandle.getAppId(uid2); 4406 // reader 4407 synchronized (mPackages) { 4408 Signature[] s1; 4409 Signature[] s2; 4410 Object obj = mSettings.getUserIdLPr(uid1); 4411 if (obj != null) { 4412 if (obj instanceof SharedUserSetting) { 4413 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4414 } else if (obj instanceof PackageSetting) { 4415 s1 = ((PackageSetting)obj).signatures.mSignatures; 4416 } else { 4417 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4418 } 4419 } else { 4420 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4421 } 4422 obj = mSettings.getUserIdLPr(uid2); 4423 if (obj != null) { 4424 if (obj instanceof SharedUserSetting) { 4425 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4426 } else if (obj instanceof PackageSetting) { 4427 s2 = ((PackageSetting)obj).signatures.mSignatures; 4428 } else { 4429 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4430 } 4431 } else { 4432 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4433 } 4434 return compareSignatures(s1, s2); 4435 } 4436 } 4437 4438 /** 4439 * This method should typically only be used when granting or revoking 4440 * permissions, since the app may immediately restart after this call. 4441 * <p> 4442 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 4443 * guard your work against the app being relaunched. 4444 */ 4445 private void killUid(int appId, int userId, String reason) { 4446 final long identity = Binder.clearCallingIdentity(); 4447 try { 4448 IActivityManager am = ActivityManagerNative.getDefault(); 4449 if (am != null) { 4450 try { 4451 am.killUid(appId, userId, reason); 4452 } catch (RemoteException e) { 4453 /* ignore - same process */ 4454 } 4455 } 4456 } finally { 4457 Binder.restoreCallingIdentity(identity); 4458 } 4459 } 4460 4461 /** 4462 * Compares two sets of signatures. Returns: 4463 * <br /> 4464 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4465 * <br /> 4466 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4467 * <br /> 4468 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4469 * <br /> 4470 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4471 * <br /> 4472 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4473 */ 4474 static int compareSignatures(Signature[] s1, Signature[] s2) { 4475 if (s1 == null) { 4476 return s2 == null 4477 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4478 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4479 } 4480 4481 if (s2 == null) { 4482 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4483 } 4484 4485 if (s1.length != s2.length) { 4486 return PackageManager.SIGNATURE_NO_MATCH; 4487 } 4488 4489 // Since both signature sets are of size 1, we can compare without HashSets. 4490 if (s1.length == 1) { 4491 return s1[0].equals(s2[0]) ? 4492 PackageManager.SIGNATURE_MATCH : 4493 PackageManager.SIGNATURE_NO_MATCH; 4494 } 4495 4496 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4497 for (Signature sig : s1) { 4498 set1.add(sig); 4499 } 4500 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4501 for (Signature sig : s2) { 4502 set2.add(sig); 4503 } 4504 // Make sure s2 contains all signatures in s1. 4505 if (set1.equals(set2)) { 4506 return PackageManager.SIGNATURE_MATCH; 4507 } 4508 return PackageManager.SIGNATURE_NO_MATCH; 4509 } 4510 4511 /** 4512 * If the database version for this type of package (internal storage or 4513 * external storage) is less than the version where package signatures 4514 * were updated, return true. 4515 */ 4516 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4517 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4518 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4519 } 4520 4521 /** 4522 * Used for backward compatibility to make sure any packages with 4523 * certificate chains get upgraded to the new style. {@code existingSigs} 4524 * will be in the old format (since they were stored on disk from before the 4525 * system upgrade) and {@code scannedSigs} will be in the newer format. 4526 */ 4527 private int compareSignaturesCompat(PackageSignatures existingSigs, 4528 PackageParser.Package scannedPkg) { 4529 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4530 return PackageManager.SIGNATURE_NO_MATCH; 4531 } 4532 4533 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4534 for (Signature sig : existingSigs.mSignatures) { 4535 existingSet.add(sig); 4536 } 4537 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4538 for (Signature sig : scannedPkg.mSignatures) { 4539 try { 4540 Signature[] chainSignatures = sig.getChainSignatures(); 4541 for (Signature chainSig : chainSignatures) { 4542 scannedCompatSet.add(chainSig); 4543 } 4544 } catch (CertificateEncodingException e) { 4545 scannedCompatSet.add(sig); 4546 } 4547 } 4548 /* 4549 * Make sure the expanded scanned set contains all signatures in the 4550 * existing one. 4551 */ 4552 if (scannedCompatSet.equals(existingSet)) { 4553 // Migrate the old signatures to the new scheme. 4554 existingSigs.assignSignatures(scannedPkg.mSignatures); 4555 // The new KeySets will be re-added later in the scanning process. 4556 synchronized (mPackages) { 4557 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4558 } 4559 return PackageManager.SIGNATURE_MATCH; 4560 } 4561 return PackageManager.SIGNATURE_NO_MATCH; 4562 } 4563 4564 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4565 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4566 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4567 } 4568 4569 private int compareSignaturesRecover(PackageSignatures existingSigs, 4570 PackageParser.Package scannedPkg) { 4571 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4572 return PackageManager.SIGNATURE_NO_MATCH; 4573 } 4574 4575 String msg = null; 4576 try { 4577 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4578 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4579 + scannedPkg.packageName); 4580 return PackageManager.SIGNATURE_MATCH; 4581 } 4582 } catch (CertificateException e) { 4583 msg = e.getMessage(); 4584 } 4585 4586 logCriticalInfo(Log.INFO, 4587 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4588 return PackageManager.SIGNATURE_NO_MATCH; 4589 } 4590 4591 @Override 4592 public List<String> getAllPackages() { 4593 synchronized (mPackages) { 4594 return new ArrayList<String>(mPackages.keySet()); 4595 } 4596 } 4597 4598 @Override 4599 public String[] getPackagesForUid(int uid) { 4600 uid = UserHandle.getAppId(uid); 4601 // reader 4602 synchronized (mPackages) { 4603 Object obj = mSettings.getUserIdLPr(uid); 4604 if (obj instanceof SharedUserSetting) { 4605 final SharedUserSetting sus = (SharedUserSetting) obj; 4606 final int N = sus.packages.size(); 4607 final String[] res = new String[N]; 4608 final Iterator<PackageSetting> it = sus.packages.iterator(); 4609 int i = 0; 4610 while (it.hasNext()) { 4611 res[i++] = it.next().name; 4612 } 4613 return res; 4614 } else if (obj instanceof PackageSetting) { 4615 final PackageSetting ps = (PackageSetting) obj; 4616 return new String[] { ps.name }; 4617 } 4618 } 4619 return null; 4620 } 4621 4622 @Override 4623 public String getNameForUid(int uid) { 4624 // reader 4625 synchronized (mPackages) { 4626 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4627 if (obj instanceof SharedUserSetting) { 4628 final SharedUserSetting sus = (SharedUserSetting) obj; 4629 return sus.name + ":" + sus.userId; 4630 } else if (obj instanceof PackageSetting) { 4631 final PackageSetting ps = (PackageSetting) obj; 4632 return ps.name; 4633 } 4634 } 4635 return null; 4636 } 4637 4638 @Override 4639 public int getUidForSharedUser(String sharedUserName) { 4640 if(sharedUserName == null) { 4641 return -1; 4642 } 4643 // reader 4644 synchronized (mPackages) { 4645 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4646 if (suid == null) { 4647 return -1; 4648 } 4649 return suid.userId; 4650 } 4651 } 4652 4653 @Override 4654 public int getFlagsForUid(int uid) { 4655 synchronized (mPackages) { 4656 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4657 if (obj instanceof SharedUserSetting) { 4658 final SharedUserSetting sus = (SharedUserSetting) obj; 4659 return sus.pkgFlags; 4660 } else if (obj instanceof PackageSetting) { 4661 final PackageSetting ps = (PackageSetting) obj; 4662 return ps.pkgFlags; 4663 } 4664 } 4665 return 0; 4666 } 4667 4668 @Override 4669 public int getPrivateFlagsForUid(int uid) { 4670 synchronized (mPackages) { 4671 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4672 if (obj instanceof SharedUserSetting) { 4673 final SharedUserSetting sus = (SharedUserSetting) obj; 4674 return sus.pkgPrivateFlags; 4675 } else if (obj instanceof PackageSetting) { 4676 final PackageSetting ps = (PackageSetting) obj; 4677 return ps.pkgPrivateFlags; 4678 } 4679 } 4680 return 0; 4681 } 4682 4683 @Override 4684 public boolean isUidPrivileged(int uid) { 4685 uid = UserHandle.getAppId(uid); 4686 // reader 4687 synchronized (mPackages) { 4688 Object obj = mSettings.getUserIdLPr(uid); 4689 if (obj instanceof SharedUserSetting) { 4690 final SharedUserSetting sus = (SharedUserSetting) obj; 4691 final Iterator<PackageSetting> it = sus.packages.iterator(); 4692 while (it.hasNext()) { 4693 if (it.next().isPrivileged()) { 4694 return true; 4695 } 4696 } 4697 } else if (obj instanceof PackageSetting) { 4698 final PackageSetting ps = (PackageSetting) obj; 4699 return ps.isPrivileged(); 4700 } 4701 } 4702 return false; 4703 } 4704 4705 @Override 4706 public String[] getAppOpPermissionPackages(String permissionName) { 4707 synchronized (mPackages) { 4708 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4709 if (pkgs == null) { 4710 return null; 4711 } 4712 return pkgs.toArray(new String[pkgs.size()]); 4713 } 4714 } 4715 4716 @Override 4717 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4718 int flags, int userId) { 4719 if (!sUserManager.exists(userId)) return null; 4720 flags = updateFlagsForResolve(flags, userId, intent); 4721 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4722 false /* requireFullPermission */, false /* checkShell */, "resolve intent"); 4723 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4724 userId); 4725 final ResolveInfo bestChoice = 4726 chooseBestActivity(intent, resolvedType, flags, query, userId); 4727 4728 if (isEphemeralAllowed(intent, query, userId)) { 4729 final EphemeralResolveInfo ai = 4730 getEphemeralResolveInfo(intent, resolvedType, userId); 4731 if (ai != null) { 4732 if (DEBUG_EPHEMERAL) { 4733 Slog.v(TAG, "Returning an EphemeralResolveInfo"); 4734 } 4735 bestChoice.ephemeralInstaller = mEphemeralInstallerInfo; 4736 bestChoice.ephemeralResolveInfo = ai; 4737 } 4738 } 4739 return bestChoice; 4740 } 4741 4742 @Override 4743 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4744 IntentFilter filter, int match, ComponentName activity) { 4745 final int userId = UserHandle.getCallingUserId(); 4746 if (DEBUG_PREFERRED) { 4747 Log.v(TAG, "setLastChosenActivity intent=" + intent 4748 + " resolvedType=" + resolvedType 4749 + " flags=" + flags 4750 + " filter=" + filter 4751 + " match=" + match 4752 + " activity=" + activity); 4753 filter.dump(new PrintStreamPrinter(System.out), " "); 4754 } 4755 intent.setComponent(null); 4756 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4757 userId); 4758 // Find any earlier preferred or last chosen entries and nuke them 4759 findPreferredActivity(intent, resolvedType, 4760 flags, query, 0, false, true, false, userId); 4761 // Add the new activity as the last chosen for this filter 4762 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4763 "Setting last chosen"); 4764 } 4765 4766 @Override 4767 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4768 final int userId = UserHandle.getCallingUserId(); 4769 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4770 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4771 userId); 4772 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4773 false, false, false, userId); 4774 } 4775 4776 4777 private boolean isEphemeralAllowed( 4778 Intent intent, List<ResolveInfo> resolvedActivites, int userId) { 4779 // Short circuit and return early if possible. 4780 if (DISABLE_EPHEMERAL_APPS) { 4781 return false; 4782 } 4783 final int callingUser = UserHandle.getCallingUserId(); 4784 if (callingUser != UserHandle.USER_SYSTEM) { 4785 return false; 4786 } 4787 if (mEphemeralResolverConnection == null) { 4788 return false; 4789 } 4790 if (intent.getComponent() != null) { 4791 return false; 4792 } 4793 if (intent.getPackage() != null) { 4794 return false; 4795 } 4796 final boolean isWebUri = hasWebURI(intent); 4797 if (!isWebUri) { 4798 return false; 4799 } 4800 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4801 synchronized (mPackages) { 4802 final int count = resolvedActivites.size(); 4803 for (int n = 0; n < count; n++) { 4804 ResolveInfo info = resolvedActivites.get(n); 4805 String packageName = info.activityInfo.packageName; 4806 PackageSetting ps = mSettings.mPackages.get(packageName); 4807 if (ps != null) { 4808 // Try to get the status from User settings first 4809 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4810 int status = (int) (packedStatus >> 32); 4811 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4812 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4813 if (DEBUG_EPHEMERAL) { 4814 Slog.v(TAG, "DENY ephemeral apps;" 4815 + " pkg: " + packageName + ", status: " + status); 4816 } 4817 return false; 4818 } 4819 } 4820 } 4821 } 4822 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4823 return true; 4824 } 4825 4826 private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType, 4827 int userId) { 4828 MessageDigest digest = null; 4829 try { 4830 digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM); 4831 } catch (NoSuchAlgorithmException e) { 4832 // If we can't create a digest, ignore ephemeral apps. 4833 return null; 4834 } 4835 4836 final byte[] hostBytes = intent.getData().getHost().getBytes(); 4837 final byte[] digestBytes = digest.digest(hostBytes); 4838 int shaPrefix = 4839 digestBytes[0] << 24 4840 | digestBytes[1] << 16 4841 | digestBytes[2] << 8 4842 | digestBytes[3] << 0; 4843 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4844 mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix); 4845 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4846 // No hash prefix match; there are no ephemeral apps for this domain. 4847 return null; 4848 } 4849 for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) { 4850 EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i); 4851 if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) { 4852 continue; 4853 } 4854 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 4855 // No filters; this should never happen. 4856 if (filters.isEmpty()) { 4857 continue; 4858 } 4859 // We have a domain match; resolve the filters to see if anything matches. 4860 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4861 for (int j = filters.size() - 1; j >= 0; --j) { 4862 final EphemeralResolveIntentInfo intentInfo = 4863 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 4864 ephemeralResolver.addFilter(intentInfo); 4865 } 4866 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 4867 intent, resolvedType, false /*defaultOnly*/, userId); 4868 if (!matchedResolveInfoList.isEmpty()) { 4869 return matchedResolveInfoList.get(0); 4870 } 4871 } 4872 // Hash or filter mis-match; no ephemeral apps for this domain. 4873 return null; 4874 } 4875 4876 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4877 int flags, List<ResolveInfo> query, int userId) { 4878 if (query != null) { 4879 final int N = query.size(); 4880 if (N == 1) { 4881 return query.get(0); 4882 } else if (N > 1) { 4883 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4884 // If there is more than one activity with the same priority, 4885 // then let the user decide between them. 4886 ResolveInfo r0 = query.get(0); 4887 ResolveInfo r1 = query.get(1); 4888 if (DEBUG_INTENT_MATCHING || debug) { 4889 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4890 + r1.activityInfo.name + "=" + r1.priority); 4891 } 4892 // If the first activity has a higher priority, or a different 4893 // default, then it is always desirable to pick it. 4894 if (r0.priority != r1.priority 4895 || r0.preferredOrder != r1.preferredOrder 4896 || r0.isDefault != r1.isDefault) { 4897 return query.get(0); 4898 } 4899 // If we have saved a preference for a preferred activity for 4900 // this Intent, use that. 4901 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4902 flags, query, r0.priority, true, false, debug, userId); 4903 if (ri != null) { 4904 return ri; 4905 } 4906 ri = new ResolveInfo(mResolveInfo); 4907 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4908 ri.activityInfo.applicationInfo = new ApplicationInfo( 4909 ri.activityInfo.applicationInfo); 4910 if (userId != 0) { 4911 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4912 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4913 } 4914 // Make sure that the resolver is displayable in car mode 4915 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 4916 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 4917 return ri; 4918 } 4919 } 4920 return null; 4921 } 4922 4923 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4924 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4925 final int N = query.size(); 4926 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4927 .get(userId); 4928 // Get the list of persistent preferred activities that handle the intent 4929 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4930 List<PersistentPreferredActivity> pprefs = ppir != null 4931 ? ppir.queryIntent(intent, resolvedType, 4932 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4933 : null; 4934 if (pprefs != null && pprefs.size() > 0) { 4935 final int M = pprefs.size(); 4936 for (int i=0; i<M; i++) { 4937 final PersistentPreferredActivity ppa = pprefs.get(i); 4938 if (DEBUG_PREFERRED || debug) { 4939 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4940 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4941 + "\n component=" + ppa.mComponent); 4942 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4943 } 4944 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4945 flags | MATCH_DISABLED_COMPONENTS, userId); 4946 if (DEBUG_PREFERRED || debug) { 4947 Slog.v(TAG, "Found persistent preferred activity:"); 4948 if (ai != null) { 4949 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4950 } else { 4951 Slog.v(TAG, " null"); 4952 } 4953 } 4954 if (ai == null) { 4955 // This previously registered persistent preferred activity 4956 // component is no longer known. Ignore it and do NOT remove it. 4957 continue; 4958 } 4959 for (int j=0; j<N; j++) { 4960 final ResolveInfo ri = query.get(j); 4961 if (!ri.activityInfo.applicationInfo.packageName 4962 .equals(ai.applicationInfo.packageName)) { 4963 continue; 4964 } 4965 if (!ri.activityInfo.name.equals(ai.name)) { 4966 continue; 4967 } 4968 // Found a persistent preference that can handle the intent. 4969 if (DEBUG_PREFERRED || debug) { 4970 Slog.v(TAG, "Returning persistent preferred activity: " + 4971 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4972 } 4973 return ri; 4974 } 4975 } 4976 } 4977 return null; 4978 } 4979 4980 // TODO: handle preferred activities missing while user has amnesia 4981 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4982 List<ResolveInfo> query, int priority, boolean always, 4983 boolean removeMatches, boolean debug, int userId) { 4984 if (!sUserManager.exists(userId)) return null; 4985 flags = updateFlagsForResolve(flags, userId, intent); 4986 // writer 4987 synchronized (mPackages) { 4988 if (intent.getSelector() != null) { 4989 intent = intent.getSelector(); 4990 } 4991 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4992 4993 // Try to find a matching persistent preferred activity. 4994 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4995 debug, userId); 4996 4997 // If a persistent preferred activity matched, use it. 4998 if (pri != null) { 4999 return pri; 5000 } 5001 5002 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5003 // Get the list of preferred activities that handle the intent 5004 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5005 List<PreferredActivity> prefs = pir != null 5006 ? pir.queryIntent(intent, resolvedType, 5007 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5008 : null; 5009 if (prefs != null && prefs.size() > 0) { 5010 boolean changed = false; 5011 try { 5012 // First figure out how good the original match set is. 5013 // We will only allow preferred activities that came 5014 // from the same match quality. 5015 int match = 0; 5016 5017 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5018 5019 final int N = query.size(); 5020 for (int j=0; j<N; j++) { 5021 final ResolveInfo ri = query.get(j); 5022 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5023 + ": 0x" + Integer.toHexString(match)); 5024 if (ri.match > match) { 5025 match = ri.match; 5026 } 5027 } 5028 5029 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5030 + Integer.toHexString(match)); 5031 5032 match &= IntentFilter.MATCH_CATEGORY_MASK; 5033 final int M = prefs.size(); 5034 for (int i=0; i<M; i++) { 5035 final PreferredActivity pa = prefs.get(i); 5036 if (DEBUG_PREFERRED || debug) { 5037 Slog.v(TAG, "Checking PreferredActivity ds=" 5038 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5039 + "\n component=" + pa.mPref.mComponent); 5040 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5041 } 5042 if (pa.mPref.mMatch != match) { 5043 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5044 + Integer.toHexString(pa.mPref.mMatch)); 5045 continue; 5046 } 5047 // If it's not an "always" type preferred activity and that's what we're 5048 // looking for, skip it. 5049 if (always && !pa.mPref.mAlways) { 5050 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5051 continue; 5052 } 5053 final ActivityInfo ai = getActivityInfo( 5054 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5055 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5056 userId); 5057 if (DEBUG_PREFERRED || debug) { 5058 Slog.v(TAG, "Found preferred activity:"); 5059 if (ai != null) { 5060 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5061 } else { 5062 Slog.v(TAG, " null"); 5063 } 5064 } 5065 if (ai == null) { 5066 // This previously registered preferred activity 5067 // component is no longer known. Most likely an update 5068 // to the app was installed and in the new version this 5069 // component no longer exists. Clean it up by removing 5070 // it from the preferred activities list, and skip it. 5071 Slog.w(TAG, "Removing dangling preferred activity: " 5072 + pa.mPref.mComponent); 5073 pir.removeFilter(pa); 5074 changed = true; 5075 continue; 5076 } 5077 for (int j=0; j<N; j++) { 5078 final ResolveInfo ri = query.get(j); 5079 if (!ri.activityInfo.applicationInfo.packageName 5080 .equals(ai.applicationInfo.packageName)) { 5081 continue; 5082 } 5083 if (!ri.activityInfo.name.equals(ai.name)) { 5084 continue; 5085 } 5086 5087 if (removeMatches) { 5088 pir.removeFilter(pa); 5089 changed = true; 5090 if (DEBUG_PREFERRED) { 5091 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 5092 } 5093 break; 5094 } 5095 5096 // Okay we found a previously set preferred or last chosen app. 5097 // If the result set is different from when this 5098 // was created, we need to clear it and re-ask the 5099 // user their preference, if we're looking for an "always" type entry. 5100 if (always && !pa.mPref.sameSet(query)) { 5101 Slog.i(TAG, "Result set changed, dropping preferred activity for " 5102 + intent + " type " + resolvedType); 5103 if (DEBUG_PREFERRED) { 5104 Slog.v(TAG, "Removing preferred activity since set changed " 5105 + pa.mPref.mComponent); 5106 } 5107 pir.removeFilter(pa); 5108 // Re-add the filter as a "last chosen" entry (!always) 5109 PreferredActivity lastChosen = new PreferredActivity( 5110 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5111 pir.addFilter(lastChosen); 5112 changed = true; 5113 return null; 5114 } 5115 5116 // Yay! Either the set matched or we're looking for the last chosen 5117 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5118 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5119 return ri; 5120 } 5121 } 5122 } finally { 5123 if (changed) { 5124 if (DEBUG_PREFERRED) { 5125 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5126 } 5127 scheduleWritePackageRestrictionsLocked(userId); 5128 } 5129 } 5130 } 5131 } 5132 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5133 return null; 5134 } 5135 5136 /* 5137 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5138 */ 5139 @Override 5140 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5141 int targetUserId) { 5142 mContext.enforceCallingOrSelfPermission( 5143 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5144 List<CrossProfileIntentFilter> matches = 5145 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5146 if (matches != null) { 5147 int size = matches.size(); 5148 for (int i = 0; i < size; i++) { 5149 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5150 } 5151 } 5152 if (hasWebURI(intent)) { 5153 // cross-profile app linking works only towards the parent. 5154 final UserInfo parent = getProfileParent(sourceUserId); 5155 synchronized(mPackages) { 5156 int flags = updateFlagsForResolve(0, parent.id, intent); 5157 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5158 intent, resolvedType, flags, sourceUserId, parent.id); 5159 return xpDomainInfo != null; 5160 } 5161 } 5162 return false; 5163 } 5164 5165 private UserInfo getProfileParent(int userId) { 5166 final long identity = Binder.clearCallingIdentity(); 5167 try { 5168 return sUserManager.getProfileParent(userId); 5169 } finally { 5170 Binder.restoreCallingIdentity(identity); 5171 } 5172 } 5173 5174 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5175 String resolvedType, int userId) { 5176 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5177 if (resolver != null) { 5178 return resolver.queryIntent(intent, resolvedType, false, userId); 5179 } 5180 return null; 5181 } 5182 5183 @Override 5184 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5185 String resolvedType, int flags, int userId) { 5186 return new ParceledListSlice<>( 5187 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5188 } 5189 5190 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5191 String resolvedType, int flags, int userId) { 5192 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5193 flags = updateFlagsForResolve(flags, userId, intent); 5194 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5195 false /* requireFullPermission */, false /* checkShell */, 5196 "query intent activities"); 5197 ComponentName comp = intent.getComponent(); 5198 if (comp == null) { 5199 if (intent.getSelector() != null) { 5200 intent = intent.getSelector(); 5201 comp = intent.getComponent(); 5202 } 5203 } 5204 5205 if (comp != null) { 5206 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5207 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5208 if (ai != null) { 5209 final ResolveInfo ri = new ResolveInfo(); 5210 ri.activityInfo = ai; 5211 list.add(ri); 5212 } 5213 return list; 5214 } 5215 5216 // reader 5217 synchronized (mPackages) { 5218 final String pkgName = intent.getPackage(); 5219 if (pkgName == null) { 5220 List<CrossProfileIntentFilter> matchingFilters = 5221 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5222 // Check for results that need to skip the current profile. 5223 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5224 resolvedType, flags, userId); 5225 if (xpResolveInfo != null) { 5226 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 5227 result.add(xpResolveInfo); 5228 return filterIfNotSystemUser(result, userId); 5229 } 5230 5231 // Check for results in the current profile. 5232 List<ResolveInfo> result = mActivities.queryIntent( 5233 intent, resolvedType, flags, userId); 5234 result = filterIfNotSystemUser(result, userId); 5235 5236 // Check for cross profile results. 5237 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5238 xpResolveInfo = queryCrossProfileIntents( 5239 matchingFilters, intent, resolvedType, flags, userId, 5240 hasNonNegativePriorityResult); 5241 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5242 boolean isVisibleToUser = filterIfNotSystemUser( 5243 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5244 if (isVisibleToUser) { 5245 result.add(xpResolveInfo); 5246 Collections.sort(result, mResolvePrioritySorter); 5247 } 5248 } 5249 if (hasWebURI(intent)) { 5250 CrossProfileDomainInfo xpDomainInfo = null; 5251 final UserInfo parent = getProfileParent(userId); 5252 if (parent != null) { 5253 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5254 flags, userId, parent.id); 5255 } 5256 if (xpDomainInfo != null) { 5257 if (xpResolveInfo != null) { 5258 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5259 // in the result. 5260 result.remove(xpResolveInfo); 5261 } 5262 if (result.size() == 0) { 5263 result.add(xpDomainInfo.resolveInfo); 5264 return result; 5265 } 5266 } else if (result.size() <= 1) { 5267 return result; 5268 } 5269 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 5270 xpDomainInfo, userId); 5271 Collections.sort(result, mResolvePrioritySorter); 5272 } 5273 return result; 5274 } 5275 final PackageParser.Package pkg = mPackages.get(pkgName); 5276 if (pkg != null) { 5277 return filterIfNotSystemUser( 5278 mActivities.queryIntentForPackage( 5279 intent, resolvedType, flags, pkg.activities, userId), 5280 userId); 5281 } 5282 return new ArrayList<ResolveInfo>(); 5283 } 5284 } 5285 5286 private static class CrossProfileDomainInfo { 5287 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5288 ResolveInfo resolveInfo; 5289 /* Best domain verification status of the activities found in the other profile */ 5290 int bestDomainVerificationStatus; 5291 } 5292 5293 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5294 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5295 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5296 sourceUserId)) { 5297 return null; 5298 } 5299 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5300 resolvedType, flags, parentUserId); 5301 5302 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5303 return null; 5304 } 5305 CrossProfileDomainInfo result = null; 5306 int size = resultTargetUser.size(); 5307 for (int i = 0; i < size; i++) { 5308 ResolveInfo riTargetUser = resultTargetUser.get(i); 5309 // Intent filter verification is only for filters that specify a host. So don't return 5310 // those that handle all web uris. 5311 if (riTargetUser.handleAllWebDataURI) { 5312 continue; 5313 } 5314 String packageName = riTargetUser.activityInfo.packageName; 5315 PackageSetting ps = mSettings.mPackages.get(packageName); 5316 if (ps == null) { 5317 continue; 5318 } 5319 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5320 int status = (int)(verificationState >> 32); 5321 if (result == null) { 5322 result = new CrossProfileDomainInfo(); 5323 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5324 sourceUserId, parentUserId); 5325 result.bestDomainVerificationStatus = status; 5326 } else { 5327 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5328 result.bestDomainVerificationStatus); 5329 } 5330 } 5331 // Don't consider matches with status NEVER across profiles. 5332 if (result != null && result.bestDomainVerificationStatus 5333 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5334 return null; 5335 } 5336 return result; 5337 } 5338 5339 /** 5340 * Verification statuses are ordered from the worse to the best, except for 5341 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5342 */ 5343 private int bestDomainVerificationStatus(int status1, int status2) { 5344 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5345 return status2; 5346 } 5347 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5348 return status1; 5349 } 5350 return (int) MathUtils.max(status1, status2); 5351 } 5352 5353 private boolean isUserEnabled(int userId) { 5354 long callingId = Binder.clearCallingIdentity(); 5355 try { 5356 UserInfo userInfo = sUserManager.getUserInfo(userId); 5357 return userInfo != null && userInfo.isEnabled(); 5358 } finally { 5359 Binder.restoreCallingIdentity(callingId); 5360 } 5361 } 5362 5363 /** 5364 * Filter out activities with systemUserOnly flag set, when current user is not System. 5365 * 5366 * @return filtered list 5367 */ 5368 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5369 if (userId == UserHandle.USER_SYSTEM) { 5370 return resolveInfos; 5371 } 5372 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5373 ResolveInfo info = resolveInfos.get(i); 5374 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5375 resolveInfos.remove(i); 5376 } 5377 } 5378 return resolveInfos; 5379 } 5380 5381 /** 5382 * @param resolveInfos list of resolve infos in descending priority order 5383 * @return if the list contains a resolve info with non-negative priority 5384 */ 5385 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5386 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5387 } 5388 5389 private static boolean hasWebURI(Intent intent) { 5390 if (intent.getData() == null) { 5391 return false; 5392 } 5393 final String scheme = intent.getScheme(); 5394 if (TextUtils.isEmpty(scheme)) { 5395 return false; 5396 } 5397 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5398 } 5399 5400 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5401 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5402 int userId) { 5403 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5404 5405 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5406 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5407 candidates.size()); 5408 } 5409 5410 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5411 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5412 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5413 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5414 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5415 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5416 5417 synchronized (mPackages) { 5418 final int count = candidates.size(); 5419 // First, try to use linked apps. Partition the candidates into four lists: 5420 // one for the final results, one for the "do not use ever", one for "undefined status" 5421 // and finally one for "browser app type". 5422 for (int n=0; n<count; n++) { 5423 ResolveInfo info = candidates.get(n); 5424 String packageName = info.activityInfo.packageName; 5425 PackageSetting ps = mSettings.mPackages.get(packageName); 5426 if (ps != null) { 5427 // Add to the special match all list (Browser use case) 5428 if (info.handleAllWebDataURI) { 5429 matchAllList.add(info); 5430 continue; 5431 } 5432 // Try to get the status from User settings first 5433 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5434 int status = (int)(packedStatus >> 32); 5435 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5436 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5437 if (DEBUG_DOMAIN_VERIFICATION) { 5438 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5439 + " : linkgen=" + linkGeneration); 5440 } 5441 // Use link-enabled generation as preferredOrder, i.e. 5442 // prefer newly-enabled over earlier-enabled. 5443 info.preferredOrder = linkGeneration; 5444 alwaysList.add(info); 5445 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5446 if (DEBUG_DOMAIN_VERIFICATION) { 5447 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5448 } 5449 neverList.add(info); 5450 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5451 if (DEBUG_DOMAIN_VERIFICATION) { 5452 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5453 } 5454 alwaysAskList.add(info); 5455 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5456 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5457 if (DEBUG_DOMAIN_VERIFICATION) { 5458 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5459 } 5460 undefinedList.add(info); 5461 } 5462 } 5463 } 5464 5465 // We'll want to include browser possibilities in a few cases 5466 boolean includeBrowser = false; 5467 5468 // First try to add the "always" resolution(s) for the current user, if any 5469 if (alwaysList.size() > 0) { 5470 result.addAll(alwaysList); 5471 } else { 5472 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5473 result.addAll(undefinedList); 5474 // Maybe add one for the other profile. 5475 if (xpDomainInfo != null && ( 5476 xpDomainInfo.bestDomainVerificationStatus 5477 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5478 result.add(xpDomainInfo.resolveInfo); 5479 } 5480 includeBrowser = true; 5481 } 5482 5483 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5484 // If there were 'always' entries their preferred order has been set, so we also 5485 // back that off to make the alternatives equivalent 5486 if (alwaysAskList.size() > 0) { 5487 for (ResolveInfo i : result) { 5488 i.preferredOrder = 0; 5489 } 5490 result.addAll(alwaysAskList); 5491 includeBrowser = true; 5492 } 5493 5494 if (includeBrowser) { 5495 // Also add browsers (all of them or only the default one) 5496 if (DEBUG_DOMAIN_VERIFICATION) { 5497 Slog.v(TAG, " ...including browsers in candidate set"); 5498 } 5499 if ((matchFlags & MATCH_ALL) != 0) { 5500 result.addAll(matchAllList); 5501 } else { 5502 // Browser/generic handling case. If there's a default browser, go straight 5503 // to that (but only if there is no other higher-priority match). 5504 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5505 int maxMatchPrio = 0; 5506 ResolveInfo defaultBrowserMatch = null; 5507 final int numCandidates = matchAllList.size(); 5508 for (int n = 0; n < numCandidates; n++) { 5509 ResolveInfo info = matchAllList.get(n); 5510 // track the highest overall match priority... 5511 if (info.priority > maxMatchPrio) { 5512 maxMatchPrio = info.priority; 5513 } 5514 // ...and the highest-priority default browser match 5515 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5516 if (defaultBrowserMatch == null 5517 || (defaultBrowserMatch.priority < info.priority)) { 5518 if (debug) { 5519 Slog.v(TAG, "Considering default browser match " + info); 5520 } 5521 defaultBrowserMatch = info; 5522 } 5523 } 5524 } 5525 if (defaultBrowserMatch != null 5526 && defaultBrowserMatch.priority >= maxMatchPrio 5527 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5528 { 5529 if (debug) { 5530 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5531 } 5532 result.add(defaultBrowserMatch); 5533 } else { 5534 result.addAll(matchAllList); 5535 } 5536 } 5537 5538 // If there is nothing selected, add all candidates and remove the ones that the user 5539 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5540 if (result.size() == 0) { 5541 result.addAll(candidates); 5542 result.removeAll(neverList); 5543 } 5544 } 5545 } 5546 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5547 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5548 result.size()); 5549 for (ResolveInfo info : result) { 5550 Slog.v(TAG, " + " + info.activityInfo); 5551 } 5552 } 5553 return result; 5554 } 5555 5556 // Returns a packed value as a long: 5557 // 5558 // high 'int'-sized word: link status: undefined/ask/never/always. 5559 // low 'int'-sized word: relative priority among 'always' results. 5560 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5561 long result = ps.getDomainVerificationStatusForUser(userId); 5562 // if none available, get the master status 5563 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5564 if (ps.getIntentFilterVerificationInfo() != null) { 5565 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5566 } 5567 } 5568 return result; 5569 } 5570 5571 private ResolveInfo querySkipCurrentProfileIntents( 5572 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5573 int flags, int sourceUserId) { 5574 if (matchingFilters != null) { 5575 int size = matchingFilters.size(); 5576 for (int i = 0; i < size; i ++) { 5577 CrossProfileIntentFilter filter = matchingFilters.get(i); 5578 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5579 // Checking if there are activities in the target user that can handle the 5580 // intent. 5581 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5582 resolvedType, flags, sourceUserId); 5583 if (resolveInfo != null) { 5584 return resolveInfo; 5585 } 5586 } 5587 } 5588 } 5589 return null; 5590 } 5591 5592 // Return matching ResolveInfo in target user if any. 5593 private ResolveInfo queryCrossProfileIntents( 5594 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5595 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5596 if (matchingFilters != null) { 5597 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5598 // match the same intent. For performance reasons, it is better not to 5599 // run queryIntent twice for the same userId 5600 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5601 int size = matchingFilters.size(); 5602 for (int i = 0; i < size; i++) { 5603 CrossProfileIntentFilter filter = matchingFilters.get(i); 5604 int targetUserId = filter.getTargetUserId(); 5605 boolean skipCurrentProfile = 5606 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5607 boolean skipCurrentProfileIfNoMatchFound = 5608 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5609 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5610 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5611 // Checking if there are activities in the target user that can handle the 5612 // intent. 5613 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5614 resolvedType, flags, sourceUserId); 5615 if (resolveInfo != null) return resolveInfo; 5616 alreadyTriedUserIds.put(targetUserId, true); 5617 } 5618 } 5619 } 5620 return null; 5621 } 5622 5623 /** 5624 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5625 * will forward the intent to the filter's target user. 5626 * Otherwise, returns null. 5627 */ 5628 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5629 String resolvedType, int flags, int sourceUserId) { 5630 int targetUserId = filter.getTargetUserId(); 5631 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5632 resolvedType, flags, targetUserId); 5633 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5634 // If all the matches in the target profile are suspended, return null. 5635 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5636 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5637 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5638 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5639 targetUserId); 5640 } 5641 } 5642 } 5643 return null; 5644 } 5645 5646 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5647 int sourceUserId, int targetUserId) { 5648 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5649 long ident = Binder.clearCallingIdentity(); 5650 boolean targetIsProfile; 5651 try { 5652 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5653 } finally { 5654 Binder.restoreCallingIdentity(ident); 5655 } 5656 String className; 5657 if (targetIsProfile) { 5658 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5659 } else { 5660 className = FORWARD_INTENT_TO_PARENT; 5661 } 5662 ComponentName forwardingActivityComponentName = new ComponentName( 5663 mAndroidApplication.packageName, className); 5664 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5665 sourceUserId); 5666 if (!targetIsProfile) { 5667 forwardingActivityInfo.showUserIcon = targetUserId; 5668 forwardingResolveInfo.noResourceId = true; 5669 } 5670 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5671 forwardingResolveInfo.priority = 0; 5672 forwardingResolveInfo.preferredOrder = 0; 5673 forwardingResolveInfo.match = 0; 5674 forwardingResolveInfo.isDefault = true; 5675 forwardingResolveInfo.filter = filter; 5676 forwardingResolveInfo.targetUserId = targetUserId; 5677 return forwardingResolveInfo; 5678 } 5679 5680 @Override 5681 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5682 Intent[] specifics, String[] specificTypes, Intent intent, 5683 String resolvedType, int flags, int userId) { 5684 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 5685 specificTypes, intent, resolvedType, flags, userId)); 5686 } 5687 5688 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 5689 Intent[] specifics, String[] specificTypes, Intent intent, 5690 String resolvedType, int flags, int userId) { 5691 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5692 flags = updateFlagsForResolve(flags, userId, intent); 5693 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5694 false /* requireFullPermission */, false /* checkShell */, 5695 "query intent activity options"); 5696 final String resultsAction = intent.getAction(); 5697 5698 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 5699 | PackageManager.GET_RESOLVED_FILTER, userId); 5700 5701 if (DEBUG_INTENT_MATCHING) { 5702 Log.v(TAG, "Query " + intent + ": " + results); 5703 } 5704 5705 int specificsPos = 0; 5706 int N; 5707 5708 // todo: note that the algorithm used here is O(N^2). This 5709 // isn't a problem in our current environment, but if we start running 5710 // into situations where we have more than 5 or 10 matches then this 5711 // should probably be changed to something smarter... 5712 5713 // First we go through and resolve each of the specific items 5714 // that were supplied, taking care of removing any corresponding 5715 // duplicate items in the generic resolve list. 5716 if (specifics != null) { 5717 for (int i=0; i<specifics.length; i++) { 5718 final Intent sintent = specifics[i]; 5719 if (sintent == null) { 5720 continue; 5721 } 5722 5723 if (DEBUG_INTENT_MATCHING) { 5724 Log.v(TAG, "Specific #" + i + ": " + sintent); 5725 } 5726 5727 String action = sintent.getAction(); 5728 if (resultsAction != null && resultsAction.equals(action)) { 5729 // If this action was explicitly requested, then don't 5730 // remove things that have it. 5731 action = null; 5732 } 5733 5734 ResolveInfo ri = null; 5735 ActivityInfo ai = null; 5736 5737 ComponentName comp = sintent.getComponent(); 5738 if (comp == null) { 5739 ri = resolveIntent( 5740 sintent, 5741 specificTypes != null ? specificTypes[i] : null, 5742 flags, userId); 5743 if (ri == null) { 5744 continue; 5745 } 5746 if (ri == mResolveInfo) { 5747 // ACK! Must do something better with this. 5748 } 5749 ai = ri.activityInfo; 5750 comp = new ComponentName(ai.applicationInfo.packageName, 5751 ai.name); 5752 } else { 5753 ai = getActivityInfo(comp, flags, userId); 5754 if (ai == null) { 5755 continue; 5756 } 5757 } 5758 5759 // Look for any generic query activities that are duplicates 5760 // of this specific one, and remove them from the results. 5761 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5762 N = results.size(); 5763 int j; 5764 for (j=specificsPos; j<N; j++) { 5765 ResolveInfo sri = results.get(j); 5766 if ((sri.activityInfo.name.equals(comp.getClassName()) 5767 && sri.activityInfo.applicationInfo.packageName.equals( 5768 comp.getPackageName())) 5769 || (action != null && sri.filter.matchAction(action))) { 5770 results.remove(j); 5771 if (DEBUG_INTENT_MATCHING) Log.v( 5772 TAG, "Removing duplicate item from " + j 5773 + " due to specific " + specificsPos); 5774 if (ri == null) { 5775 ri = sri; 5776 } 5777 j--; 5778 N--; 5779 } 5780 } 5781 5782 // Add this specific item to its proper place. 5783 if (ri == null) { 5784 ri = new ResolveInfo(); 5785 ri.activityInfo = ai; 5786 } 5787 results.add(specificsPos, ri); 5788 ri.specificIndex = i; 5789 specificsPos++; 5790 } 5791 } 5792 5793 // Now we go through the remaining generic results and remove any 5794 // duplicate actions that are found here. 5795 N = results.size(); 5796 for (int i=specificsPos; i<N-1; i++) { 5797 final ResolveInfo rii = results.get(i); 5798 if (rii.filter == null) { 5799 continue; 5800 } 5801 5802 // Iterate over all of the actions of this result's intent 5803 // filter... typically this should be just one. 5804 final Iterator<String> it = rii.filter.actionsIterator(); 5805 if (it == null) { 5806 continue; 5807 } 5808 while (it.hasNext()) { 5809 final String action = it.next(); 5810 if (resultsAction != null && resultsAction.equals(action)) { 5811 // If this action was explicitly requested, then don't 5812 // remove things that have it. 5813 continue; 5814 } 5815 for (int j=i+1; j<N; j++) { 5816 final ResolveInfo rij = results.get(j); 5817 if (rij.filter != null && rij.filter.hasAction(action)) { 5818 results.remove(j); 5819 if (DEBUG_INTENT_MATCHING) Log.v( 5820 TAG, "Removing duplicate item from " + j 5821 + " due to action " + action + " at " + i); 5822 j--; 5823 N--; 5824 } 5825 } 5826 } 5827 5828 // If the caller didn't request filter information, drop it now 5829 // so we don't have to marshall/unmarshall it. 5830 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5831 rii.filter = null; 5832 } 5833 } 5834 5835 // Filter out the caller activity if so requested. 5836 if (caller != null) { 5837 N = results.size(); 5838 for (int i=0; i<N; i++) { 5839 ActivityInfo ainfo = results.get(i).activityInfo; 5840 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5841 && caller.getClassName().equals(ainfo.name)) { 5842 results.remove(i); 5843 break; 5844 } 5845 } 5846 } 5847 5848 // If the caller didn't request filter information, 5849 // drop them now so we don't have to 5850 // marshall/unmarshall it. 5851 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5852 N = results.size(); 5853 for (int i=0; i<N; i++) { 5854 results.get(i).filter = null; 5855 } 5856 } 5857 5858 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5859 return results; 5860 } 5861 5862 @Override 5863 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 5864 String resolvedType, int flags, int userId) { 5865 return new ParceledListSlice<>( 5866 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 5867 } 5868 5869 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 5870 String resolvedType, int flags, int userId) { 5871 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5872 flags = updateFlagsForResolve(flags, userId, intent); 5873 ComponentName comp = intent.getComponent(); 5874 if (comp == null) { 5875 if (intent.getSelector() != null) { 5876 intent = intent.getSelector(); 5877 comp = intent.getComponent(); 5878 } 5879 } 5880 if (comp != null) { 5881 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5882 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5883 if (ai != null) { 5884 ResolveInfo ri = new ResolveInfo(); 5885 ri.activityInfo = ai; 5886 list.add(ri); 5887 } 5888 return list; 5889 } 5890 5891 // reader 5892 synchronized (mPackages) { 5893 String pkgName = intent.getPackage(); 5894 if (pkgName == null) { 5895 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5896 } 5897 final PackageParser.Package pkg = mPackages.get(pkgName); 5898 if (pkg != null) { 5899 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5900 userId); 5901 } 5902 return Collections.emptyList(); 5903 } 5904 } 5905 5906 @Override 5907 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5908 if (!sUserManager.exists(userId)) return null; 5909 flags = updateFlagsForResolve(flags, userId, intent); 5910 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 5911 if (query != null) { 5912 if (query.size() >= 1) { 5913 // If there is more than one service with the same priority, 5914 // just arbitrarily pick the first one. 5915 return query.get(0); 5916 } 5917 } 5918 return null; 5919 } 5920 5921 @Override 5922 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 5923 String resolvedType, int flags, int userId) { 5924 return new ParceledListSlice<>( 5925 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 5926 } 5927 5928 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 5929 String resolvedType, int flags, int userId) { 5930 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5931 flags = updateFlagsForResolve(flags, userId, intent); 5932 ComponentName comp = intent.getComponent(); 5933 if (comp == null) { 5934 if (intent.getSelector() != null) { 5935 intent = intent.getSelector(); 5936 comp = intent.getComponent(); 5937 } 5938 } 5939 if (comp != null) { 5940 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5941 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5942 if (si != null) { 5943 final ResolveInfo ri = new ResolveInfo(); 5944 ri.serviceInfo = si; 5945 list.add(ri); 5946 } 5947 return list; 5948 } 5949 5950 // reader 5951 synchronized (mPackages) { 5952 String pkgName = intent.getPackage(); 5953 if (pkgName == null) { 5954 return mServices.queryIntent(intent, resolvedType, flags, userId); 5955 } 5956 final PackageParser.Package pkg = mPackages.get(pkgName); 5957 if (pkg != null) { 5958 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5959 userId); 5960 } 5961 return Collections.emptyList(); 5962 } 5963 } 5964 5965 @Override 5966 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 5967 String resolvedType, int flags, int userId) { 5968 return new ParceledListSlice<>( 5969 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 5970 } 5971 5972 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 5973 Intent intent, String resolvedType, int flags, int userId) { 5974 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5975 flags = updateFlagsForResolve(flags, userId, intent); 5976 ComponentName comp = intent.getComponent(); 5977 if (comp == null) { 5978 if (intent.getSelector() != null) { 5979 intent = intent.getSelector(); 5980 comp = intent.getComponent(); 5981 } 5982 } 5983 if (comp != null) { 5984 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5985 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5986 if (pi != null) { 5987 final ResolveInfo ri = new ResolveInfo(); 5988 ri.providerInfo = pi; 5989 list.add(ri); 5990 } 5991 return list; 5992 } 5993 5994 // reader 5995 synchronized (mPackages) { 5996 String pkgName = intent.getPackage(); 5997 if (pkgName == null) { 5998 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5999 } 6000 final PackageParser.Package pkg = mPackages.get(pkgName); 6001 if (pkg != null) { 6002 return mProviders.queryIntentForPackage( 6003 intent, resolvedType, flags, pkg.providers, userId); 6004 } 6005 return Collections.emptyList(); 6006 } 6007 } 6008 6009 @Override 6010 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 6011 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6012 flags = updateFlagsForPackage(flags, userId, null); 6013 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6014 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6015 true /* requireFullPermission */, false /* checkShell */, 6016 "get installed packages"); 6017 6018 // writer 6019 synchronized (mPackages) { 6020 ArrayList<PackageInfo> list; 6021 if (listUninstalled) { 6022 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 6023 for (PackageSetting ps : mSettings.mPackages.values()) { 6024 final PackageInfo pi; 6025 if (ps.pkg != null) { 6026 pi = generatePackageInfo(ps, flags, userId); 6027 } else { 6028 pi = generatePackageInfo(ps, flags, userId); 6029 } 6030 if (pi != null) { 6031 list.add(pi); 6032 } 6033 } 6034 } else { 6035 list = new ArrayList<PackageInfo>(mPackages.size()); 6036 for (PackageParser.Package p : mPackages.values()) { 6037 final PackageInfo pi = 6038 generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 6039 if (pi != null) { 6040 list.add(pi); 6041 } 6042 } 6043 } 6044 6045 return new ParceledListSlice<PackageInfo>(list); 6046 } 6047 } 6048 6049 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 6050 String[] permissions, boolean[] tmp, int flags, int userId) { 6051 int numMatch = 0; 6052 final PermissionsState permissionsState = ps.getPermissionsState(); 6053 for (int i=0; i<permissions.length; i++) { 6054 final String permission = permissions[i]; 6055 if (permissionsState.hasPermission(permission, userId)) { 6056 tmp[i] = true; 6057 numMatch++; 6058 } else { 6059 tmp[i] = false; 6060 } 6061 } 6062 if (numMatch == 0) { 6063 return; 6064 } 6065 final PackageInfo pi; 6066 if (ps.pkg != null) { 6067 pi = generatePackageInfo(ps, flags, userId); 6068 } else { 6069 pi = generatePackageInfo(ps, flags, userId); 6070 } 6071 // The above might return null in cases of uninstalled apps or install-state 6072 // skew across users/profiles. 6073 if (pi != null) { 6074 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 6075 if (numMatch == permissions.length) { 6076 pi.requestedPermissions = permissions; 6077 } else { 6078 pi.requestedPermissions = new String[numMatch]; 6079 numMatch = 0; 6080 for (int i=0; i<permissions.length; i++) { 6081 if (tmp[i]) { 6082 pi.requestedPermissions[numMatch] = permissions[i]; 6083 numMatch++; 6084 } 6085 } 6086 } 6087 } 6088 list.add(pi); 6089 } 6090 } 6091 6092 @Override 6093 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 6094 String[] permissions, int flags, int userId) { 6095 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6096 flags = updateFlagsForPackage(flags, userId, permissions); 6097 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6098 6099 // writer 6100 synchronized (mPackages) { 6101 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 6102 boolean[] tmpBools = new boolean[permissions.length]; 6103 if (listUninstalled) { 6104 for (PackageSetting ps : mSettings.mPackages.values()) { 6105 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 6106 } 6107 } else { 6108 for (PackageParser.Package pkg : mPackages.values()) { 6109 PackageSetting ps = (PackageSetting)pkg.mExtras; 6110 if (ps != null) { 6111 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6112 userId); 6113 } 6114 } 6115 } 6116 6117 return new ParceledListSlice<PackageInfo>(list); 6118 } 6119 } 6120 6121 @Override 6122 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 6123 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6124 flags = updateFlagsForApplication(flags, userId, null); 6125 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6126 6127 // writer 6128 synchronized (mPackages) { 6129 ArrayList<ApplicationInfo> list; 6130 if (listUninstalled) { 6131 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 6132 for (PackageSetting ps : mSettings.mPackages.values()) { 6133 ApplicationInfo ai; 6134 if (ps.pkg != null) { 6135 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 6136 ps.readUserState(userId), userId); 6137 } else { 6138 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 6139 } 6140 if (ai != null) { 6141 list.add(ai); 6142 } 6143 } 6144 } else { 6145 list = new ArrayList<ApplicationInfo>(mPackages.size()); 6146 for (PackageParser.Package p : mPackages.values()) { 6147 if (p.mExtras != null) { 6148 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6149 ((PackageSetting)p.mExtras).readUserState(userId), userId); 6150 if (ai != null) { 6151 list.add(ai); 6152 } 6153 } 6154 } 6155 } 6156 6157 return new ParceledListSlice<ApplicationInfo>(list); 6158 } 6159 } 6160 6161 @Override 6162 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 6163 if (DISABLE_EPHEMERAL_APPS) { 6164 return null; 6165 } 6166 6167 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6168 "getEphemeralApplications"); 6169 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6170 true /* requireFullPermission */, false /* checkShell */, 6171 "getEphemeralApplications"); 6172 synchronized (mPackages) { 6173 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 6174 .getEphemeralApplicationsLPw(userId); 6175 if (ephemeralApps != null) { 6176 return new ParceledListSlice<>(ephemeralApps); 6177 } 6178 } 6179 return null; 6180 } 6181 6182 @Override 6183 public boolean isEphemeralApplication(String packageName, int userId) { 6184 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6185 true /* requireFullPermission */, false /* checkShell */, 6186 "isEphemeral"); 6187 if (DISABLE_EPHEMERAL_APPS) { 6188 return false; 6189 } 6190 6191 if (!isCallerSameApp(packageName)) { 6192 return false; 6193 } 6194 synchronized (mPackages) { 6195 PackageParser.Package pkg = mPackages.get(packageName); 6196 if (pkg != null) { 6197 return pkg.applicationInfo.isEphemeralApp(); 6198 } 6199 } 6200 return false; 6201 } 6202 6203 @Override 6204 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6205 if (DISABLE_EPHEMERAL_APPS) { 6206 return null; 6207 } 6208 6209 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6210 true /* requireFullPermission */, false /* checkShell */, 6211 "getCookie"); 6212 if (!isCallerSameApp(packageName)) { 6213 return null; 6214 } 6215 synchronized (mPackages) { 6216 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6217 packageName, userId); 6218 } 6219 } 6220 6221 @Override 6222 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6223 if (DISABLE_EPHEMERAL_APPS) { 6224 return true; 6225 } 6226 6227 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6228 true /* requireFullPermission */, true /* checkShell */, 6229 "setCookie"); 6230 if (!isCallerSameApp(packageName)) { 6231 return false; 6232 } 6233 synchronized (mPackages) { 6234 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6235 packageName, cookie, userId); 6236 } 6237 } 6238 6239 @Override 6240 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6241 if (DISABLE_EPHEMERAL_APPS) { 6242 return null; 6243 } 6244 6245 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6246 "getEphemeralApplicationIcon"); 6247 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6248 true /* requireFullPermission */, false /* checkShell */, 6249 "getEphemeralApplicationIcon"); 6250 synchronized (mPackages) { 6251 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6252 packageName, userId); 6253 } 6254 } 6255 6256 private boolean isCallerSameApp(String packageName) { 6257 PackageParser.Package pkg = mPackages.get(packageName); 6258 return pkg != null 6259 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6260 } 6261 6262 @Override 6263 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 6264 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 6265 } 6266 6267 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 6268 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6269 6270 // reader 6271 synchronized (mPackages) { 6272 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6273 final int userId = UserHandle.getCallingUserId(); 6274 while (i.hasNext()) { 6275 final PackageParser.Package p = i.next(); 6276 if (p.applicationInfo == null) continue; 6277 6278 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 6279 && !p.applicationInfo.isDirectBootAware(); 6280 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 6281 && p.applicationInfo.isDirectBootAware(); 6282 6283 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6284 && (!mSafeMode || isSystemApp(p)) 6285 && (matchesUnaware || matchesAware)) { 6286 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6287 if (ps != null) { 6288 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6289 ps.readUserState(userId), userId); 6290 if (ai != null) { 6291 finalList.add(ai); 6292 } 6293 } 6294 } 6295 } 6296 } 6297 6298 return finalList; 6299 } 6300 6301 @Override 6302 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6303 if (!sUserManager.exists(userId)) return null; 6304 flags = updateFlagsForComponent(flags, userId, name); 6305 // reader 6306 synchronized (mPackages) { 6307 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6308 PackageSetting ps = provider != null 6309 ? mSettings.mPackages.get(provider.owner.packageName) 6310 : null; 6311 return ps != null 6312 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6313 ? PackageParser.generateProviderInfo(provider, flags, 6314 ps.readUserState(userId), userId) 6315 : null; 6316 } 6317 } 6318 6319 /** 6320 * @deprecated 6321 */ 6322 @Deprecated 6323 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6324 // reader 6325 synchronized (mPackages) { 6326 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6327 .entrySet().iterator(); 6328 final int userId = UserHandle.getCallingUserId(); 6329 while (i.hasNext()) { 6330 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6331 PackageParser.Provider p = entry.getValue(); 6332 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6333 6334 if (ps != null && p.syncable 6335 && (!mSafeMode || (p.info.applicationInfo.flags 6336 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6337 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6338 ps.readUserState(userId), userId); 6339 if (info != null) { 6340 outNames.add(entry.getKey()); 6341 outInfo.add(info); 6342 } 6343 } 6344 } 6345 } 6346 } 6347 6348 @Override 6349 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6350 int uid, int flags) { 6351 final int userId = processName != null ? UserHandle.getUserId(uid) 6352 : UserHandle.getCallingUserId(); 6353 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6354 flags = updateFlagsForComponent(flags, userId, processName); 6355 6356 ArrayList<ProviderInfo> finalList = null; 6357 // reader 6358 synchronized (mPackages) { 6359 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6360 while (i.hasNext()) { 6361 final PackageParser.Provider p = i.next(); 6362 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6363 if (ps != null && p.info.authority != null 6364 && (processName == null 6365 || (p.info.processName.equals(processName) 6366 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6367 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6368 if (finalList == null) { 6369 finalList = new ArrayList<ProviderInfo>(3); 6370 } 6371 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6372 ps.readUserState(userId), userId); 6373 if (info != null) { 6374 finalList.add(info); 6375 } 6376 } 6377 } 6378 } 6379 6380 if (finalList != null) { 6381 Collections.sort(finalList, mProviderInitOrderSorter); 6382 return new ParceledListSlice<ProviderInfo>(finalList); 6383 } 6384 6385 return ParceledListSlice.emptyList(); 6386 } 6387 6388 @Override 6389 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6390 // reader 6391 synchronized (mPackages) { 6392 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6393 return PackageParser.generateInstrumentationInfo(i, flags); 6394 } 6395 } 6396 6397 @Override 6398 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 6399 String targetPackage, int flags) { 6400 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 6401 } 6402 6403 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 6404 int flags) { 6405 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 6406 6407 // reader 6408 synchronized (mPackages) { 6409 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6410 while (i.hasNext()) { 6411 final PackageParser.Instrumentation p = i.next(); 6412 if (targetPackage == null 6413 || targetPackage.equals(p.info.targetPackage)) { 6414 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6415 flags); 6416 if (ii != null) { 6417 finalList.add(ii); 6418 } 6419 } 6420 } 6421 } 6422 6423 return finalList; 6424 } 6425 6426 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6427 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6428 if (overlays == null) { 6429 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6430 return; 6431 } 6432 for (PackageParser.Package opkg : overlays.values()) { 6433 // Not much to do if idmap fails: we already logged the error 6434 // and we certainly don't want to abort installation of pkg simply 6435 // because an overlay didn't fit properly. For these reasons, 6436 // ignore the return value of createIdmapForPackagePairLI. 6437 createIdmapForPackagePairLI(pkg, opkg); 6438 } 6439 } 6440 6441 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6442 PackageParser.Package opkg) { 6443 if (!opkg.mTrustedOverlay) { 6444 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6445 opkg.baseCodePath + ": overlay not trusted"); 6446 return false; 6447 } 6448 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6449 if (overlaySet == null) { 6450 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6451 opkg.baseCodePath + " but target package has no known overlays"); 6452 return false; 6453 } 6454 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6455 // TODO: generate idmap for split APKs 6456 try { 6457 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6458 } catch (InstallerException e) { 6459 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6460 + opkg.baseCodePath); 6461 return false; 6462 } 6463 PackageParser.Package[] overlayArray = 6464 overlaySet.values().toArray(new PackageParser.Package[0]); 6465 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6466 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6467 return p1.mOverlayPriority - p2.mOverlayPriority; 6468 } 6469 }; 6470 Arrays.sort(overlayArray, cmp); 6471 6472 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6473 int i = 0; 6474 for (PackageParser.Package p : overlayArray) { 6475 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6476 } 6477 return true; 6478 } 6479 6480 private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6481 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6482 try { 6483 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6484 } finally { 6485 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6486 } 6487 } 6488 6489 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6490 final File[] files = dir.listFiles(); 6491 if (ArrayUtils.isEmpty(files)) { 6492 Log.d(TAG, "No files in app dir " + dir); 6493 return; 6494 } 6495 6496 if (DEBUG_PACKAGE_SCANNING) { 6497 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6498 + " flags=0x" + Integer.toHexString(parseFlags)); 6499 } 6500 6501 for (File file : files) { 6502 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6503 && !PackageInstallerService.isStageName(file.getName()); 6504 if (!isPackage) { 6505 // Ignore entries which are not packages 6506 continue; 6507 } 6508 try { 6509 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6510 scanFlags, currentTime, null); 6511 } catch (PackageManagerException e) { 6512 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6513 6514 // Delete invalid userdata apps 6515 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6516 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6517 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6518 removeCodePathLI(file); 6519 } 6520 } 6521 } 6522 } 6523 6524 private static File getSettingsProblemFile() { 6525 File dataDir = Environment.getDataDirectory(); 6526 File systemDir = new File(dataDir, "system"); 6527 File fname = new File(systemDir, "uiderrors.txt"); 6528 return fname; 6529 } 6530 6531 static void reportSettingsProblem(int priority, String msg) { 6532 logCriticalInfo(priority, msg); 6533 } 6534 6535 static void logCriticalInfo(int priority, String msg) { 6536 Slog.println(priority, TAG, msg); 6537 EventLogTags.writePmCriticalInfo(msg); 6538 try { 6539 File fname = getSettingsProblemFile(); 6540 FileOutputStream out = new FileOutputStream(fname, true); 6541 PrintWriter pw = new FastPrintWriter(out); 6542 SimpleDateFormat formatter = new SimpleDateFormat(); 6543 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6544 pw.println(dateString + ": " + msg); 6545 pw.close(); 6546 FileUtils.setPermissions( 6547 fname.toString(), 6548 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6549 -1, -1); 6550 } catch (java.io.IOException e) { 6551 } 6552 } 6553 6554 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6555 int parseFlags) throws PackageManagerException { 6556 if (ps != null 6557 && ps.codePath.equals(srcFile) 6558 && ps.timeStamp == srcFile.lastModified() 6559 && !isCompatSignatureUpdateNeeded(pkg) 6560 && !isRecoverSignatureUpdateNeeded(pkg)) { 6561 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6562 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6563 ArraySet<PublicKey> signingKs; 6564 synchronized (mPackages) { 6565 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6566 } 6567 if (ps.signatures.mSignatures != null 6568 && ps.signatures.mSignatures.length != 0 6569 && signingKs != null) { 6570 // Optimization: reuse the existing cached certificates 6571 // if the package appears to be unchanged. 6572 pkg.mSignatures = ps.signatures.mSignatures; 6573 pkg.mSigningKeys = signingKs; 6574 return; 6575 } 6576 6577 Slog.w(TAG, "PackageSetting for " + ps.name 6578 + " is missing signatures. Collecting certs again to recover them."); 6579 } else { 6580 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6581 } 6582 6583 try { 6584 PackageParser.collectCertificates(pkg, parseFlags); 6585 } catch (PackageParserException e) { 6586 throw PackageManagerException.from(e); 6587 } 6588 } 6589 6590 /** 6591 * Traces a package scan. 6592 * @see #scanPackageLI(File, int, int, long, UserHandle) 6593 */ 6594 private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags, 6595 long currentTime, UserHandle user) throws PackageManagerException { 6596 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6597 try { 6598 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6599 } finally { 6600 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6601 } 6602 } 6603 6604 /** 6605 * Scans a package and returns the newly parsed package. 6606 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6607 */ 6608 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6609 long currentTime, UserHandle user) throws PackageManagerException { 6610 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6611 parseFlags |= mDefParseFlags; 6612 PackageParser pp = new PackageParser(); 6613 pp.setSeparateProcesses(mSeparateProcesses); 6614 pp.setOnlyCoreApps(mOnlyCore); 6615 pp.setDisplayMetrics(mMetrics); 6616 6617 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6618 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6619 } 6620 6621 final PackageParser.Package pkg; 6622 try { 6623 pkg = pp.parsePackage(scanFile, parseFlags); 6624 } catch (PackageParserException e) { 6625 throw PackageManagerException.from(e); 6626 } 6627 6628 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6629 } 6630 6631 /** 6632 * Scans a package and returns the newly parsed package. 6633 * @throws PackageManagerException on a parse error. 6634 */ 6635 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6636 int parseFlags, int scanFlags, long currentTime, UserHandle user) 6637 throws PackageManagerException { 6638 // If the package has children and this is the first dive in the function 6639 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6640 // packages (parent and children) would be successfully scanned before the 6641 // actual scan since scanning mutates internal state and we want to atomically 6642 // install the package and its children. 6643 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6644 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6645 scanFlags |= SCAN_CHECK_ONLY; 6646 } 6647 } else { 6648 scanFlags &= ~SCAN_CHECK_ONLY; 6649 } 6650 6651 // Scan the parent 6652 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, parseFlags, 6653 scanFlags, currentTime, user); 6654 6655 // Scan the children 6656 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6657 for (int i = 0; i < childCount; i++) { 6658 PackageParser.Package childPackage = pkg.childPackages.get(i); 6659 scanPackageInternalLI(childPackage, scanFile, parseFlags, scanFlags, 6660 currentTime, user); 6661 } 6662 6663 6664 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6665 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6666 } 6667 6668 return scannedPkg; 6669 } 6670 6671 /** 6672 * Scans a package and returns the newly parsed package. 6673 * @throws PackageManagerException on a parse error. 6674 */ 6675 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6676 int parseFlags, int scanFlags, long currentTime, UserHandle user) 6677 throws PackageManagerException { 6678 PackageSetting ps = null; 6679 PackageSetting updatedPkg; 6680 // reader 6681 synchronized (mPackages) { 6682 // Look to see if we already know about this package. 6683 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6684 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6685 // This package has been renamed to its original name. Let's 6686 // use that. 6687 ps = mSettings.peekPackageLPr(oldName); 6688 } 6689 // If there was no original package, see one for the real package name. 6690 if (ps == null) { 6691 ps = mSettings.peekPackageLPr(pkg.packageName); 6692 } 6693 // Check to see if this package could be hiding/updating a system 6694 // package. Must look for it either under the original or real 6695 // package name depending on our state. 6696 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6697 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6698 6699 // If this is a package we don't know about on the system partition, we 6700 // may need to remove disabled child packages on the system partition 6701 // or may need to not add child packages if the parent apk is updated 6702 // on the data partition and no longer defines this child package. 6703 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6704 // If this is a parent package for an updated system app and this system 6705 // app got an OTA update which no longer defines some of the child packages 6706 // we have to prune them from the disabled system packages. 6707 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6708 if (disabledPs != null) { 6709 final int scannedChildCount = (pkg.childPackages != null) 6710 ? pkg.childPackages.size() : 0; 6711 final int disabledChildCount = disabledPs.childPackageNames != null 6712 ? disabledPs.childPackageNames.size() : 0; 6713 for (int i = 0; i < disabledChildCount; i++) { 6714 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6715 boolean disabledPackageAvailable = false; 6716 for (int j = 0; j < scannedChildCount; j++) { 6717 PackageParser.Package childPkg = pkg.childPackages.get(j); 6718 if (childPkg.packageName.equals(disabledChildPackageName)) { 6719 disabledPackageAvailable = true; 6720 break; 6721 } 6722 } 6723 if (!disabledPackageAvailable) { 6724 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6725 } 6726 } 6727 } 6728 } 6729 } 6730 6731 boolean updatedPkgBetter = false; 6732 // First check if this is a system package that may involve an update 6733 if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6734 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6735 // it needs to drop FLAG_PRIVILEGED. 6736 if (locationIsPrivileged(scanFile)) { 6737 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6738 } else { 6739 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6740 } 6741 6742 if (ps != null && !ps.codePath.equals(scanFile)) { 6743 // The path has changed from what was last scanned... check the 6744 // version of the new path against what we have stored to determine 6745 // what to do. 6746 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6747 if (pkg.mVersionCode <= ps.versionCode) { 6748 // The system package has been updated and the code path does not match 6749 // Ignore entry. Skip it. 6750 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6751 + " ignored: updated version " + ps.versionCode 6752 + " better than this " + pkg.mVersionCode); 6753 if (!updatedPkg.codePath.equals(scanFile)) { 6754 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6755 + ps.name + " changing from " + updatedPkg.codePathString 6756 + " to " + scanFile); 6757 updatedPkg.codePath = scanFile; 6758 updatedPkg.codePathString = scanFile.toString(); 6759 updatedPkg.resourcePath = scanFile; 6760 updatedPkg.resourcePathString = scanFile.toString(); 6761 } 6762 updatedPkg.pkg = pkg; 6763 updatedPkg.versionCode = pkg.mVersionCode; 6764 6765 // Update the disabled system child packages to point to the package too. 6766 final int childCount = updatedPkg.childPackageNames != null 6767 ? updatedPkg.childPackageNames.size() : 0; 6768 for (int i = 0; i < childCount; i++) { 6769 String childPackageName = updatedPkg.childPackageNames.get(i); 6770 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 6771 childPackageName); 6772 if (updatedChildPkg != null) { 6773 updatedChildPkg.pkg = pkg; 6774 updatedChildPkg.versionCode = pkg.mVersionCode; 6775 } 6776 } 6777 6778 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 6779 + scanFile + " ignored: updated version " + ps.versionCode 6780 + " better than this " + pkg.mVersionCode); 6781 } else { 6782 // The current app on the system partition is better than 6783 // what we have updated to on the data partition; switch 6784 // back to the system partition version. 6785 // At this point, its safely assumed that package installation for 6786 // apps in system partition will go through. If not there won't be a working 6787 // version of the app 6788 // writer 6789 synchronized (mPackages) { 6790 // Just remove the loaded entries from package lists. 6791 mPackages.remove(ps.name); 6792 } 6793 6794 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6795 + " reverting from " + ps.codePathString 6796 + ": new version " + pkg.mVersionCode 6797 + " better than installed " + ps.versionCode); 6798 6799 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6800 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6801 synchronized (mInstallLock) { 6802 args.cleanUpResourcesLI(); 6803 } 6804 synchronized (mPackages) { 6805 mSettings.enableSystemPackageLPw(ps.name); 6806 } 6807 updatedPkgBetter = true; 6808 } 6809 } 6810 } 6811 6812 if (updatedPkg != null) { 6813 // An updated system app will not have the PARSE_IS_SYSTEM flag set 6814 // initially 6815 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 6816 6817 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 6818 // flag set initially 6819 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 6820 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 6821 } 6822 } 6823 6824 // Verify certificates against what was last scanned 6825 collectCertificatesLI(ps, pkg, scanFile, parseFlags); 6826 6827 /* 6828 * A new system app appeared, but we already had a non-system one of the 6829 * same name installed earlier. 6830 */ 6831 boolean shouldHideSystemApp = false; 6832 if (updatedPkg == null && ps != null 6833 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 6834 /* 6835 * Check to make sure the signatures match first. If they don't, 6836 * wipe the installed application and its data. 6837 */ 6838 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 6839 != PackageManager.SIGNATURE_MATCH) { 6840 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 6841 + " signatures don't match existing userdata copy; removing"); 6842 try (PackageFreezer freezer = freezePackage(pkg.packageName, 6843 "scanPackageInternalLI")) { 6844 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 6845 } 6846 ps = null; 6847 } else { 6848 /* 6849 * If the newly-added system app is an older version than the 6850 * already installed version, hide it. It will be scanned later 6851 * and re-added like an update. 6852 */ 6853 if (pkg.mVersionCode <= ps.versionCode) { 6854 shouldHideSystemApp = true; 6855 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 6856 + " but new version " + pkg.mVersionCode + " better than installed " 6857 + ps.versionCode + "; hiding system"); 6858 } else { 6859 /* 6860 * The newly found system app is a newer version that the 6861 * one previously installed. Simply remove the 6862 * already-installed application and replace it with our own 6863 * while keeping the application data. 6864 */ 6865 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6866 + " reverting from " + ps.codePathString + ": new version " 6867 + pkg.mVersionCode + " better than installed " + ps.versionCode); 6868 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6869 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6870 synchronized (mInstallLock) { 6871 args.cleanUpResourcesLI(); 6872 } 6873 } 6874 } 6875 } 6876 6877 // The apk is forward locked (not public) if its code and resources 6878 // are kept in different files. (except for app in either system or 6879 // vendor path). 6880 // TODO grab this value from PackageSettings 6881 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6882 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 6883 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 6884 } 6885 } 6886 6887 // TODO: extend to support forward-locked splits 6888 String resourcePath = null; 6889 String baseResourcePath = null; 6890 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 6891 if (ps != null && ps.resourcePathString != null) { 6892 resourcePath = ps.resourcePathString; 6893 baseResourcePath = ps.resourcePathString; 6894 } else { 6895 // Should not happen at all. Just log an error. 6896 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 6897 } 6898 } else { 6899 resourcePath = pkg.codePath; 6900 baseResourcePath = pkg.baseCodePath; 6901 } 6902 6903 // Set application objects path explicitly. 6904 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 6905 pkg.setApplicationInfoCodePath(pkg.codePath); 6906 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 6907 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 6908 pkg.setApplicationInfoResourcePath(resourcePath); 6909 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 6910 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 6911 6912 // Note that we invoke the following method only if we are about to unpack an application 6913 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 6914 | SCAN_UPDATE_SIGNATURE, currentTime, user); 6915 6916 /* 6917 * If the system app should be overridden by a previously installed 6918 * data, hide the system app now and let the /data/app scan pick it up 6919 * again. 6920 */ 6921 if (shouldHideSystemApp) { 6922 synchronized (mPackages) { 6923 mSettings.disableSystemPackageLPw(pkg.packageName, true); 6924 } 6925 } 6926 6927 return scannedPkg; 6928 } 6929 6930 private static String fixProcessName(String defProcessName, 6931 String processName, int uid) { 6932 if (processName == null) { 6933 return defProcessName; 6934 } 6935 return processName; 6936 } 6937 6938 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 6939 throws PackageManagerException { 6940 if (pkgSetting.signatures.mSignatures != null) { 6941 // Already existing package. Make sure signatures match 6942 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 6943 == PackageManager.SIGNATURE_MATCH; 6944 if (!match) { 6945 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 6946 == PackageManager.SIGNATURE_MATCH; 6947 } 6948 if (!match) { 6949 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 6950 == PackageManager.SIGNATURE_MATCH; 6951 } 6952 if (!match) { 6953 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 6954 + pkg.packageName + " signatures do not match the " 6955 + "previously installed version; ignoring!"); 6956 } 6957 } 6958 6959 // Check for shared user signatures 6960 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 6961 // Already existing package. Make sure signatures match 6962 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6963 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 6964 if (!match) { 6965 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 6966 == PackageManager.SIGNATURE_MATCH; 6967 } 6968 if (!match) { 6969 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 6970 == PackageManager.SIGNATURE_MATCH; 6971 } 6972 if (!match) { 6973 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 6974 "Package " + pkg.packageName 6975 + " has no signatures that match those in shared user " 6976 + pkgSetting.sharedUser.name + "; ignoring!"); 6977 } 6978 } 6979 } 6980 6981 /** 6982 * Enforces that only the system UID or root's UID can call a method exposed 6983 * via Binder. 6984 * 6985 * @param message used as message if SecurityException is thrown 6986 * @throws SecurityException if the caller is not system or root 6987 */ 6988 private static final void enforceSystemOrRoot(String message) { 6989 final int uid = Binder.getCallingUid(); 6990 if (uid != Process.SYSTEM_UID && uid != 0) { 6991 throw new SecurityException(message); 6992 } 6993 } 6994 6995 @Override 6996 public void performFstrimIfNeeded() { 6997 enforceSystemOrRoot("Only the system can request fstrim"); 6998 6999 // Before everything else, see whether we need to fstrim. 7000 try { 7001 IMountService ms = PackageHelper.getMountService(); 7002 if (ms != null) { 7003 final boolean isUpgrade = isUpgrade(); 7004 boolean doTrim = isUpgrade; 7005 if (doTrim) { 7006 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 7007 } else { 7008 final long interval = android.provider.Settings.Global.getLong( 7009 mContext.getContentResolver(), 7010 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 7011 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 7012 if (interval > 0) { 7013 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 7014 if (timeSinceLast > interval) { 7015 doTrim = true; 7016 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 7017 + "; running immediately"); 7018 } 7019 } 7020 } 7021 if (doTrim) { 7022 if (!isFirstBoot()) { 7023 try { 7024 ActivityManagerNative.getDefault().showBootMessage( 7025 mContext.getResources().getString( 7026 R.string.android_upgrading_fstrim), true); 7027 } catch (RemoteException e) { 7028 } 7029 } 7030 ms.runMaintenance(); 7031 } 7032 } else { 7033 Slog.e(TAG, "Mount service unavailable!"); 7034 } 7035 } catch (RemoteException e) { 7036 // Can't happen; MountService is local 7037 } 7038 } 7039 7040 @Override 7041 public void updatePackagesIfNeeded() { 7042 enforceSystemOrRoot("Only the system can request package update"); 7043 7044 // We need to re-extract after an OTA. 7045 boolean causeUpgrade = isUpgrade(); 7046 7047 // First boot or factory reset. 7048 // Note: we also handle devices that are upgrading to N right now as if it is their 7049 // first boot, as they do not have profile data. 7050 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 7051 7052 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 7053 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 7054 7055 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 7056 return; 7057 } 7058 7059 List<PackageParser.Package> pkgs; 7060 synchronized (mPackages) { 7061 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 7062 } 7063 7064 UsageStatsManager usageMgr = 7065 (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 7066 7067 int curr = 0; 7068 int total = pkgs.size(); 7069 for (PackageParser.Package pkg : pkgs) { 7070 curr++; 7071 7072 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 7073 if (DEBUG_DEXOPT) { 7074 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 7075 } 7076 continue; 7077 } 7078 7079 if (!causeFirstBoot && usageMgr.isAppInactive(pkg.packageName)) { 7080 if (DEBUG_DEXOPT) { 7081 Log.i(TAG, "Skipping update of of idle app " + pkg.packageName); 7082 } 7083 continue; 7084 } 7085 7086 if (DEBUG_DEXOPT) { 7087 Log.i(TAG, "Extracting app " + curr + " of " + total + ": " + pkg.packageName); 7088 } 7089 7090 if (!isFirstBoot()) { 7091 try { 7092 ActivityManagerNative.getDefault().showBootMessage( 7093 mContext.getResources().getString(R.string.android_upgrading_apk, 7094 curr, total), true); 7095 } catch (RemoteException e) { 7096 } 7097 } 7098 7099 performDexOpt(pkg.packageName, 7100 null /* instructionSet */, 7101 false /* checkProfiles */, 7102 causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT, 7103 false /* force */); 7104 } 7105 } 7106 7107 @Override 7108 public void notifyPackageUse(String packageName) { 7109 synchronized (mPackages) { 7110 PackageParser.Package p = mPackages.get(packageName); 7111 if (p == null) { 7112 return; 7113 } 7114 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 7115 } 7116 } 7117 7118 // TODO: this is not used nor needed. Delete it. 7119 @Override 7120 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 7121 return performDexOptTraced(packageName, instructionSet, false /* checkProfiles */, 7122 getFullCompilerFilter(), false /* force */); 7123 } 7124 7125 @Override 7126 public boolean performDexOpt(String packageName, String instructionSet, 7127 boolean checkProfiles, int compileReason, boolean force) { 7128 return performDexOptTraced(packageName, instructionSet, checkProfiles, 7129 getCompilerFilterForReason(compileReason), force); 7130 } 7131 7132 @Override 7133 public boolean performDexOptMode(String packageName, String instructionSet, 7134 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7135 return performDexOptTraced(packageName, instructionSet, checkProfiles, 7136 targetCompilerFilter, force); 7137 } 7138 7139 private boolean performDexOptTraced(String packageName, String instructionSet, 7140 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7141 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7142 try { 7143 return performDexOptInternal(packageName, instructionSet, checkProfiles, 7144 targetCompilerFilter, force); 7145 } finally { 7146 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7147 } 7148 } 7149 7150 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 7151 // if the package can now be considered up to date for the given filter. 7152 private boolean performDexOptInternal(String packageName, String instructionSet, 7153 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7154 PackageParser.Package p; 7155 final String targetInstructionSet; 7156 synchronized (mPackages) { 7157 p = mPackages.get(packageName); 7158 if (p == null) { 7159 return false; 7160 } 7161 mPackageUsage.write(false); 7162 7163 targetInstructionSet = instructionSet != null ? instructionSet : 7164 getPrimaryInstructionSet(p.applicationInfo); 7165 } 7166 long callingId = Binder.clearCallingIdentity(); 7167 try { 7168 synchronized (mInstallLock) { 7169 final String[] instructionSets = new String[] { targetInstructionSet }; 7170 int result = performDexOptInternalWithDependenciesLI(p, instructionSets, 7171 checkProfiles, targetCompilerFilter, force); 7172 return result != PackageDexOptimizer.DEX_OPT_FAILED; 7173 } 7174 } finally { 7175 Binder.restoreCallingIdentity(callingId); 7176 } 7177 } 7178 7179 public ArraySet<String> getOptimizablePackages() { 7180 ArraySet<String> pkgs = new ArraySet<String>(); 7181 synchronized (mPackages) { 7182 for (PackageParser.Package p : mPackages.values()) { 7183 if (PackageDexOptimizer.canOptimizePackage(p)) { 7184 pkgs.add(p.packageName); 7185 } 7186 } 7187 } 7188 return pkgs; 7189 } 7190 7191 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7192 String instructionSets[], boolean checkProfiles, String targetCompilerFilter, 7193 boolean force) { 7194 // Select the dex optimizer based on the force parameter. 7195 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7196 // allocate an object here. 7197 PackageDexOptimizer pdo = force 7198 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7199 : mPackageDexOptimizer; 7200 7201 // Optimize all dependencies first. Note: we ignore the return value and march on 7202 // on errors. 7203 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7204 if (!deps.isEmpty()) { 7205 for (PackageParser.Package depPackage : deps) { 7206 // TODO: Analyze and investigate if we (should) profile libraries. 7207 // Currently this will do a full compilation of the library by default. 7208 pdo.performDexOpt(depPackage, instructionSets, false /* checkProfiles */, 7209 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY)); 7210 } 7211 } 7212 7213 return pdo.performDexOpt(p, instructionSets, checkProfiles, targetCompilerFilter); 7214 } 7215 7216 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7217 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7218 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7219 Set<String> collectedNames = new HashSet<>(); 7220 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7221 7222 retValue.remove(p); 7223 7224 return retValue; 7225 } else { 7226 return Collections.emptyList(); 7227 } 7228 } 7229 7230 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7231 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7232 if (!collectedNames.contains(p.packageName)) { 7233 collectedNames.add(p.packageName); 7234 collected.add(p); 7235 7236 if (p.usesLibraries != null) { 7237 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7238 } 7239 if (p.usesOptionalLibraries != null) { 7240 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7241 collectedNames); 7242 } 7243 } 7244 } 7245 7246 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7247 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7248 for (String libName : libs) { 7249 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7250 if (libPkg != null) { 7251 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7252 } 7253 } 7254 } 7255 7256 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7257 synchronized (mPackages) { 7258 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7259 if (lib != null && lib.apk != null) { 7260 return mPackages.get(lib.apk); 7261 } 7262 } 7263 return null; 7264 } 7265 7266 public void shutdown() { 7267 mPackageUsage.write(true); 7268 } 7269 7270 @Override 7271 public void forceDexOpt(String packageName) { 7272 enforceSystemOrRoot("forceDexOpt"); 7273 7274 PackageParser.Package pkg; 7275 synchronized (mPackages) { 7276 pkg = mPackages.get(packageName); 7277 if (pkg == null) { 7278 throw new IllegalArgumentException("Unknown package: " + packageName); 7279 } 7280 } 7281 7282 synchronized (mInstallLock) { 7283 final String[] instructionSets = new String[] { 7284 getPrimaryInstructionSet(pkg.applicationInfo) }; 7285 7286 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7287 7288 // Whoever is calling forceDexOpt wants a fully compiled package. 7289 // Don't use profiles since that may cause compilation to be skipped. 7290 final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets, 7291 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7292 true /* force */); 7293 7294 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7295 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7296 throw new IllegalStateException("Failed to dexopt: " + res); 7297 } 7298 } 7299 } 7300 7301 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7302 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7303 Slog.w(TAG, "Unable to update from " + oldPkg.name 7304 + " to " + newPkg.packageName 7305 + ": old package not in system partition"); 7306 return false; 7307 } else if (mPackages.get(oldPkg.name) != null) { 7308 Slog.w(TAG, "Unable to update from " + oldPkg.name 7309 + " to " + newPkg.packageName 7310 + ": old package still exists"); 7311 return false; 7312 } 7313 return true; 7314 } 7315 7316 void removeCodePathLI(File codePath) { 7317 if (codePath.isDirectory()) { 7318 try { 7319 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7320 } catch (InstallerException e) { 7321 Slog.w(TAG, "Failed to remove code path", e); 7322 } 7323 } else { 7324 codePath.delete(); 7325 } 7326 } 7327 7328 private int[] resolveUserIds(int userId) { 7329 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 7330 } 7331 7332 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7333 if (pkg == null) { 7334 Slog.wtf(TAG, "Package was null!", new Throwable()); 7335 return; 7336 } 7337 clearAppDataLeafLIF(pkg, userId, flags); 7338 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7339 for (int i = 0; i < childCount; i++) { 7340 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7341 } 7342 } 7343 7344 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7345 final PackageSetting ps; 7346 synchronized (mPackages) { 7347 ps = mSettings.mPackages.get(pkg.packageName); 7348 } 7349 for (int realUserId : resolveUserIds(userId)) { 7350 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7351 try { 7352 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7353 ceDataInode); 7354 } catch (InstallerException e) { 7355 Slog.w(TAG, String.valueOf(e)); 7356 } 7357 } 7358 } 7359 7360 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7361 if (pkg == null) { 7362 Slog.wtf(TAG, "Package was null!", new Throwable()); 7363 return; 7364 } 7365 destroyAppDataLeafLIF(pkg, userId, flags); 7366 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7367 for (int i = 0; i < childCount; i++) { 7368 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7369 } 7370 } 7371 7372 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7373 final PackageSetting ps; 7374 synchronized (mPackages) { 7375 ps = mSettings.mPackages.get(pkg.packageName); 7376 } 7377 for (int realUserId : resolveUserIds(userId)) { 7378 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7379 try { 7380 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7381 ceDataInode); 7382 } catch (InstallerException e) { 7383 Slog.w(TAG, String.valueOf(e)); 7384 } 7385 } 7386 } 7387 7388 private void destroyAppProfilesLIF(PackageParser.Package pkg) { 7389 if (pkg == null) { 7390 Slog.wtf(TAG, "Package was null!", new Throwable()); 7391 return; 7392 } 7393 destroyAppProfilesLeafLIF(pkg); 7394 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7395 for (int i = 0; i < childCount; i++) { 7396 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 7397 } 7398 } 7399 7400 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 7401 try { 7402 mInstaller.destroyAppProfiles(pkg.packageName); 7403 } catch (InstallerException e) { 7404 Slog.w(TAG, String.valueOf(e)); 7405 } 7406 } 7407 7408 private void clearAppProfilesLIF(PackageParser.Package pkg) { 7409 if (pkg == null) { 7410 Slog.wtf(TAG, "Package was null!", new Throwable()); 7411 return; 7412 } 7413 clearAppProfilesLeafLIF(pkg); 7414 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7415 for (int i = 0; i < childCount; i++) { 7416 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 7417 } 7418 } 7419 7420 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 7421 try { 7422 mInstaller.clearAppProfiles(pkg.packageName); 7423 } catch (InstallerException e) { 7424 Slog.w(TAG, String.valueOf(e)); 7425 } 7426 } 7427 7428 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7429 long lastUpdateTime) { 7430 // Set parent install/update time 7431 PackageSetting ps = (PackageSetting) pkg.mExtras; 7432 if (ps != null) { 7433 ps.firstInstallTime = firstInstallTime; 7434 ps.lastUpdateTime = lastUpdateTime; 7435 } 7436 // Set children install/update time 7437 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7438 for (int i = 0; i < childCount; i++) { 7439 PackageParser.Package childPkg = pkg.childPackages.get(i); 7440 ps = (PackageSetting) childPkg.mExtras; 7441 if (ps != null) { 7442 ps.firstInstallTime = firstInstallTime; 7443 ps.lastUpdateTime = lastUpdateTime; 7444 } 7445 } 7446 } 7447 7448 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7449 PackageParser.Package changingLib) { 7450 if (file.path != null) { 7451 usesLibraryFiles.add(file.path); 7452 return; 7453 } 7454 PackageParser.Package p = mPackages.get(file.apk); 7455 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7456 // If we are doing this while in the middle of updating a library apk, 7457 // then we need to make sure to use that new apk for determining the 7458 // dependencies here. (We haven't yet finished committing the new apk 7459 // to the package manager state.) 7460 if (p == null || p.packageName.equals(changingLib.packageName)) { 7461 p = changingLib; 7462 } 7463 } 7464 if (p != null) { 7465 usesLibraryFiles.addAll(p.getAllCodePaths()); 7466 } 7467 } 7468 7469 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7470 PackageParser.Package changingLib) throws PackageManagerException { 7471 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7472 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7473 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7474 for (int i=0; i<N; i++) { 7475 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7476 if (file == null) { 7477 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7478 "Package " + pkg.packageName + " requires unavailable shared library " 7479 + pkg.usesLibraries.get(i) + "; failing!"); 7480 } 7481 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7482 } 7483 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7484 for (int i=0; i<N; i++) { 7485 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7486 if (file == null) { 7487 Slog.w(TAG, "Package " + pkg.packageName 7488 + " desires unavailable shared library " 7489 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7490 } else { 7491 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7492 } 7493 } 7494 N = usesLibraryFiles.size(); 7495 if (N > 0) { 7496 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7497 } else { 7498 pkg.usesLibraryFiles = null; 7499 } 7500 } 7501 } 7502 7503 private static boolean hasString(List<String> list, List<String> which) { 7504 if (list == null) { 7505 return false; 7506 } 7507 for (int i=list.size()-1; i>=0; i--) { 7508 for (int j=which.size()-1; j>=0; j--) { 7509 if (which.get(j).equals(list.get(i))) { 7510 return true; 7511 } 7512 } 7513 } 7514 return false; 7515 } 7516 7517 private void updateAllSharedLibrariesLPw() { 7518 for (PackageParser.Package pkg : mPackages.values()) { 7519 try { 7520 updateSharedLibrariesLPw(pkg, null); 7521 } catch (PackageManagerException e) { 7522 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7523 } 7524 } 7525 } 7526 7527 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7528 PackageParser.Package changingPkg) { 7529 ArrayList<PackageParser.Package> res = null; 7530 for (PackageParser.Package pkg : mPackages.values()) { 7531 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7532 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7533 if (res == null) { 7534 res = new ArrayList<PackageParser.Package>(); 7535 } 7536 res.add(pkg); 7537 try { 7538 updateSharedLibrariesLPw(pkg, changingPkg); 7539 } catch (PackageManagerException e) { 7540 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7541 } 7542 } 7543 } 7544 return res; 7545 } 7546 7547 /** 7548 * Derive the value of the {@code cpuAbiOverride} based on the provided 7549 * value and an optional stored value from the package settings. 7550 */ 7551 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7552 String cpuAbiOverride = null; 7553 7554 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7555 cpuAbiOverride = null; 7556 } else if (abiOverride != null) { 7557 cpuAbiOverride = abiOverride; 7558 } else if (settings != null) { 7559 cpuAbiOverride = settings.cpuAbiOverrideString; 7560 } 7561 7562 return cpuAbiOverride; 7563 } 7564 7565 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags, 7566 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7567 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7568 // If the package has children and this is the first dive in the function 7569 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7570 // whether all packages (parent and children) would be successfully scanned 7571 // before the actual scan since scanning mutates internal state and we want 7572 // to atomically install the package and its children. 7573 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7574 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7575 scanFlags |= SCAN_CHECK_ONLY; 7576 } 7577 } else { 7578 scanFlags &= ~SCAN_CHECK_ONLY; 7579 } 7580 7581 final PackageParser.Package scannedPkg; 7582 try { 7583 // Scan the parent 7584 scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user); 7585 // Scan the children 7586 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7587 for (int i = 0; i < childCount; i++) { 7588 PackageParser.Package childPkg = pkg.childPackages.get(i); 7589 scanPackageLI(childPkg, parseFlags, 7590 scanFlags, currentTime, user); 7591 } 7592 } finally { 7593 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7594 } 7595 7596 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7597 return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user); 7598 } 7599 7600 return scannedPkg; 7601 } 7602 7603 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 7604 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7605 boolean success = false; 7606 try { 7607 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 7608 currentTime, user); 7609 success = true; 7610 return res; 7611 } finally { 7612 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 7613 // DELETE_DATA_ON_FAILURES is only used by frozen paths 7614 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 7615 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 7616 destroyAppProfilesLIF(pkg); 7617 } 7618 } 7619 } 7620 7621 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 7622 int scanFlags, long currentTime, UserHandle user) 7623 throws PackageManagerException { 7624 final File scanFile = new File(pkg.codePath); 7625 if (pkg.applicationInfo.getCodePath() == null || 7626 pkg.applicationInfo.getResourcePath() == null) { 7627 // Bail out. The resource and code paths haven't been set. 7628 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7629 "Code and resource paths haven't been set correctly"); 7630 } 7631 7632 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 7633 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 7634 } else { 7635 // Only allow system apps to be flagged as core apps. 7636 pkg.coreApp = false; 7637 } 7638 7639 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 7640 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7641 } 7642 7643 if (mCustomResolverComponentName != null && 7644 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 7645 setUpCustomResolverActivity(pkg); 7646 } 7647 7648 if (pkg.packageName.equals("android")) { 7649 synchronized (mPackages) { 7650 if (mAndroidApplication != null) { 7651 Slog.w(TAG, "*************************************************"); 7652 Slog.w(TAG, "Core android package being redefined. Skipping."); 7653 Slog.w(TAG, " file=" + scanFile); 7654 Slog.w(TAG, "*************************************************"); 7655 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7656 "Core android package being redefined. Skipping."); 7657 } 7658 7659 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7660 // Set up information for our fall-back user intent resolution activity. 7661 mPlatformPackage = pkg; 7662 pkg.mVersionCode = mSdkVersion; 7663 mAndroidApplication = pkg.applicationInfo; 7664 7665 if (!mResolverReplaced) { 7666 mResolveActivity.applicationInfo = mAndroidApplication; 7667 mResolveActivity.name = ResolverActivity.class.getName(); 7668 mResolveActivity.packageName = mAndroidApplication.packageName; 7669 mResolveActivity.processName = "system:ui"; 7670 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7671 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 7672 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 7673 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 7674 mResolveActivity.exported = true; 7675 mResolveActivity.enabled = true; 7676 mResolveInfo.activityInfo = mResolveActivity; 7677 mResolveInfo.priority = 0; 7678 mResolveInfo.preferredOrder = 0; 7679 mResolveInfo.match = 0; 7680 mResolveComponentName = new ComponentName( 7681 mAndroidApplication.packageName, mResolveActivity.name); 7682 } 7683 } 7684 } 7685 } 7686 7687 if (DEBUG_PACKAGE_SCANNING) { 7688 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7689 Log.d(TAG, "Scanning package " + pkg.packageName); 7690 } 7691 7692 synchronized (mPackages) { 7693 if (mPackages.containsKey(pkg.packageName) 7694 || mSharedLibraries.containsKey(pkg.packageName)) { 7695 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7696 "Application package " + pkg.packageName 7697 + " already installed. Skipping duplicate."); 7698 } 7699 7700 // If we're only installing presumed-existing packages, require that the 7701 // scanned APK is both already known and at the path previously established 7702 // for it. Previously unknown packages we pick up normally, but if we have an 7703 // a priori expectation about this package's install presence, enforce it. 7704 // With a singular exception for new system packages. When an OTA contains 7705 // a new system package, we allow the codepath to change from a system location 7706 // to the user-installed location. If we don't allow this change, any newer, 7707 // user-installed version of the application will be ignored. 7708 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 7709 if (mExpectingBetter.containsKey(pkg.packageName)) { 7710 logCriticalInfo(Log.WARN, 7711 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 7712 } else { 7713 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 7714 if (known != null) { 7715 if (DEBUG_PACKAGE_SCANNING) { 7716 Log.d(TAG, "Examining " + pkg.codePath 7717 + " and requiring known paths " + known.codePathString 7718 + " & " + known.resourcePathString); 7719 } 7720 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 7721 || !pkg.applicationInfo.getResourcePath().equals( 7722 known.resourcePathString)) { 7723 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 7724 "Application package " + pkg.packageName 7725 + " found at " + pkg.applicationInfo.getCodePath() 7726 + " but expected at " + known.codePathString 7727 + "; ignoring."); 7728 } 7729 } 7730 } 7731 } 7732 } 7733 7734 // Initialize package source and resource directories 7735 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 7736 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 7737 7738 SharedUserSetting suid = null; 7739 PackageSetting pkgSetting = null; 7740 7741 if (!isSystemApp(pkg)) { 7742 // Only system apps can use these features. 7743 pkg.mOriginalPackages = null; 7744 pkg.mRealPackage = null; 7745 pkg.mAdoptPermissions = null; 7746 } 7747 7748 // Getting the package setting may have a side-effect, so if we 7749 // are only checking if scan would succeed, stash a copy of the 7750 // old setting to restore at the end. 7751 PackageSetting nonMutatedPs = null; 7752 7753 // writer 7754 synchronized (mPackages) { 7755 if (pkg.mSharedUserId != null) { 7756 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 7757 if (suid == null) { 7758 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7759 "Creating application package " + pkg.packageName 7760 + " for shared user failed"); 7761 } 7762 if (DEBUG_PACKAGE_SCANNING) { 7763 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7764 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 7765 + "): packages=" + suid.packages); 7766 } 7767 } 7768 7769 // Check if we are renaming from an original package name. 7770 PackageSetting origPackage = null; 7771 String realName = null; 7772 if (pkg.mOriginalPackages != null) { 7773 // This package may need to be renamed to a previously 7774 // installed name. Let's check on that... 7775 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 7776 if (pkg.mOriginalPackages.contains(renamed)) { 7777 // This package had originally been installed as the 7778 // original name, and we have already taken care of 7779 // transitioning to the new one. Just update the new 7780 // one to continue using the old name. 7781 realName = pkg.mRealPackage; 7782 if (!pkg.packageName.equals(renamed)) { 7783 // Callers into this function may have already taken 7784 // care of renaming the package; only do it here if 7785 // it is not already done. 7786 pkg.setPackageName(renamed); 7787 } 7788 7789 } else { 7790 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 7791 if ((origPackage = mSettings.peekPackageLPr( 7792 pkg.mOriginalPackages.get(i))) != null) { 7793 // We do have the package already installed under its 7794 // original name... should we use it? 7795 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 7796 // New package is not compatible with original. 7797 origPackage = null; 7798 continue; 7799 } else if (origPackage.sharedUser != null) { 7800 // Make sure uid is compatible between packages. 7801 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 7802 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 7803 + " to " + pkg.packageName + ": old uid " 7804 + origPackage.sharedUser.name 7805 + " differs from " + pkg.mSharedUserId); 7806 origPackage = null; 7807 continue; 7808 } 7809 } else { 7810 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 7811 + pkg.packageName + " to old name " + origPackage.name); 7812 } 7813 break; 7814 } 7815 } 7816 } 7817 } 7818 7819 if (mTransferedPackages.contains(pkg.packageName)) { 7820 Slog.w(TAG, "Package " + pkg.packageName 7821 + " was transferred to another, but its .apk remains"); 7822 } 7823 7824 // See comments in nonMutatedPs declaration 7825 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7826 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 7827 if (foundPs != null) { 7828 nonMutatedPs = new PackageSetting(foundPs); 7829 } 7830 } 7831 7832 // Just create the setting, don't add it yet. For already existing packages 7833 // the PkgSetting exists already and doesn't have to be created. 7834 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 7835 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 7836 pkg.applicationInfo.primaryCpuAbi, 7837 pkg.applicationInfo.secondaryCpuAbi, 7838 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 7839 user, false); 7840 if (pkgSetting == null) { 7841 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7842 "Creating application package " + pkg.packageName + " failed"); 7843 } 7844 7845 if (pkgSetting.origPackage != null) { 7846 // If we are first transitioning from an original package, 7847 // fix up the new package's name now. We need to do this after 7848 // looking up the package under its new name, so getPackageLP 7849 // can take care of fiddling things correctly. 7850 pkg.setPackageName(origPackage.name); 7851 7852 // File a report about this. 7853 String msg = "New package " + pkgSetting.realName 7854 + " renamed to replace old package " + pkgSetting.name; 7855 reportSettingsProblem(Log.WARN, msg); 7856 7857 // Make a note of it. 7858 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7859 mTransferedPackages.add(origPackage.name); 7860 } 7861 7862 // No longer need to retain this. 7863 pkgSetting.origPackage = null; 7864 } 7865 7866 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 7867 // Make a note of it. 7868 mTransferedPackages.add(pkg.packageName); 7869 } 7870 7871 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 7872 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 7873 } 7874 7875 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7876 // Check all shared libraries and map to their actual file path. 7877 // We only do this here for apps not on a system dir, because those 7878 // are the only ones that can fail an install due to this. We 7879 // will take care of the system apps by updating all of their 7880 // library paths after the scan is done. 7881 updateSharedLibrariesLPw(pkg, null); 7882 } 7883 7884 if (mFoundPolicyFile) { 7885 SELinuxMMAC.assignSeinfoValue(pkg); 7886 } 7887 7888 pkg.applicationInfo.uid = pkgSetting.appId; 7889 pkg.mExtras = pkgSetting; 7890 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 7891 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 7892 // We just determined the app is signed correctly, so bring 7893 // over the latest parsed certs. 7894 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7895 } else { 7896 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7897 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7898 "Package " + pkg.packageName + " upgrade keys do not match the " 7899 + "previously installed version"); 7900 } else { 7901 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7902 String msg = "System package " + pkg.packageName 7903 + " signature changed; retaining data."; 7904 reportSettingsProblem(Log.WARN, msg); 7905 } 7906 } 7907 } else { 7908 try { 7909 verifySignaturesLP(pkgSetting, pkg); 7910 // We just determined the app is signed correctly, so bring 7911 // over the latest parsed certs. 7912 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7913 } catch (PackageManagerException e) { 7914 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7915 throw e; 7916 } 7917 // The signature has changed, but this package is in the system 7918 // image... let's recover! 7919 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7920 // However... if this package is part of a shared user, but it 7921 // doesn't match the signature of the shared user, let's fail. 7922 // What this means is that you can't change the signatures 7923 // associated with an overall shared user, which doesn't seem all 7924 // that unreasonable. 7925 if (pkgSetting.sharedUser != null) { 7926 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7927 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 7928 throw new PackageManagerException( 7929 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 7930 "Signature mismatch for shared user: " 7931 + pkgSetting.sharedUser); 7932 } 7933 } 7934 // File a report about this. 7935 String msg = "System package " + pkg.packageName 7936 + " signature changed; retaining data."; 7937 reportSettingsProblem(Log.WARN, msg); 7938 } 7939 } 7940 // Verify that this new package doesn't have any content providers 7941 // that conflict with existing packages. Only do this if the 7942 // package isn't already installed, since we don't want to break 7943 // things that are installed. 7944 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 7945 final int N = pkg.providers.size(); 7946 int i; 7947 for (i=0; i<N; i++) { 7948 PackageParser.Provider p = pkg.providers.get(i); 7949 if (p.info.authority != null) { 7950 String names[] = p.info.authority.split(";"); 7951 for (int j = 0; j < names.length; j++) { 7952 if (mProvidersByAuthority.containsKey(names[j])) { 7953 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7954 final String otherPackageName = 7955 ((other != null && other.getComponentName() != null) ? 7956 other.getComponentName().getPackageName() : "?"); 7957 throw new PackageManagerException( 7958 INSTALL_FAILED_CONFLICTING_PROVIDER, 7959 "Can't install because provider name " + names[j] 7960 + " (in package " + pkg.applicationInfo.packageName 7961 + ") is already used by " + otherPackageName); 7962 } 7963 } 7964 } 7965 } 7966 } 7967 7968 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 7969 // This package wants to adopt ownership of permissions from 7970 // another package. 7971 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 7972 final String origName = pkg.mAdoptPermissions.get(i); 7973 final PackageSetting orig = mSettings.peekPackageLPr(origName); 7974 if (orig != null) { 7975 if (verifyPackageUpdateLPr(orig, pkg)) { 7976 Slog.i(TAG, "Adopting permissions from " + origName + " to " 7977 + pkg.packageName); 7978 mSettings.transferPermissionsLPw(origName, pkg.packageName); 7979 } 7980 } 7981 } 7982 } 7983 } 7984 7985 final String pkgName = pkg.packageName; 7986 7987 final long scanFileTime = scanFile.lastModified(); 7988 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 7989 pkg.applicationInfo.processName = fixProcessName( 7990 pkg.applicationInfo.packageName, 7991 pkg.applicationInfo.processName, 7992 pkg.applicationInfo.uid); 7993 7994 if (pkg != mPlatformPackage) { 7995 // Get all of our default paths setup 7996 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 7997 } 7998 7999 final String path = scanFile.getPath(); 8000 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 8001 8002 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 8003 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 8004 8005 // Some system apps still use directory structure for native libraries 8006 // in which case we might end up not detecting abi solely based on apk 8007 // structure. Try to detect abi based on directory structure. 8008 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 8009 pkg.applicationInfo.primaryCpuAbi == null) { 8010 setBundledAppAbisAndRoots(pkg, pkgSetting); 8011 setNativeLibraryPaths(pkg); 8012 } 8013 8014 } else { 8015 if ((scanFlags & SCAN_MOVE) != 0) { 8016 // We haven't run dex-opt for this move (since we've moved the compiled output too) 8017 // but we already have this packages package info in the PackageSetting. We just 8018 // use that and derive the native library path based on the new codepath. 8019 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 8020 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 8021 } 8022 8023 // Set native library paths again. For moves, the path will be updated based on the 8024 // ABIs we've determined above. For non-moves, the path will be updated based on the 8025 // ABIs we determined during compilation, but the path will depend on the final 8026 // package path (after the rename away from the stage path). 8027 setNativeLibraryPaths(pkg); 8028 } 8029 8030 // This is a special case for the "system" package, where the ABI is 8031 // dictated by the zygote configuration (and init.rc). We should keep track 8032 // of this ABI so that we can deal with "normal" applications that run under 8033 // the same UID correctly. 8034 if (mPlatformPackage == pkg) { 8035 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 8036 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 8037 } 8038 8039 // If there's a mismatch between the abi-override in the package setting 8040 // and the abiOverride specified for the install. Warn about this because we 8041 // would've already compiled the app without taking the package setting into 8042 // account. 8043 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 8044 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 8045 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 8046 " for package " + pkg.packageName); 8047 } 8048 } 8049 8050 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8051 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8052 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 8053 8054 // Copy the derived override back to the parsed package, so that we can 8055 // update the package settings accordingly. 8056 pkg.cpuAbiOverride = cpuAbiOverride; 8057 8058 if (DEBUG_ABI_SELECTION) { 8059 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 8060 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 8061 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 8062 } 8063 8064 // Push the derived path down into PackageSettings so we know what to 8065 // clean up at uninstall time. 8066 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 8067 8068 if (DEBUG_ABI_SELECTION) { 8069 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 8070 " primary=" + pkg.applicationInfo.primaryCpuAbi + 8071 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 8072 } 8073 8074 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 8075 // We don't do this here during boot because we can do it all 8076 // at once after scanning all existing packages. 8077 // 8078 // We also do this *before* we perform dexopt on this package, so that 8079 // we can avoid redundant dexopts, and also to make sure we've got the 8080 // code and package path correct. 8081 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 8082 pkg, true /* boot complete */); 8083 } 8084 8085 if (mFactoryTest && pkg.requestedPermissions.contains( 8086 android.Manifest.permission.FACTORY_TEST)) { 8087 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 8088 } 8089 8090 ArrayList<PackageParser.Package> clientLibPkgs = null; 8091 8092 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8093 if (nonMutatedPs != null) { 8094 synchronized (mPackages) { 8095 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 8096 } 8097 } 8098 return pkg; 8099 } 8100 8101 // Only privileged apps and updated privileged apps can add child packages. 8102 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 8103 if ((parseFlags & PARSE_IS_PRIVILEGED) == 0) { 8104 throw new PackageManagerException("Only privileged apps and updated " 8105 + "privileged apps can add child packages. Ignoring package " 8106 + pkg.packageName); 8107 } 8108 final int childCount = pkg.childPackages.size(); 8109 for (int i = 0; i < childCount; i++) { 8110 PackageParser.Package childPkg = pkg.childPackages.get(i); 8111 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 8112 childPkg.packageName)) { 8113 throw new PackageManagerException("Cannot override a child package of " 8114 + "another disabled system app. Ignoring package " + pkg.packageName); 8115 } 8116 } 8117 } 8118 8119 // writer 8120 synchronized (mPackages) { 8121 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8122 // Only system apps can add new shared libraries. 8123 if (pkg.libraryNames != null) { 8124 for (int i=0; i<pkg.libraryNames.size(); i++) { 8125 String name = pkg.libraryNames.get(i); 8126 boolean allowed = false; 8127 if (pkg.isUpdatedSystemApp()) { 8128 // New library entries can only be added through the 8129 // system image. This is important to get rid of a lot 8130 // of nasty edge cases: for example if we allowed a non- 8131 // system update of the app to add a library, then uninstalling 8132 // the update would make the library go away, and assumptions 8133 // we made such as through app install filtering would now 8134 // have allowed apps on the device which aren't compatible 8135 // with it. Better to just have the restriction here, be 8136 // conservative, and create many fewer cases that can negatively 8137 // impact the user experience. 8138 final PackageSetting sysPs = mSettings 8139 .getDisabledSystemPkgLPr(pkg.packageName); 8140 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 8141 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 8142 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 8143 allowed = true; 8144 break; 8145 } 8146 } 8147 } 8148 } else { 8149 allowed = true; 8150 } 8151 if (allowed) { 8152 if (!mSharedLibraries.containsKey(name)) { 8153 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 8154 } else if (!name.equals(pkg.packageName)) { 8155 Slog.w(TAG, "Package " + pkg.packageName + " library " 8156 + name + " already exists; skipping"); 8157 } 8158 } else { 8159 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 8160 + name + " that is not declared on system image; skipping"); 8161 } 8162 } 8163 if ((scanFlags & SCAN_BOOTING) == 0) { 8164 // If we are not booting, we need to update any applications 8165 // that are clients of our shared library. If we are booting, 8166 // this will all be done once the scan is complete. 8167 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 8168 } 8169 } 8170 } 8171 } 8172 8173 if ((scanFlags & SCAN_BOOTING) != 0) { 8174 // No apps can run during boot scan, so they don't need to be frozen 8175 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 8176 // Caller asked to not kill app, so it's probably not frozen 8177 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 8178 // Caller asked us to ignore frozen check for some reason; they 8179 // probably didn't know the package name 8180 } else { 8181 // We're doing major surgery on this package, so it better be frozen 8182 // right now to keep it from launching 8183 checkPackageFrozen(pkgName); 8184 } 8185 8186 // Also need to kill any apps that are dependent on the library. 8187 if (clientLibPkgs != null) { 8188 for (int i=0; i<clientLibPkgs.size(); i++) { 8189 PackageParser.Package clientPkg = clientLibPkgs.get(i); 8190 killApplication(clientPkg.applicationInfo.packageName, 8191 clientPkg.applicationInfo.uid, "update lib"); 8192 } 8193 } 8194 8195 // Make sure we're not adding any bogus keyset info 8196 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8197 ksms.assertScannedPackageValid(pkg); 8198 8199 // writer 8200 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 8201 8202 boolean createIdmapFailed = false; 8203 synchronized (mPackages) { 8204 // We don't expect installation to fail beyond this point 8205 8206 // Add the new setting to mSettings 8207 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 8208 // Add the new setting to mPackages 8209 mPackages.put(pkg.applicationInfo.packageName, pkg); 8210 // Make sure we don't accidentally delete its data. 8211 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 8212 while (iter.hasNext()) { 8213 PackageCleanItem item = iter.next(); 8214 if (pkgName.equals(item.packageName)) { 8215 iter.remove(); 8216 } 8217 } 8218 8219 // Take care of first install / last update times. 8220 if (currentTime != 0) { 8221 if (pkgSetting.firstInstallTime == 0) { 8222 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8223 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 8224 pkgSetting.lastUpdateTime = currentTime; 8225 } 8226 } else if (pkgSetting.firstInstallTime == 0) { 8227 // We need *something*. Take time time stamp of the file. 8228 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8229 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8230 if (scanFileTime != pkgSetting.timeStamp) { 8231 // A package on the system image has changed; consider this 8232 // to be an update. 8233 pkgSetting.lastUpdateTime = scanFileTime; 8234 } 8235 } 8236 8237 // Add the package's KeySets to the global KeySetManagerService 8238 ksms.addScannedPackageLPw(pkg); 8239 8240 int N = pkg.providers.size(); 8241 StringBuilder r = null; 8242 int i; 8243 for (i=0; i<N; i++) { 8244 PackageParser.Provider p = pkg.providers.get(i); 8245 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 8246 p.info.processName, pkg.applicationInfo.uid); 8247 mProviders.addProvider(p); 8248 p.syncable = p.info.isSyncable; 8249 if (p.info.authority != null) { 8250 String names[] = p.info.authority.split(";"); 8251 p.info.authority = null; 8252 for (int j = 0; j < names.length; j++) { 8253 if (j == 1 && p.syncable) { 8254 // We only want the first authority for a provider to possibly be 8255 // syncable, so if we already added this provider using a different 8256 // authority clear the syncable flag. We copy the provider before 8257 // changing it because the mProviders object contains a reference 8258 // to a provider that we don't want to change. 8259 // Only do this for the second authority since the resulting provider 8260 // object can be the same for all future authorities for this provider. 8261 p = new PackageParser.Provider(p); 8262 p.syncable = false; 8263 } 8264 if (!mProvidersByAuthority.containsKey(names[j])) { 8265 mProvidersByAuthority.put(names[j], p); 8266 if (p.info.authority == null) { 8267 p.info.authority = names[j]; 8268 } else { 8269 p.info.authority = p.info.authority + ";" + names[j]; 8270 } 8271 if (DEBUG_PACKAGE_SCANNING) { 8272 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 8273 Log.d(TAG, "Registered content provider: " + names[j] 8274 + ", className = " + p.info.name + ", isSyncable = " 8275 + p.info.isSyncable); 8276 } 8277 } else { 8278 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8279 Slog.w(TAG, "Skipping provider name " + names[j] + 8280 " (in package " + pkg.applicationInfo.packageName + 8281 "): name already used by " 8282 + ((other != null && other.getComponentName() != null) 8283 ? other.getComponentName().getPackageName() : "?")); 8284 } 8285 } 8286 } 8287 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8288 if (r == null) { 8289 r = new StringBuilder(256); 8290 } else { 8291 r.append(' '); 8292 } 8293 r.append(p.info.name); 8294 } 8295 } 8296 if (r != null) { 8297 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8298 } 8299 8300 N = pkg.services.size(); 8301 r = null; 8302 for (i=0; i<N; i++) { 8303 PackageParser.Service s = pkg.services.get(i); 8304 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8305 s.info.processName, pkg.applicationInfo.uid); 8306 mServices.addService(s); 8307 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8308 if (r == null) { 8309 r = new StringBuilder(256); 8310 } else { 8311 r.append(' '); 8312 } 8313 r.append(s.info.name); 8314 } 8315 } 8316 if (r != null) { 8317 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8318 } 8319 8320 N = pkg.receivers.size(); 8321 r = null; 8322 for (i=0; i<N; i++) { 8323 PackageParser.Activity a = pkg.receivers.get(i); 8324 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8325 a.info.processName, pkg.applicationInfo.uid); 8326 mReceivers.addActivity(a, "receiver"); 8327 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8328 if (r == null) { 8329 r = new StringBuilder(256); 8330 } else { 8331 r.append(' '); 8332 } 8333 r.append(a.info.name); 8334 } 8335 } 8336 if (r != null) { 8337 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8338 } 8339 8340 N = pkg.activities.size(); 8341 r = null; 8342 for (i=0; i<N; i++) { 8343 PackageParser.Activity a = pkg.activities.get(i); 8344 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8345 a.info.processName, pkg.applicationInfo.uid); 8346 mActivities.addActivity(a, "activity"); 8347 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8348 if (r == null) { 8349 r = new StringBuilder(256); 8350 } else { 8351 r.append(' '); 8352 } 8353 r.append(a.info.name); 8354 } 8355 } 8356 if (r != null) { 8357 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8358 } 8359 8360 N = pkg.permissionGroups.size(); 8361 r = null; 8362 for (i=0; i<N; i++) { 8363 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8364 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8365 if (cur == null) { 8366 mPermissionGroups.put(pg.info.name, pg); 8367 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8368 if (r == null) { 8369 r = new StringBuilder(256); 8370 } else { 8371 r.append(' '); 8372 } 8373 r.append(pg.info.name); 8374 } 8375 } else { 8376 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8377 + pg.info.packageName + " ignored: original from " 8378 + cur.info.packageName); 8379 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8380 if (r == null) { 8381 r = new StringBuilder(256); 8382 } else { 8383 r.append(' '); 8384 } 8385 r.append("DUP:"); 8386 r.append(pg.info.name); 8387 } 8388 } 8389 } 8390 if (r != null) { 8391 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8392 } 8393 8394 N = pkg.permissions.size(); 8395 r = null; 8396 for (i=0; i<N; i++) { 8397 PackageParser.Permission p = pkg.permissions.get(i); 8398 8399 // Assume by default that we did not install this permission into the system. 8400 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8401 8402 // Now that permission groups have a special meaning, we ignore permission 8403 // groups for legacy apps to prevent unexpected behavior. In particular, 8404 // permissions for one app being granted to someone just becase they happen 8405 // to be in a group defined by another app (before this had no implications). 8406 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8407 p.group = mPermissionGroups.get(p.info.group); 8408 // Warn for a permission in an unknown group. 8409 if (p.info.group != null && p.group == null) { 8410 Slog.w(TAG, "Permission " + p.info.name + " from package " 8411 + p.info.packageName + " in an unknown group " + p.info.group); 8412 } 8413 } 8414 8415 ArrayMap<String, BasePermission> permissionMap = 8416 p.tree ? mSettings.mPermissionTrees 8417 : mSettings.mPermissions; 8418 BasePermission bp = permissionMap.get(p.info.name); 8419 8420 // Allow system apps to redefine non-system permissions 8421 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8422 final boolean currentOwnerIsSystem = (bp.perm != null 8423 && isSystemApp(bp.perm.owner)); 8424 if (isSystemApp(p.owner)) { 8425 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8426 // It's a built-in permission and no owner, take ownership now 8427 bp.packageSetting = pkgSetting; 8428 bp.perm = p; 8429 bp.uid = pkg.applicationInfo.uid; 8430 bp.sourcePackage = p.info.packageName; 8431 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8432 } else if (!currentOwnerIsSystem) { 8433 String msg = "New decl " + p.owner + " of permission " 8434 + p.info.name + " is system; overriding " + bp.sourcePackage; 8435 reportSettingsProblem(Log.WARN, msg); 8436 bp = null; 8437 } 8438 } 8439 } 8440 8441 if (bp == null) { 8442 bp = new BasePermission(p.info.name, p.info.packageName, 8443 BasePermission.TYPE_NORMAL); 8444 permissionMap.put(p.info.name, bp); 8445 } 8446 8447 if (bp.perm == null) { 8448 if (bp.sourcePackage == null 8449 || bp.sourcePackage.equals(p.info.packageName)) { 8450 BasePermission tree = findPermissionTreeLP(p.info.name); 8451 if (tree == null 8452 || tree.sourcePackage.equals(p.info.packageName)) { 8453 bp.packageSetting = pkgSetting; 8454 bp.perm = p; 8455 bp.uid = pkg.applicationInfo.uid; 8456 bp.sourcePackage = p.info.packageName; 8457 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8458 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8459 if (r == null) { 8460 r = new StringBuilder(256); 8461 } else { 8462 r.append(' '); 8463 } 8464 r.append(p.info.name); 8465 } 8466 } else { 8467 Slog.w(TAG, "Permission " + p.info.name + " from package " 8468 + p.info.packageName + " ignored: base tree " 8469 + tree.name + " is from package " 8470 + tree.sourcePackage); 8471 } 8472 } else { 8473 Slog.w(TAG, "Permission " + p.info.name + " from package " 8474 + p.info.packageName + " ignored: original from " 8475 + bp.sourcePackage); 8476 } 8477 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8478 if (r == null) { 8479 r = new StringBuilder(256); 8480 } else { 8481 r.append(' '); 8482 } 8483 r.append("DUP:"); 8484 r.append(p.info.name); 8485 } 8486 if (bp.perm == p) { 8487 bp.protectionLevel = p.info.protectionLevel; 8488 } 8489 } 8490 8491 if (r != null) { 8492 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 8493 } 8494 8495 N = pkg.instrumentation.size(); 8496 r = null; 8497 for (i=0; i<N; i++) { 8498 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8499 a.info.packageName = pkg.applicationInfo.packageName; 8500 a.info.sourceDir = pkg.applicationInfo.sourceDir; 8501 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 8502 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 8503 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 8504 a.info.dataDir = pkg.applicationInfo.dataDir; 8505 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 8506 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 8507 8508 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 8509 // need other information about the application, like the ABI and what not ? 8510 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 8511 mInstrumentation.put(a.getComponentName(), a); 8512 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8513 if (r == null) { 8514 r = new StringBuilder(256); 8515 } else { 8516 r.append(' '); 8517 } 8518 r.append(a.info.name); 8519 } 8520 } 8521 if (r != null) { 8522 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 8523 } 8524 8525 if (pkg.protectedBroadcasts != null) { 8526 N = pkg.protectedBroadcasts.size(); 8527 for (i=0; i<N; i++) { 8528 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 8529 } 8530 } 8531 8532 pkgSetting.setTimeStamp(scanFileTime); 8533 8534 // Create idmap files for pairs of (packages, overlay packages). 8535 // Note: "android", ie framework-res.apk, is handled by native layers. 8536 if (pkg.mOverlayTarget != null) { 8537 // This is an overlay package. 8538 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 8539 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 8540 mOverlays.put(pkg.mOverlayTarget, 8541 new ArrayMap<String, PackageParser.Package>()); 8542 } 8543 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 8544 map.put(pkg.packageName, pkg); 8545 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 8546 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 8547 createIdmapFailed = true; 8548 } 8549 } 8550 } else if (mOverlays.containsKey(pkg.packageName) && 8551 !pkg.packageName.equals("android")) { 8552 // This is a regular package, with one or more known overlay packages. 8553 createIdmapsForPackageLI(pkg); 8554 } 8555 } 8556 8557 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8558 8559 if (createIdmapFailed) { 8560 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8561 "scanPackageLI failed to createIdmap"); 8562 } 8563 return pkg; 8564 } 8565 8566 /** 8567 * Derive the ABI of a non-system package located at {@code scanFile}. This information 8568 * is derived purely on the basis of the contents of {@code scanFile} and 8569 * {@code cpuAbiOverride}. 8570 * 8571 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 8572 */ 8573 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 8574 String cpuAbiOverride, boolean extractLibs) 8575 throws PackageManagerException { 8576 // TODO: We can probably be smarter about this stuff. For installed apps, 8577 // we can calculate this information at install time once and for all. For 8578 // system apps, we can probably assume that this information doesn't change 8579 // after the first boot scan. As things stand, we do lots of unnecessary work. 8580 8581 // Give ourselves some initial paths; we'll come back for another 8582 // pass once we've determined ABI below. 8583 setNativeLibraryPaths(pkg); 8584 8585 // We would never need to extract libs for forward-locked and external packages, 8586 // since the container service will do it for us. We shouldn't attempt to 8587 // extract libs from system app when it was not updated. 8588 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 8589 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 8590 extractLibs = false; 8591 } 8592 8593 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 8594 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 8595 8596 NativeLibraryHelper.Handle handle = null; 8597 try { 8598 handle = NativeLibraryHelper.Handle.create(pkg); 8599 // TODO(multiArch): This can be null for apps that didn't go through the 8600 // usual installation process. We can calculate it again, like we 8601 // do during install time. 8602 // 8603 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 8604 // unnecessary. 8605 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 8606 8607 // Null out the abis so that they can be recalculated. 8608 pkg.applicationInfo.primaryCpuAbi = null; 8609 pkg.applicationInfo.secondaryCpuAbi = null; 8610 if (isMultiArch(pkg.applicationInfo)) { 8611 // Warn if we've set an abiOverride for multi-lib packages.. 8612 // By definition, we need to copy both 32 and 64 bit libraries for 8613 // such packages. 8614 if (pkg.cpuAbiOverride != null 8615 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 8616 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 8617 } 8618 8619 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 8620 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 8621 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 8622 if (extractLibs) { 8623 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8624 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 8625 useIsaSpecificSubdirs); 8626 } else { 8627 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 8628 } 8629 } 8630 8631 maybeThrowExceptionForMultiArchCopy( 8632 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 8633 8634 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 8635 if (extractLibs) { 8636 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8637 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 8638 useIsaSpecificSubdirs); 8639 } else { 8640 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 8641 } 8642 } 8643 8644 maybeThrowExceptionForMultiArchCopy( 8645 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 8646 8647 if (abi64 >= 0) { 8648 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 8649 } 8650 8651 if (abi32 >= 0) { 8652 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 8653 if (abi64 >= 0) { 8654 if (pkg.use32bitAbi) { 8655 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 8656 pkg.applicationInfo.primaryCpuAbi = abi; 8657 } else { 8658 pkg.applicationInfo.secondaryCpuAbi = abi; 8659 } 8660 } else { 8661 pkg.applicationInfo.primaryCpuAbi = abi; 8662 } 8663 } 8664 8665 } else { 8666 String[] abiList = (cpuAbiOverride != null) ? 8667 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 8668 8669 // Enable gross and lame hacks for apps that are built with old 8670 // SDK tools. We must scan their APKs for renderscript bitcode and 8671 // not launch them if it's present. Don't bother checking on devices 8672 // that don't have 64 bit support. 8673 boolean needsRenderScriptOverride = false; 8674 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 8675 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 8676 abiList = Build.SUPPORTED_32_BIT_ABIS; 8677 needsRenderScriptOverride = true; 8678 } 8679 8680 final int copyRet; 8681 if (extractLibs) { 8682 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8683 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 8684 } else { 8685 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 8686 } 8687 8688 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 8689 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 8690 "Error unpackaging native libs for app, errorCode=" + copyRet); 8691 } 8692 8693 if (copyRet >= 0) { 8694 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 8695 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 8696 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 8697 } else if (needsRenderScriptOverride) { 8698 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 8699 } 8700 } 8701 } catch (IOException ioe) { 8702 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 8703 } finally { 8704 IoUtils.closeQuietly(handle); 8705 } 8706 8707 // Now that we've calculated the ABIs and determined if it's an internal app, 8708 // we will go ahead and populate the nativeLibraryPath. 8709 setNativeLibraryPaths(pkg); 8710 } 8711 8712 /** 8713 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 8714 * i.e, so that all packages can be run inside a single process if required. 8715 * 8716 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 8717 * this function will either try and make the ABI for all packages in {@code packagesForUser} 8718 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 8719 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 8720 * updating a package that belongs to a shared user. 8721 * 8722 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 8723 * adds unnecessary complexity. 8724 */ 8725 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 8726 PackageParser.Package scannedPackage, boolean bootComplete) { 8727 String requiredInstructionSet = null; 8728 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 8729 requiredInstructionSet = VMRuntime.getInstructionSet( 8730 scannedPackage.applicationInfo.primaryCpuAbi); 8731 } 8732 8733 PackageSetting requirer = null; 8734 for (PackageSetting ps : packagesForUser) { 8735 // If packagesForUser contains scannedPackage, we skip it. This will happen 8736 // when scannedPackage is an update of an existing package. Without this check, 8737 // we will never be able to change the ABI of any package belonging to a shared 8738 // user, even if it's compatible with other packages. 8739 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8740 if (ps.primaryCpuAbiString == null) { 8741 continue; 8742 } 8743 8744 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 8745 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 8746 // We have a mismatch between instruction sets (say arm vs arm64) warn about 8747 // this but there's not much we can do. 8748 String errorMessage = "Instruction set mismatch, " 8749 + ((requirer == null) ? "[caller]" : requirer) 8750 + " requires " + requiredInstructionSet + " whereas " + ps 8751 + " requires " + instructionSet; 8752 Slog.w(TAG, errorMessage); 8753 } 8754 8755 if (requiredInstructionSet == null) { 8756 requiredInstructionSet = instructionSet; 8757 requirer = ps; 8758 } 8759 } 8760 } 8761 8762 if (requiredInstructionSet != null) { 8763 String adjustedAbi; 8764 if (requirer != null) { 8765 // requirer != null implies that either scannedPackage was null or that scannedPackage 8766 // did not require an ABI, in which case we have to adjust scannedPackage to match 8767 // the ABI of the set (which is the same as requirer's ABI) 8768 adjustedAbi = requirer.primaryCpuAbiString; 8769 if (scannedPackage != null) { 8770 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 8771 } 8772 } else { 8773 // requirer == null implies that we're updating all ABIs in the set to 8774 // match scannedPackage. 8775 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 8776 } 8777 8778 for (PackageSetting ps : packagesForUser) { 8779 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8780 if (ps.primaryCpuAbiString != null) { 8781 continue; 8782 } 8783 8784 ps.primaryCpuAbiString = adjustedAbi; 8785 if (ps.pkg != null && ps.pkg.applicationInfo != null && 8786 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 8787 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 8788 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 8789 + " (requirer=" 8790 + (requirer == null ? "null" : requirer.pkg.packageName) 8791 + ", scannedPackage=" 8792 + (scannedPackage != null ? scannedPackage.packageName : "null") 8793 + ")"); 8794 try { 8795 mInstaller.rmdex(ps.codePathString, 8796 getDexCodeInstructionSet(getPreferredInstructionSet())); 8797 } catch (InstallerException ignored) { 8798 } 8799 } 8800 } 8801 } 8802 } 8803 } 8804 8805 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 8806 synchronized (mPackages) { 8807 mResolverReplaced = true; 8808 // Set up information for custom user intent resolution activity. 8809 mResolveActivity.applicationInfo = pkg.applicationInfo; 8810 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 8811 mResolveActivity.packageName = pkg.applicationInfo.packageName; 8812 mResolveActivity.processName = pkg.applicationInfo.packageName; 8813 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8814 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8815 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8816 mResolveActivity.theme = 0; 8817 mResolveActivity.exported = true; 8818 mResolveActivity.enabled = true; 8819 mResolveInfo.activityInfo = mResolveActivity; 8820 mResolveInfo.priority = 0; 8821 mResolveInfo.preferredOrder = 0; 8822 mResolveInfo.match = 0; 8823 mResolveComponentName = mCustomResolverComponentName; 8824 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 8825 mResolveComponentName); 8826 } 8827 } 8828 8829 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 8830 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 8831 8832 // Set up information for ephemeral installer activity 8833 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 8834 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 8835 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 8836 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 8837 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8838 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8839 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8840 mEphemeralInstallerActivity.theme = 0; 8841 mEphemeralInstallerActivity.exported = true; 8842 mEphemeralInstallerActivity.enabled = true; 8843 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 8844 mEphemeralInstallerInfo.priority = 0; 8845 mEphemeralInstallerInfo.preferredOrder = 0; 8846 mEphemeralInstallerInfo.match = 0; 8847 8848 if (DEBUG_EPHEMERAL) { 8849 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 8850 } 8851 } 8852 8853 private static String calculateBundledApkRoot(final String codePathString) { 8854 final File codePath = new File(codePathString); 8855 final File codeRoot; 8856 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 8857 codeRoot = Environment.getRootDirectory(); 8858 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 8859 codeRoot = Environment.getOemDirectory(); 8860 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 8861 codeRoot = Environment.getVendorDirectory(); 8862 } else { 8863 // Unrecognized code path; take its top real segment as the apk root: 8864 // e.g. /something/app/blah.apk => /something 8865 try { 8866 File f = codePath.getCanonicalFile(); 8867 File parent = f.getParentFile(); // non-null because codePath is a file 8868 File tmp; 8869 while ((tmp = parent.getParentFile()) != null) { 8870 f = parent; 8871 parent = tmp; 8872 } 8873 codeRoot = f; 8874 Slog.w(TAG, "Unrecognized code path " 8875 + codePath + " - using " + codeRoot); 8876 } catch (IOException e) { 8877 // Can't canonicalize the code path -- shenanigans? 8878 Slog.w(TAG, "Can't canonicalize code path " + codePath); 8879 return Environment.getRootDirectory().getPath(); 8880 } 8881 } 8882 return codeRoot.getPath(); 8883 } 8884 8885 /** 8886 * Derive and set the location of native libraries for the given package, 8887 * which varies depending on where and how the package was installed. 8888 */ 8889 private void setNativeLibraryPaths(PackageParser.Package pkg) { 8890 final ApplicationInfo info = pkg.applicationInfo; 8891 final String codePath = pkg.codePath; 8892 final File codeFile = new File(codePath); 8893 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 8894 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 8895 8896 info.nativeLibraryRootDir = null; 8897 info.nativeLibraryRootRequiresIsa = false; 8898 info.nativeLibraryDir = null; 8899 info.secondaryNativeLibraryDir = null; 8900 8901 if (isApkFile(codeFile)) { 8902 // Monolithic install 8903 if (bundledApp) { 8904 // If "/system/lib64/apkname" exists, assume that is the per-package 8905 // native library directory to use; otherwise use "/system/lib/apkname". 8906 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 8907 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 8908 getPrimaryInstructionSet(info)); 8909 8910 // This is a bundled system app so choose the path based on the ABI. 8911 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 8912 // is just the default path. 8913 final String apkName = deriveCodePathName(codePath); 8914 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 8915 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 8916 apkName).getAbsolutePath(); 8917 8918 if (info.secondaryCpuAbi != null) { 8919 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 8920 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 8921 secondaryLibDir, apkName).getAbsolutePath(); 8922 } 8923 } else if (asecApp) { 8924 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 8925 .getAbsolutePath(); 8926 } else { 8927 final String apkName = deriveCodePathName(codePath); 8928 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 8929 .getAbsolutePath(); 8930 } 8931 8932 info.nativeLibraryRootRequiresIsa = false; 8933 info.nativeLibraryDir = info.nativeLibraryRootDir; 8934 } else { 8935 // Cluster install 8936 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 8937 info.nativeLibraryRootRequiresIsa = true; 8938 8939 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 8940 getPrimaryInstructionSet(info)).getAbsolutePath(); 8941 8942 if (info.secondaryCpuAbi != null) { 8943 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 8944 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 8945 } 8946 } 8947 } 8948 8949 /** 8950 * Calculate the abis and roots for a bundled app. These can uniquely 8951 * be determined from the contents of the system partition, i.e whether 8952 * it contains 64 or 32 bit shared libraries etc. We do not validate any 8953 * of this information, and instead assume that the system was built 8954 * sensibly. 8955 */ 8956 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 8957 PackageSetting pkgSetting) { 8958 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 8959 8960 // If "/system/lib64/apkname" exists, assume that is the per-package 8961 // native library directory to use; otherwise use "/system/lib/apkname". 8962 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 8963 setBundledAppAbi(pkg, apkRoot, apkName); 8964 // pkgSetting might be null during rescan following uninstall of updates 8965 // to a bundled app, so accommodate that possibility. The settings in 8966 // that case will be established later from the parsed package. 8967 // 8968 // If the settings aren't null, sync them up with what we've just derived. 8969 // note that apkRoot isn't stored in the package settings. 8970 if (pkgSetting != null) { 8971 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8972 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8973 } 8974 } 8975 8976 /** 8977 * Deduces the ABI of a bundled app and sets the relevant fields on the 8978 * parsed pkg object. 8979 * 8980 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 8981 * under which system libraries are installed. 8982 * @param apkName the name of the installed package. 8983 */ 8984 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 8985 final File codeFile = new File(pkg.codePath); 8986 8987 final boolean has64BitLibs; 8988 final boolean has32BitLibs; 8989 if (isApkFile(codeFile)) { 8990 // Monolithic install 8991 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 8992 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 8993 } else { 8994 // Cluster install 8995 final File rootDir = new File(codeFile, LIB_DIR_NAME); 8996 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 8997 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 8998 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 8999 has64BitLibs = (new File(rootDir, isa)).exists(); 9000 } else { 9001 has64BitLibs = false; 9002 } 9003 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 9004 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 9005 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 9006 has32BitLibs = (new File(rootDir, isa)).exists(); 9007 } else { 9008 has32BitLibs = false; 9009 } 9010 } 9011 9012 if (has64BitLibs && !has32BitLibs) { 9013 // The package has 64 bit libs, but not 32 bit libs. Its primary 9014 // ABI should be 64 bit. We can safely assume here that the bundled 9015 // native libraries correspond to the most preferred ABI in the list. 9016 9017 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9018 pkg.applicationInfo.secondaryCpuAbi = null; 9019 } else if (has32BitLibs && !has64BitLibs) { 9020 // The package has 32 bit libs but not 64 bit libs. Its primary 9021 // ABI should be 32 bit. 9022 9023 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9024 pkg.applicationInfo.secondaryCpuAbi = null; 9025 } else if (has32BitLibs && has64BitLibs) { 9026 // The application has both 64 and 32 bit bundled libraries. We check 9027 // here that the app declares multiArch support, and warn if it doesn't. 9028 // 9029 // We will be lenient here and record both ABIs. The primary will be the 9030 // ABI that's higher on the list, i.e, a device that's configured to prefer 9031 // 64 bit apps will see a 64 bit primary ABI, 9032 9033 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 9034 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 9035 } 9036 9037 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 9038 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9039 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9040 } else { 9041 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9042 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9043 } 9044 } else { 9045 pkg.applicationInfo.primaryCpuAbi = null; 9046 pkg.applicationInfo.secondaryCpuAbi = null; 9047 } 9048 } 9049 9050 private void killApplication(String pkgName, int appId, String reason) { 9051 // Request the ActivityManager to kill the process(only for existing packages) 9052 // so that we do not end up in a confused state while the user is still using the older 9053 // version of the application while the new one gets installed. 9054 final long token = Binder.clearCallingIdentity(); 9055 try { 9056 IActivityManager am = ActivityManagerNative.getDefault(); 9057 if (am != null) { 9058 try { 9059 am.killApplicationWithAppId(pkgName, appId, reason); 9060 } catch (RemoteException e) { 9061 } 9062 } 9063 } finally { 9064 Binder.restoreCallingIdentity(token); 9065 } 9066 } 9067 9068 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 9069 // Remove the parent package setting 9070 PackageSetting ps = (PackageSetting) pkg.mExtras; 9071 if (ps != null) { 9072 removePackageLI(ps, chatty); 9073 } 9074 // Remove the child package setting 9075 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9076 for (int i = 0; i < childCount; i++) { 9077 PackageParser.Package childPkg = pkg.childPackages.get(i); 9078 ps = (PackageSetting) childPkg.mExtras; 9079 if (ps != null) { 9080 removePackageLI(ps, chatty); 9081 } 9082 } 9083 } 9084 9085 void removePackageLI(PackageSetting ps, boolean chatty) { 9086 if (DEBUG_INSTALL) { 9087 if (chatty) 9088 Log.d(TAG, "Removing package " + ps.name); 9089 } 9090 9091 // writer 9092 synchronized (mPackages) { 9093 mPackages.remove(ps.name); 9094 final PackageParser.Package pkg = ps.pkg; 9095 if (pkg != null) { 9096 cleanPackageDataStructuresLILPw(pkg, chatty); 9097 } 9098 } 9099 } 9100 9101 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 9102 if (DEBUG_INSTALL) { 9103 if (chatty) 9104 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 9105 } 9106 9107 // writer 9108 synchronized (mPackages) { 9109 // Remove the parent package 9110 mPackages.remove(pkg.applicationInfo.packageName); 9111 cleanPackageDataStructuresLILPw(pkg, chatty); 9112 9113 // Remove the child packages 9114 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9115 for (int i = 0; i < childCount; i++) { 9116 PackageParser.Package childPkg = pkg.childPackages.get(i); 9117 mPackages.remove(childPkg.applicationInfo.packageName); 9118 cleanPackageDataStructuresLILPw(childPkg, chatty); 9119 } 9120 } 9121 } 9122 9123 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 9124 int N = pkg.providers.size(); 9125 StringBuilder r = null; 9126 int i; 9127 for (i=0; i<N; i++) { 9128 PackageParser.Provider p = pkg.providers.get(i); 9129 mProviders.removeProvider(p); 9130 if (p.info.authority == null) { 9131 9132 /* There was another ContentProvider with this authority when 9133 * this app was installed so this authority is null, 9134 * Ignore it as we don't have to unregister the provider. 9135 */ 9136 continue; 9137 } 9138 String names[] = p.info.authority.split(";"); 9139 for (int j = 0; j < names.length; j++) { 9140 if (mProvidersByAuthority.get(names[j]) == p) { 9141 mProvidersByAuthority.remove(names[j]); 9142 if (DEBUG_REMOVE) { 9143 if (chatty) 9144 Log.d(TAG, "Unregistered content provider: " + names[j] 9145 + ", className = " + p.info.name + ", isSyncable = " 9146 + p.info.isSyncable); 9147 } 9148 } 9149 } 9150 if (DEBUG_REMOVE && chatty) { 9151 if (r == null) { 9152 r = new StringBuilder(256); 9153 } else { 9154 r.append(' '); 9155 } 9156 r.append(p.info.name); 9157 } 9158 } 9159 if (r != null) { 9160 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 9161 } 9162 9163 N = pkg.services.size(); 9164 r = null; 9165 for (i=0; i<N; i++) { 9166 PackageParser.Service s = pkg.services.get(i); 9167 mServices.removeService(s); 9168 if (chatty) { 9169 if (r == null) { 9170 r = new StringBuilder(256); 9171 } else { 9172 r.append(' '); 9173 } 9174 r.append(s.info.name); 9175 } 9176 } 9177 if (r != null) { 9178 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 9179 } 9180 9181 N = pkg.receivers.size(); 9182 r = null; 9183 for (i=0; i<N; i++) { 9184 PackageParser.Activity a = pkg.receivers.get(i); 9185 mReceivers.removeActivity(a, "receiver"); 9186 if (DEBUG_REMOVE && chatty) { 9187 if (r == null) { 9188 r = new StringBuilder(256); 9189 } else { 9190 r.append(' '); 9191 } 9192 r.append(a.info.name); 9193 } 9194 } 9195 if (r != null) { 9196 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 9197 } 9198 9199 N = pkg.activities.size(); 9200 r = null; 9201 for (i=0; i<N; i++) { 9202 PackageParser.Activity a = pkg.activities.get(i); 9203 mActivities.removeActivity(a, "activity"); 9204 if (DEBUG_REMOVE && chatty) { 9205 if (r == null) { 9206 r = new StringBuilder(256); 9207 } else { 9208 r.append(' '); 9209 } 9210 r.append(a.info.name); 9211 } 9212 } 9213 if (r != null) { 9214 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 9215 } 9216 9217 N = pkg.permissions.size(); 9218 r = null; 9219 for (i=0; i<N; i++) { 9220 PackageParser.Permission p = pkg.permissions.get(i); 9221 BasePermission bp = mSettings.mPermissions.get(p.info.name); 9222 if (bp == null) { 9223 bp = mSettings.mPermissionTrees.get(p.info.name); 9224 } 9225 if (bp != null && bp.perm == p) { 9226 bp.perm = null; 9227 if (DEBUG_REMOVE && chatty) { 9228 if (r == null) { 9229 r = new StringBuilder(256); 9230 } else { 9231 r.append(' '); 9232 } 9233 r.append(p.info.name); 9234 } 9235 } 9236 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9237 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 9238 if (appOpPkgs != null) { 9239 appOpPkgs.remove(pkg.packageName); 9240 } 9241 } 9242 } 9243 if (r != null) { 9244 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9245 } 9246 9247 N = pkg.requestedPermissions.size(); 9248 r = null; 9249 for (i=0; i<N; i++) { 9250 String perm = pkg.requestedPermissions.get(i); 9251 BasePermission bp = mSettings.mPermissions.get(perm); 9252 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9253 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 9254 if (appOpPkgs != null) { 9255 appOpPkgs.remove(pkg.packageName); 9256 if (appOpPkgs.isEmpty()) { 9257 mAppOpPermissionPackages.remove(perm); 9258 } 9259 } 9260 } 9261 } 9262 if (r != null) { 9263 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9264 } 9265 9266 N = pkg.instrumentation.size(); 9267 r = null; 9268 for (i=0; i<N; i++) { 9269 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9270 mInstrumentation.remove(a.getComponentName()); 9271 if (DEBUG_REMOVE && chatty) { 9272 if (r == null) { 9273 r = new StringBuilder(256); 9274 } else { 9275 r.append(' '); 9276 } 9277 r.append(a.info.name); 9278 } 9279 } 9280 if (r != null) { 9281 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9282 } 9283 9284 r = null; 9285 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9286 // Only system apps can hold shared libraries. 9287 if (pkg.libraryNames != null) { 9288 for (i=0; i<pkg.libraryNames.size(); i++) { 9289 String name = pkg.libraryNames.get(i); 9290 SharedLibraryEntry cur = mSharedLibraries.get(name); 9291 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9292 mSharedLibraries.remove(name); 9293 if (DEBUG_REMOVE && chatty) { 9294 if (r == null) { 9295 r = new StringBuilder(256); 9296 } else { 9297 r.append(' '); 9298 } 9299 r.append(name); 9300 } 9301 } 9302 } 9303 } 9304 } 9305 if (r != null) { 9306 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9307 } 9308 } 9309 9310 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9311 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9312 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9313 return true; 9314 } 9315 } 9316 return false; 9317 } 9318 9319 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9320 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9321 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9322 9323 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9324 // Update the parent permissions 9325 updatePermissionsLPw(pkg.packageName, pkg, flags); 9326 // Update the child permissions 9327 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9328 for (int i = 0; i < childCount; i++) { 9329 PackageParser.Package childPkg = pkg.childPackages.get(i); 9330 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9331 } 9332 } 9333 9334 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9335 int flags) { 9336 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9337 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9338 } 9339 9340 private void updatePermissionsLPw(String changingPkg, 9341 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9342 // Make sure there are no dangling permission trees. 9343 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9344 while (it.hasNext()) { 9345 final BasePermission bp = it.next(); 9346 if (bp.packageSetting == null) { 9347 // We may not yet have parsed the package, so just see if 9348 // we still know about its settings. 9349 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9350 } 9351 if (bp.packageSetting == null) { 9352 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9353 + " from package " + bp.sourcePackage); 9354 it.remove(); 9355 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9356 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9357 Slog.i(TAG, "Removing old permission tree: " + bp.name 9358 + " from package " + bp.sourcePackage); 9359 flags |= UPDATE_PERMISSIONS_ALL; 9360 it.remove(); 9361 } 9362 } 9363 } 9364 9365 // Make sure all dynamic permissions have been assigned to a package, 9366 // and make sure there are no dangling permissions. 9367 it = mSettings.mPermissions.values().iterator(); 9368 while (it.hasNext()) { 9369 final BasePermission bp = it.next(); 9370 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9371 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9372 + bp.name + " pkg=" + bp.sourcePackage 9373 + " info=" + bp.pendingInfo); 9374 if (bp.packageSetting == null && bp.pendingInfo != null) { 9375 final BasePermission tree = findPermissionTreeLP(bp.name); 9376 if (tree != null && tree.perm != null) { 9377 bp.packageSetting = tree.packageSetting; 9378 bp.perm = new PackageParser.Permission(tree.perm.owner, 9379 new PermissionInfo(bp.pendingInfo)); 9380 bp.perm.info.packageName = tree.perm.info.packageName; 9381 bp.perm.info.name = bp.name; 9382 bp.uid = tree.uid; 9383 } 9384 } 9385 } 9386 if (bp.packageSetting == null) { 9387 // We may not yet have parsed the package, so just see if 9388 // we still know about its settings. 9389 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9390 } 9391 if (bp.packageSetting == null) { 9392 Slog.w(TAG, "Removing dangling permission: " + bp.name 9393 + " from package " + bp.sourcePackage); 9394 it.remove(); 9395 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9396 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9397 Slog.i(TAG, "Removing old permission: " + bp.name 9398 + " from package " + bp.sourcePackage); 9399 flags |= UPDATE_PERMISSIONS_ALL; 9400 it.remove(); 9401 } 9402 } 9403 } 9404 9405 // Now update the permissions for all packages, in particular 9406 // replace the granted permissions of the system packages. 9407 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9408 for (PackageParser.Package pkg : mPackages.values()) { 9409 if (pkg != pkgInfo) { 9410 // Only replace for packages on requested volume 9411 final String volumeUuid = getVolumeUuidForPackage(pkg); 9412 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9413 && Objects.equals(replaceVolumeUuid, volumeUuid); 9414 grantPermissionsLPw(pkg, replace, changingPkg); 9415 } 9416 } 9417 } 9418 9419 if (pkgInfo != null) { 9420 // Only replace for packages on requested volume 9421 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9422 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9423 && Objects.equals(replaceVolumeUuid, volumeUuid); 9424 grantPermissionsLPw(pkgInfo, replace, changingPkg); 9425 } 9426 } 9427 9428 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 9429 String packageOfInterest) { 9430 // IMPORTANT: There are two types of permissions: install and runtime. 9431 // Install time permissions are granted when the app is installed to 9432 // all device users and users added in the future. Runtime permissions 9433 // are granted at runtime explicitly to specific users. Normal and signature 9434 // protected permissions are install time permissions. Dangerous permissions 9435 // are install permissions if the app's target SDK is Lollipop MR1 or older, 9436 // otherwise they are runtime permissions. This function does not manage 9437 // runtime permissions except for the case an app targeting Lollipop MR1 9438 // being upgraded to target a newer SDK, in which case dangerous permissions 9439 // are transformed from install time to runtime ones. 9440 9441 final PackageSetting ps = (PackageSetting) pkg.mExtras; 9442 if (ps == null) { 9443 return; 9444 } 9445 9446 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 9447 9448 PermissionsState permissionsState = ps.getPermissionsState(); 9449 PermissionsState origPermissions = permissionsState; 9450 9451 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 9452 9453 boolean runtimePermissionsRevoked = false; 9454 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 9455 9456 boolean changedInstallPermission = false; 9457 9458 if (replace) { 9459 ps.installPermissionsFixed = false; 9460 if (!ps.isSharedUser()) { 9461 origPermissions = new PermissionsState(permissionsState); 9462 permissionsState.reset(); 9463 } else { 9464 // We need to know only about runtime permission changes since the 9465 // calling code always writes the install permissions state but 9466 // the runtime ones are written only if changed. The only cases of 9467 // changed runtime permissions here are promotion of an install to 9468 // runtime and revocation of a runtime from a shared user. 9469 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 9470 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 9471 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 9472 runtimePermissionsRevoked = true; 9473 } 9474 } 9475 } 9476 9477 permissionsState.setGlobalGids(mGlobalGids); 9478 9479 final int N = pkg.requestedPermissions.size(); 9480 for (int i=0; i<N; i++) { 9481 final String name = pkg.requestedPermissions.get(i); 9482 final BasePermission bp = mSettings.mPermissions.get(name); 9483 9484 if (DEBUG_INSTALL) { 9485 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 9486 } 9487 9488 if (bp == null || bp.packageSetting == null) { 9489 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9490 Slog.w(TAG, "Unknown permission " + name 9491 + " in package " + pkg.packageName); 9492 } 9493 continue; 9494 } 9495 9496 final String perm = bp.name; 9497 boolean allowedSig = false; 9498 int grant = GRANT_DENIED; 9499 9500 // Keep track of app op permissions. 9501 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9502 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 9503 if (pkgs == null) { 9504 pkgs = new ArraySet<>(); 9505 mAppOpPermissionPackages.put(bp.name, pkgs); 9506 } 9507 pkgs.add(pkg.packageName); 9508 } 9509 9510 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 9511 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 9512 >= Build.VERSION_CODES.M; 9513 switch (level) { 9514 case PermissionInfo.PROTECTION_NORMAL: { 9515 // For all apps normal permissions are install time ones. 9516 grant = GRANT_INSTALL; 9517 } break; 9518 9519 case PermissionInfo.PROTECTION_DANGEROUS: { 9520 // If a permission review is required for legacy apps we represent 9521 // their permissions as always granted runtime ones since we need 9522 // to keep the review required permission flag per user while an 9523 // install permission's state is shared across all users. 9524 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 9525 // For legacy apps dangerous permissions are install time ones. 9526 grant = GRANT_INSTALL; 9527 } else if (origPermissions.hasInstallPermission(bp.name)) { 9528 // For legacy apps that became modern, install becomes runtime. 9529 grant = GRANT_UPGRADE; 9530 } else if (mPromoteSystemApps 9531 && isSystemApp(ps) 9532 && mExistingSystemPackages.contains(ps.name)) { 9533 // For legacy system apps, install becomes runtime. 9534 // We cannot check hasInstallPermission() for system apps since those 9535 // permissions were granted implicitly and not persisted pre-M. 9536 grant = GRANT_UPGRADE; 9537 } else { 9538 // For modern apps keep runtime permissions unchanged. 9539 grant = GRANT_RUNTIME; 9540 } 9541 } break; 9542 9543 case PermissionInfo.PROTECTION_SIGNATURE: { 9544 // For all apps signature permissions are install time ones. 9545 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 9546 if (allowedSig) { 9547 grant = GRANT_INSTALL; 9548 } 9549 } break; 9550 } 9551 9552 if (DEBUG_INSTALL) { 9553 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 9554 } 9555 9556 if (grant != GRANT_DENIED) { 9557 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 9558 // If this is an existing, non-system package, then 9559 // we can't add any new permissions to it. 9560 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 9561 // Except... if this is a permission that was added 9562 // to the platform (note: need to only do this when 9563 // updating the platform). 9564 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 9565 grant = GRANT_DENIED; 9566 } 9567 } 9568 } 9569 9570 switch (grant) { 9571 case GRANT_INSTALL: { 9572 // Revoke this as runtime permission to handle the case of 9573 // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps 9574 for (int userId : UserManagerService.getInstance().getUserIds()) { 9575 if (origPermissions.getRuntimePermissionState( 9576 bp.name, userId) != null) { 9577 // Revoke the runtime permission and clear the flags. 9578 origPermissions.revokeRuntimePermission(bp, userId); 9579 origPermissions.updatePermissionFlags(bp, userId, 9580 PackageManager.MASK_PERMISSION_FLAGS, 0); 9581 // If we revoked a permission permission, we have to write. 9582 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9583 changedRuntimePermissionUserIds, userId); 9584 } 9585 } 9586 // Grant an install permission. 9587 if (permissionsState.grantInstallPermission(bp) != 9588 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9589 changedInstallPermission = true; 9590 } 9591 } break; 9592 9593 case GRANT_RUNTIME: { 9594 // Grant previously granted runtime permissions. 9595 for (int userId : UserManagerService.getInstance().getUserIds()) { 9596 PermissionState permissionState = origPermissions 9597 .getRuntimePermissionState(bp.name, userId); 9598 int flags = permissionState != null 9599 ? permissionState.getFlags() : 0; 9600 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 9601 if (permissionsState.grantRuntimePermission(bp, userId) == 9602 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9603 // If we cannot put the permission as it was, we have to write. 9604 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9605 changedRuntimePermissionUserIds, userId); 9606 } 9607 // If the app supports runtime permissions no need for a review. 9608 if (Build.PERMISSIONS_REVIEW_REQUIRED 9609 && appSupportsRuntimePermissions 9610 && (flags & PackageManager 9611 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 9612 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 9613 // Since we changed the flags, we have to write. 9614 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9615 changedRuntimePermissionUserIds, userId); 9616 } 9617 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 9618 && !appSupportsRuntimePermissions) { 9619 // For legacy apps that need a permission review, every new 9620 // runtime permission is granted but it is pending a review. 9621 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 9622 permissionsState.grantRuntimePermission(bp, userId); 9623 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 9624 // We changed the permission and flags, hence have to write. 9625 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9626 changedRuntimePermissionUserIds, userId); 9627 } 9628 } 9629 // Propagate the permission flags. 9630 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 9631 } 9632 } break; 9633 9634 case GRANT_UPGRADE: { 9635 // Grant runtime permissions for a previously held install permission. 9636 PermissionState permissionState = origPermissions 9637 .getInstallPermissionState(bp.name); 9638 final int flags = permissionState != null ? permissionState.getFlags() : 0; 9639 9640 if (origPermissions.revokeInstallPermission(bp) 9641 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 9642 // We will be transferring the permission flags, so clear them. 9643 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 9644 PackageManager.MASK_PERMISSION_FLAGS, 0); 9645 changedInstallPermission = true; 9646 } 9647 9648 // If the permission is not to be promoted to runtime we ignore it and 9649 // also its other flags as they are not applicable to install permissions. 9650 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 9651 for (int userId : currentUserIds) { 9652 if (permissionsState.grantRuntimePermission(bp, userId) != 9653 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9654 // Transfer the permission flags. 9655 permissionsState.updatePermissionFlags(bp, userId, 9656 flags, flags); 9657 // If we granted the permission, we have to write. 9658 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9659 changedRuntimePermissionUserIds, userId); 9660 } 9661 } 9662 } 9663 } break; 9664 9665 default: { 9666 if (packageOfInterest == null 9667 || packageOfInterest.equals(pkg.packageName)) { 9668 Slog.w(TAG, "Not granting permission " + perm 9669 + " to package " + pkg.packageName 9670 + " because it was previously installed without"); 9671 } 9672 } break; 9673 } 9674 } else { 9675 if (permissionsState.revokeInstallPermission(bp) != 9676 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9677 // Also drop the permission flags. 9678 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 9679 PackageManager.MASK_PERMISSION_FLAGS, 0); 9680 changedInstallPermission = true; 9681 Slog.i(TAG, "Un-granting permission " + perm 9682 + " from package " + pkg.packageName 9683 + " (protectionLevel=" + bp.protectionLevel 9684 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9685 + ")"); 9686 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 9687 // Don't print warning for app op permissions, since it is fine for them 9688 // not to be granted, there is a UI for the user to decide. 9689 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9690 Slog.w(TAG, "Not granting permission " + perm 9691 + " to package " + pkg.packageName 9692 + " (protectionLevel=" + bp.protectionLevel 9693 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9694 + ")"); 9695 } 9696 } 9697 } 9698 } 9699 9700 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 9701 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 9702 // This is the first that we have heard about this package, so the 9703 // permissions we have now selected are fixed until explicitly 9704 // changed. 9705 ps.installPermissionsFixed = true; 9706 } 9707 9708 // Persist the runtime permissions state for users with changes. If permissions 9709 // were revoked because no app in the shared user declares them we have to 9710 // write synchronously to avoid losing runtime permissions state. 9711 for (int userId : changedRuntimePermissionUserIds) { 9712 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 9713 } 9714 9715 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9716 } 9717 9718 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 9719 boolean allowed = false; 9720 final int NP = PackageParser.NEW_PERMISSIONS.length; 9721 for (int ip=0; ip<NP; ip++) { 9722 final PackageParser.NewPermissionInfo npi 9723 = PackageParser.NEW_PERMISSIONS[ip]; 9724 if (npi.name.equals(perm) 9725 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 9726 allowed = true; 9727 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 9728 + pkg.packageName); 9729 break; 9730 } 9731 } 9732 return allowed; 9733 } 9734 9735 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 9736 BasePermission bp, PermissionsState origPermissions) { 9737 boolean allowed; 9738 allowed = (compareSignatures( 9739 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 9740 == PackageManager.SIGNATURE_MATCH) 9741 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 9742 == PackageManager.SIGNATURE_MATCH); 9743 if (!allowed && (bp.protectionLevel 9744 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 9745 if (isSystemApp(pkg)) { 9746 // For updated system applications, a system permission 9747 // is granted only if it had been defined by the original application. 9748 if (pkg.isUpdatedSystemApp()) { 9749 final PackageSetting sysPs = mSettings 9750 .getDisabledSystemPkgLPr(pkg.packageName); 9751 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 9752 // If the original was granted this permission, we take 9753 // that grant decision as read and propagate it to the 9754 // update. 9755 if (sysPs.isPrivileged()) { 9756 allowed = true; 9757 } 9758 } else { 9759 // The system apk may have been updated with an older 9760 // version of the one on the data partition, but which 9761 // granted a new system permission that it didn't have 9762 // before. In this case we do want to allow the app to 9763 // now get the new permission if the ancestral apk is 9764 // privileged to get it. 9765 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 9766 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 9767 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 9768 allowed = true; 9769 break; 9770 } 9771 } 9772 } 9773 // Also if a privileged parent package on the system image or any of 9774 // its children requested a privileged permission, the updated child 9775 // packages can also get the permission. 9776 if (pkg.parentPackage != null) { 9777 final PackageSetting disabledSysParentPs = mSettings 9778 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 9779 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 9780 && disabledSysParentPs.isPrivileged()) { 9781 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 9782 allowed = true; 9783 } else if (disabledSysParentPs.pkg.childPackages != null) { 9784 final int count = disabledSysParentPs.pkg.childPackages.size(); 9785 for (int i = 0; i < count; i++) { 9786 PackageParser.Package disabledSysChildPkg = 9787 disabledSysParentPs.pkg.childPackages.get(i); 9788 if (isPackageRequestingPermission(disabledSysChildPkg, 9789 perm)) { 9790 allowed = true; 9791 break; 9792 } 9793 } 9794 } 9795 } 9796 } 9797 } 9798 } else { 9799 allowed = isPrivilegedApp(pkg); 9800 } 9801 } 9802 } 9803 if (!allowed) { 9804 if (!allowed && (bp.protectionLevel 9805 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 9806 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 9807 // If this was a previously normal/dangerous permission that got moved 9808 // to a system permission as part of the runtime permission redesign, then 9809 // we still want to blindly grant it to old apps. 9810 allowed = true; 9811 } 9812 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 9813 && pkg.packageName.equals(mRequiredInstallerPackage)) { 9814 // If this permission is to be granted to the system installer and 9815 // this app is an installer, then it gets the permission. 9816 allowed = true; 9817 } 9818 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 9819 && pkg.packageName.equals(mRequiredVerifierPackage)) { 9820 // If this permission is to be granted to the system verifier and 9821 // this app is a verifier, then it gets the permission. 9822 allowed = true; 9823 } 9824 if (!allowed && (bp.protectionLevel 9825 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 9826 && isSystemApp(pkg)) { 9827 // Any pre-installed system app is allowed to get this permission. 9828 allowed = true; 9829 } 9830 if (!allowed && (bp.protectionLevel 9831 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 9832 // For development permissions, a development permission 9833 // is granted only if it was already granted. 9834 allowed = origPermissions.hasInstallPermission(perm); 9835 } 9836 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 9837 && pkg.packageName.equals(mSetupWizardPackage)) { 9838 // If this permission is to be granted to the system setup wizard and 9839 // this app is a setup wizard, then it gets the permission. 9840 allowed = true; 9841 } 9842 } 9843 return allowed; 9844 } 9845 9846 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 9847 final int permCount = pkg.requestedPermissions.size(); 9848 for (int j = 0; j < permCount; j++) { 9849 String requestedPermission = pkg.requestedPermissions.get(j); 9850 if (permission.equals(requestedPermission)) { 9851 return true; 9852 } 9853 } 9854 return false; 9855 } 9856 9857 final class ActivityIntentResolver 9858 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 9859 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9860 boolean defaultOnly, int userId) { 9861 if (!sUserManager.exists(userId)) return null; 9862 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9863 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9864 } 9865 9866 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9867 int userId) { 9868 if (!sUserManager.exists(userId)) return null; 9869 mFlags = flags; 9870 return super.queryIntent(intent, resolvedType, 9871 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9872 } 9873 9874 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9875 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 9876 if (!sUserManager.exists(userId)) return null; 9877 if (packageActivities == null) { 9878 return null; 9879 } 9880 mFlags = flags; 9881 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9882 final int N = packageActivities.size(); 9883 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 9884 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 9885 9886 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 9887 for (int i = 0; i < N; ++i) { 9888 intentFilters = packageActivities.get(i).intents; 9889 if (intentFilters != null && intentFilters.size() > 0) { 9890 PackageParser.ActivityIntentInfo[] array = 9891 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 9892 intentFilters.toArray(array); 9893 listCut.add(array); 9894 } 9895 } 9896 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9897 } 9898 9899 /** 9900 * Finds a privileged activity that matches the specified activity names. 9901 */ 9902 private PackageParser.Activity findMatchingActivity( 9903 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 9904 for (PackageParser.Activity sysActivity : activityList) { 9905 if (sysActivity.info.name.equals(activityInfo.name)) { 9906 return sysActivity; 9907 } 9908 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 9909 return sysActivity; 9910 } 9911 if (sysActivity.info.targetActivity != null) { 9912 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 9913 return sysActivity; 9914 } 9915 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 9916 return sysActivity; 9917 } 9918 } 9919 } 9920 return null; 9921 } 9922 9923 public class IterGenerator<E> { 9924 public Iterator<E> generate(ActivityIntentInfo info) { 9925 return null; 9926 } 9927 } 9928 9929 public class ActionIterGenerator extends IterGenerator<String> { 9930 @Override 9931 public Iterator<String> generate(ActivityIntentInfo info) { 9932 return info.actionsIterator(); 9933 } 9934 } 9935 9936 public class CategoriesIterGenerator extends IterGenerator<String> { 9937 @Override 9938 public Iterator<String> generate(ActivityIntentInfo info) { 9939 return info.categoriesIterator(); 9940 } 9941 } 9942 9943 public class SchemesIterGenerator extends IterGenerator<String> { 9944 @Override 9945 public Iterator<String> generate(ActivityIntentInfo info) { 9946 return info.schemesIterator(); 9947 } 9948 } 9949 9950 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 9951 @Override 9952 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 9953 return info.authoritiesIterator(); 9954 } 9955 } 9956 9957 /** 9958 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 9959 * MODIFIED. Do not pass in a list that should not be changed. 9960 */ 9961 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 9962 IterGenerator<T> generator, Iterator<T> searchIterator) { 9963 // loop through the set of actions; every one must be found in the intent filter 9964 while (searchIterator.hasNext()) { 9965 // we must have at least one filter in the list to consider a match 9966 if (intentList.size() == 0) { 9967 break; 9968 } 9969 9970 final T searchAction = searchIterator.next(); 9971 9972 // loop through the set of intent filters 9973 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 9974 while (intentIter.hasNext()) { 9975 final ActivityIntentInfo intentInfo = intentIter.next(); 9976 boolean selectionFound = false; 9977 9978 // loop through the intent filter's selection criteria; at least one 9979 // of them must match the searched criteria 9980 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 9981 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 9982 final T intentSelection = intentSelectionIter.next(); 9983 if (intentSelection != null && intentSelection.equals(searchAction)) { 9984 selectionFound = true; 9985 break; 9986 } 9987 } 9988 9989 // the selection criteria wasn't found in this filter's set; this filter 9990 // is not a potential match 9991 if (!selectionFound) { 9992 intentIter.remove(); 9993 } 9994 } 9995 } 9996 } 9997 9998 private boolean isProtectedAction(ActivityIntentInfo filter) { 9999 final Iterator<String> actionsIter = filter.actionsIterator(); 10000 while (actionsIter != null && actionsIter.hasNext()) { 10001 final String filterAction = actionsIter.next(); 10002 if (PROTECTED_ACTIONS.contains(filterAction)) { 10003 return true; 10004 } 10005 } 10006 return false; 10007 } 10008 10009 /** 10010 * Adjusts the priority of the given intent filter according to policy. 10011 * <p> 10012 * <ul> 10013 * <li>The priority for non privileged applications is capped to '0'</li> 10014 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 10015 * <li>The priority for unbundled updates to privileged applications is capped to the 10016 * priority defined on the system partition</li> 10017 * </ul> 10018 * <p> 10019 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 10020 * allowed to obtain any priority on any action. 10021 */ 10022 private void adjustPriority( 10023 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 10024 // nothing to do; priority is fine as-is 10025 if (intent.getPriority() <= 0) { 10026 return; 10027 } 10028 10029 final ActivityInfo activityInfo = intent.activity.info; 10030 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 10031 10032 final boolean privilegedApp = 10033 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 10034 if (!privilegedApp) { 10035 // non-privileged applications can never define a priority >0 10036 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 10037 + " package: " + applicationInfo.packageName 10038 + " activity: " + intent.activity.className 10039 + " origPrio: " + intent.getPriority()); 10040 intent.setPriority(0); 10041 return; 10042 } 10043 10044 if (systemActivities == null) { 10045 // the system package is not disabled; we're parsing the system partition 10046 if (isProtectedAction(intent)) { 10047 if (mDeferProtectedFilters) { 10048 // We can't deal with these just yet. No component should ever obtain a 10049 // >0 priority for a protected actions, with ONE exception -- the setup 10050 // wizard. The setup wizard, however, cannot be known until we're able to 10051 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 10052 // until all intent filters have been processed. Chicken, meet egg. 10053 // Let the filter temporarily have a high priority and rectify the 10054 // priorities after all system packages have been scanned. 10055 mProtectedFilters.add(intent); 10056 if (DEBUG_FILTERS) { 10057 Slog.i(TAG, "Protected action; save for later;" 10058 + " package: " + applicationInfo.packageName 10059 + " activity: " + intent.activity.className 10060 + " origPrio: " + intent.getPriority()); 10061 } 10062 return; 10063 } else { 10064 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 10065 Slog.i(TAG, "No setup wizard;" 10066 + " All protected intents capped to priority 0"); 10067 } 10068 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 10069 if (DEBUG_FILTERS) { 10070 Slog.i(TAG, "Found setup wizard;" 10071 + " allow priority " + intent.getPriority() + ";" 10072 + " package: " + intent.activity.info.packageName 10073 + " activity: " + intent.activity.className 10074 + " priority: " + intent.getPriority()); 10075 } 10076 // setup wizard gets whatever it wants 10077 return; 10078 } 10079 Slog.w(TAG, "Protected action; cap priority to 0;" 10080 + " package: " + intent.activity.info.packageName 10081 + " activity: " + intent.activity.className 10082 + " origPrio: " + intent.getPriority()); 10083 intent.setPriority(0); 10084 return; 10085 } 10086 } 10087 // privileged apps on the system image get whatever priority they request 10088 return; 10089 } 10090 10091 // privileged app unbundled update ... try to find the same activity 10092 final PackageParser.Activity foundActivity = 10093 findMatchingActivity(systemActivities, activityInfo); 10094 if (foundActivity == null) { 10095 // this is a new activity; it cannot obtain >0 priority 10096 if (DEBUG_FILTERS) { 10097 Slog.i(TAG, "New activity; cap priority to 0;" 10098 + " package: " + applicationInfo.packageName 10099 + " activity: " + intent.activity.className 10100 + " origPrio: " + intent.getPriority()); 10101 } 10102 intent.setPriority(0); 10103 return; 10104 } 10105 10106 // found activity, now check for filter equivalence 10107 10108 // a shallow copy is enough; we modify the list, not its contents 10109 final List<ActivityIntentInfo> intentListCopy = 10110 new ArrayList<>(foundActivity.intents); 10111 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 10112 10113 // find matching action subsets 10114 final Iterator<String> actionsIterator = intent.actionsIterator(); 10115 if (actionsIterator != null) { 10116 getIntentListSubset( 10117 intentListCopy, new ActionIterGenerator(), actionsIterator); 10118 if (intentListCopy.size() == 0) { 10119 // no more intents to match; we're not equivalent 10120 if (DEBUG_FILTERS) { 10121 Slog.i(TAG, "Mismatched action; cap priority to 0;" 10122 + " package: " + applicationInfo.packageName 10123 + " activity: " + intent.activity.className 10124 + " origPrio: " + intent.getPriority()); 10125 } 10126 intent.setPriority(0); 10127 return; 10128 } 10129 } 10130 10131 // find matching category subsets 10132 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 10133 if (categoriesIterator != null) { 10134 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 10135 categoriesIterator); 10136 if (intentListCopy.size() == 0) { 10137 // no more intents to match; we're not equivalent 10138 if (DEBUG_FILTERS) { 10139 Slog.i(TAG, "Mismatched category; cap priority to 0;" 10140 + " package: " + applicationInfo.packageName 10141 + " activity: " + intent.activity.className 10142 + " origPrio: " + intent.getPriority()); 10143 } 10144 intent.setPriority(0); 10145 return; 10146 } 10147 } 10148 10149 // find matching schemes subsets 10150 final Iterator<String> schemesIterator = intent.schemesIterator(); 10151 if (schemesIterator != null) { 10152 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 10153 schemesIterator); 10154 if (intentListCopy.size() == 0) { 10155 // no more intents to match; we're not equivalent 10156 if (DEBUG_FILTERS) { 10157 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 10158 + " package: " + applicationInfo.packageName 10159 + " activity: " + intent.activity.className 10160 + " origPrio: " + intent.getPriority()); 10161 } 10162 intent.setPriority(0); 10163 return; 10164 } 10165 } 10166 10167 // find matching authorities subsets 10168 final Iterator<IntentFilter.AuthorityEntry> 10169 authoritiesIterator = intent.authoritiesIterator(); 10170 if (authoritiesIterator != null) { 10171 getIntentListSubset(intentListCopy, 10172 new AuthoritiesIterGenerator(), 10173 authoritiesIterator); 10174 if (intentListCopy.size() == 0) { 10175 // no more intents to match; we're not equivalent 10176 if (DEBUG_FILTERS) { 10177 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 10178 + " package: " + applicationInfo.packageName 10179 + " activity: " + intent.activity.className 10180 + " origPrio: " + intent.getPriority()); 10181 } 10182 intent.setPriority(0); 10183 return; 10184 } 10185 } 10186 10187 // we found matching filter(s); app gets the max priority of all intents 10188 int cappedPriority = 0; 10189 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 10190 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 10191 } 10192 if (intent.getPriority() > cappedPriority) { 10193 if (DEBUG_FILTERS) { 10194 Slog.i(TAG, "Found matching filter(s);" 10195 + " cap priority to " + cappedPriority + ";" 10196 + " package: " + applicationInfo.packageName 10197 + " activity: " + intent.activity.className 10198 + " origPrio: " + intent.getPriority()); 10199 } 10200 intent.setPriority(cappedPriority); 10201 return; 10202 } 10203 // all this for nothing; the requested priority was <= what was on the system 10204 } 10205 10206 public final void addActivity(PackageParser.Activity a, String type) { 10207 mActivities.put(a.getComponentName(), a); 10208 if (DEBUG_SHOW_INFO) 10209 Log.v( 10210 TAG, " " + type + " " + 10211 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 10212 if (DEBUG_SHOW_INFO) 10213 Log.v(TAG, " Class=" + a.info.name); 10214 final int NI = a.intents.size(); 10215 for (int j=0; j<NI; j++) { 10216 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10217 if ("activity".equals(type)) { 10218 final PackageSetting ps = 10219 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 10220 final List<PackageParser.Activity> systemActivities = 10221 ps != null && ps.pkg != null ? ps.pkg.activities : null; 10222 adjustPriority(systemActivities, intent); 10223 } 10224 if (DEBUG_SHOW_INFO) { 10225 Log.v(TAG, " IntentFilter:"); 10226 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10227 } 10228 if (!intent.debugCheck()) { 10229 Log.w(TAG, "==> For Activity " + a.info.name); 10230 } 10231 addFilter(intent); 10232 } 10233 } 10234 10235 public final void removeActivity(PackageParser.Activity a, String type) { 10236 mActivities.remove(a.getComponentName()); 10237 if (DEBUG_SHOW_INFO) { 10238 Log.v(TAG, " " + type + " " 10239 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 10240 : a.info.name) + ":"); 10241 Log.v(TAG, " Class=" + a.info.name); 10242 } 10243 final int NI = a.intents.size(); 10244 for (int j=0; j<NI; j++) { 10245 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10246 if (DEBUG_SHOW_INFO) { 10247 Log.v(TAG, " IntentFilter:"); 10248 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10249 } 10250 removeFilter(intent); 10251 } 10252 } 10253 10254 @Override 10255 protected boolean allowFilterResult( 10256 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 10257 ActivityInfo filterAi = filter.activity.info; 10258 for (int i=dest.size()-1; i>=0; i--) { 10259 ActivityInfo destAi = dest.get(i).activityInfo; 10260 if (destAi.name == filterAi.name 10261 && destAi.packageName == filterAi.packageName) { 10262 return false; 10263 } 10264 } 10265 return true; 10266 } 10267 10268 @Override 10269 protected ActivityIntentInfo[] newArray(int size) { 10270 return new ActivityIntentInfo[size]; 10271 } 10272 10273 @Override 10274 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 10275 if (!sUserManager.exists(userId)) return true; 10276 PackageParser.Package p = filter.activity.owner; 10277 if (p != null) { 10278 PackageSetting ps = (PackageSetting)p.mExtras; 10279 if (ps != null) { 10280 // System apps are never considered stopped for purposes of 10281 // filtering, because there may be no way for the user to 10282 // actually re-launch them. 10283 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 10284 && ps.getStopped(userId); 10285 } 10286 } 10287 return false; 10288 } 10289 10290 @Override 10291 protected boolean isPackageForFilter(String packageName, 10292 PackageParser.ActivityIntentInfo info) { 10293 return packageName.equals(info.activity.owner.packageName); 10294 } 10295 10296 @Override 10297 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 10298 int match, int userId) { 10299 if (!sUserManager.exists(userId)) return null; 10300 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 10301 return null; 10302 } 10303 final PackageParser.Activity activity = info.activity; 10304 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 10305 if (ps == null) { 10306 return null; 10307 } 10308 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 10309 ps.readUserState(userId), userId); 10310 if (ai == null) { 10311 return null; 10312 } 10313 final ResolveInfo res = new ResolveInfo(); 10314 res.activityInfo = ai; 10315 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10316 res.filter = info; 10317 } 10318 if (info != null) { 10319 res.handleAllWebDataURI = info.handleAllWebDataURI(); 10320 } 10321 res.priority = info.getPriority(); 10322 res.preferredOrder = activity.owner.mPreferredOrder; 10323 //System.out.println("Result: " + res.activityInfo.className + 10324 // " = " + res.priority); 10325 res.match = match; 10326 res.isDefault = info.hasDefault; 10327 res.labelRes = info.labelRes; 10328 res.nonLocalizedLabel = info.nonLocalizedLabel; 10329 if (userNeedsBadging(userId)) { 10330 res.noResourceId = true; 10331 } else { 10332 res.icon = info.icon; 10333 } 10334 res.iconResourceId = info.icon; 10335 res.system = res.activityInfo.applicationInfo.isSystemApp(); 10336 return res; 10337 } 10338 10339 @Override 10340 protected void sortResults(List<ResolveInfo> results) { 10341 Collections.sort(results, mResolvePrioritySorter); 10342 } 10343 10344 @Override 10345 protected void dumpFilter(PrintWriter out, String prefix, 10346 PackageParser.ActivityIntentInfo filter) { 10347 out.print(prefix); out.print( 10348 Integer.toHexString(System.identityHashCode(filter.activity))); 10349 out.print(' '); 10350 filter.activity.printComponentShortName(out); 10351 out.print(" filter "); 10352 out.println(Integer.toHexString(System.identityHashCode(filter))); 10353 } 10354 10355 @Override 10356 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 10357 return filter.activity; 10358 } 10359 10360 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10361 PackageParser.Activity activity = (PackageParser.Activity)label; 10362 out.print(prefix); out.print( 10363 Integer.toHexString(System.identityHashCode(activity))); 10364 out.print(' '); 10365 activity.printComponentShortName(out); 10366 if (count > 1) { 10367 out.print(" ("); out.print(count); out.print(" filters)"); 10368 } 10369 out.println(); 10370 } 10371 10372 // Keys are String (activity class name), values are Activity. 10373 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 10374 = new ArrayMap<ComponentName, PackageParser.Activity>(); 10375 private int mFlags; 10376 } 10377 10378 private final class ServiceIntentResolver 10379 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 10380 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10381 boolean defaultOnly, int userId) { 10382 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10383 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10384 } 10385 10386 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10387 int userId) { 10388 if (!sUserManager.exists(userId)) return null; 10389 mFlags = flags; 10390 return super.queryIntent(intent, resolvedType, 10391 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10392 } 10393 10394 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10395 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 10396 if (!sUserManager.exists(userId)) return null; 10397 if (packageServices == null) { 10398 return null; 10399 } 10400 mFlags = flags; 10401 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10402 final int N = packageServices.size(); 10403 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 10404 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 10405 10406 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 10407 for (int i = 0; i < N; ++i) { 10408 intentFilters = packageServices.get(i).intents; 10409 if (intentFilters != null && intentFilters.size() > 0) { 10410 PackageParser.ServiceIntentInfo[] array = 10411 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 10412 intentFilters.toArray(array); 10413 listCut.add(array); 10414 } 10415 } 10416 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10417 } 10418 10419 public final void addService(PackageParser.Service s) { 10420 mServices.put(s.getComponentName(), s); 10421 if (DEBUG_SHOW_INFO) { 10422 Log.v(TAG, " " 10423 + (s.info.nonLocalizedLabel != null 10424 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10425 Log.v(TAG, " Class=" + s.info.name); 10426 } 10427 final int NI = s.intents.size(); 10428 int j; 10429 for (j=0; j<NI; j++) { 10430 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10431 if (DEBUG_SHOW_INFO) { 10432 Log.v(TAG, " IntentFilter:"); 10433 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10434 } 10435 if (!intent.debugCheck()) { 10436 Log.w(TAG, "==> For Service " + s.info.name); 10437 } 10438 addFilter(intent); 10439 } 10440 } 10441 10442 public final void removeService(PackageParser.Service s) { 10443 mServices.remove(s.getComponentName()); 10444 if (DEBUG_SHOW_INFO) { 10445 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 10446 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10447 Log.v(TAG, " Class=" + s.info.name); 10448 } 10449 final int NI = s.intents.size(); 10450 int j; 10451 for (j=0; j<NI; j++) { 10452 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10453 if (DEBUG_SHOW_INFO) { 10454 Log.v(TAG, " IntentFilter:"); 10455 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10456 } 10457 removeFilter(intent); 10458 } 10459 } 10460 10461 @Override 10462 protected boolean allowFilterResult( 10463 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 10464 ServiceInfo filterSi = filter.service.info; 10465 for (int i=dest.size()-1; i>=0; i--) { 10466 ServiceInfo destAi = dest.get(i).serviceInfo; 10467 if (destAi.name == filterSi.name 10468 && destAi.packageName == filterSi.packageName) { 10469 return false; 10470 } 10471 } 10472 return true; 10473 } 10474 10475 @Override 10476 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 10477 return new PackageParser.ServiceIntentInfo[size]; 10478 } 10479 10480 @Override 10481 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 10482 if (!sUserManager.exists(userId)) return true; 10483 PackageParser.Package p = filter.service.owner; 10484 if (p != null) { 10485 PackageSetting ps = (PackageSetting)p.mExtras; 10486 if (ps != null) { 10487 // System apps are never considered stopped for purposes of 10488 // filtering, because there may be no way for the user to 10489 // actually re-launch them. 10490 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10491 && ps.getStopped(userId); 10492 } 10493 } 10494 return false; 10495 } 10496 10497 @Override 10498 protected boolean isPackageForFilter(String packageName, 10499 PackageParser.ServiceIntentInfo info) { 10500 return packageName.equals(info.service.owner.packageName); 10501 } 10502 10503 @Override 10504 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 10505 int match, int userId) { 10506 if (!sUserManager.exists(userId)) return null; 10507 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 10508 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 10509 return null; 10510 } 10511 final PackageParser.Service service = info.service; 10512 PackageSetting ps = (PackageSetting) service.owner.mExtras; 10513 if (ps == null) { 10514 return null; 10515 } 10516 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 10517 ps.readUserState(userId), userId); 10518 if (si == null) { 10519 return null; 10520 } 10521 final ResolveInfo res = new ResolveInfo(); 10522 res.serviceInfo = si; 10523 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10524 res.filter = filter; 10525 } 10526 res.priority = info.getPriority(); 10527 res.preferredOrder = service.owner.mPreferredOrder; 10528 res.match = match; 10529 res.isDefault = info.hasDefault; 10530 res.labelRes = info.labelRes; 10531 res.nonLocalizedLabel = info.nonLocalizedLabel; 10532 res.icon = info.icon; 10533 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 10534 return res; 10535 } 10536 10537 @Override 10538 protected void sortResults(List<ResolveInfo> results) { 10539 Collections.sort(results, mResolvePrioritySorter); 10540 } 10541 10542 @Override 10543 protected void dumpFilter(PrintWriter out, String prefix, 10544 PackageParser.ServiceIntentInfo filter) { 10545 out.print(prefix); out.print( 10546 Integer.toHexString(System.identityHashCode(filter.service))); 10547 out.print(' '); 10548 filter.service.printComponentShortName(out); 10549 out.print(" filter "); 10550 out.println(Integer.toHexString(System.identityHashCode(filter))); 10551 } 10552 10553 @Override 10554 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 10555 return filter.service; 10556 } 10557 10558 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10559 PackageParser.Service service = (PackageParser.Service)label; 10560 out.print(prefix); out.print( 10561 Integer.toHexString(System.identityHashCode(service))); 10562 out.print(' '); 10563 service.printComponentShortName(out); 10564 if (count > 1) { 10565 out.print(" ("); out.print(count); out.print(" filters)"); 10566 } 10567 out.println(); 10568 } 10569 10570// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 10571// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 10572// final List<ResolveInfo> retList = Lists.newArrayList(); 10573// while (i.hasNext()) { 10574// final ResolveInfo resolveInfo = (ResolveInfo) i; 10575// if (isEnabledLP(resolveInfo.serviceInfo)) { 10576// retList.add(resolveInfo); 10577// } 10578// } 10579// return retList; 10580// } 10581 10582 // Keys are String (activity class name), values are Activity. 10583 private final ArrayMap<ComponentName, PackageParser.Service> mServices 10584 = new ArrayMap<ComponentName, PackageParser.Service>(); 10585 private int mFlags; 10586 }; 10587 10588 private final class ProviderIntentResolver 10589 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 10590 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10591 boolean defaultOnly, int userId) { 10592 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10593 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10594 } 10595 10596 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10597 int userId) { 10598 if (!sUserManager.exists(userId)) 10599 return null; 10600 mFlags = flags; 10601 return super.queryIntent(intent, resolvedType, 10602 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10603 } 10604 10605 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10606 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 10607 if (!sUserManager.exists(userId)) 10608 return null; 10609 if (packageProviders == null) { 10610 return null; 10611 } 10612 mFlags = flags; 10613 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 10614 final int N = packageProviders.size(); 10615 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 10616 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 10617 10618 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 10619 for (int i = 0; i < N; ++i) { 10620 intentFilters = packageProviders.get(i).intents; 10621 if (intentFilters != null && intentFilters.size() > 0) { 10622 PackageParser.ProviderIntentInfo[] array = 10623 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 10624 intentFilters.toArray(array); 10625 listCut.add(array); 10626 } 10627 } 10628 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10629 } 10630 10631 public final void addProvider(PackageParser.Provider p) { 10632 if (mProviders.containsKey(p.getComponentName())) { 10633 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 10634 return; 10635 } 10636 10637 mProviders.put(p.getComponentName(), p); 10638 if (DEBUG_SHOW_INFO) { 10639 Log.v(TAG, " " 10640 + (p.info.nonLocalizedLabel != null 10641 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10642 Log.v(TAG, " Class=" + p.info.name); 10643 } 10644 final int NI = p.intents.size(); 10645 int j; 10646 for (j = 0; j < NI; j++) { 10647 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10648 if (DEBUG_SHOW_INFO) { 10649 Log.v(TAG, " IntentFilter:"); 10650 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10651 } 10652 if (!intent.debugCheck()) { 10653 Log.w(TAG, "==> For Provider " + p.info.name); 10654 } 10655 addFilter(intent); 10656 } 10657 } 10658 10659 public final void removeProvider(PackageParser.Provider p) { 10660 mProviders.remove(p.getComponentName()); 10661 if (DEBUG_SHOW_INFO) { 10662 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 10663 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10664 Log.v(TAG, " Class=" + p.info.name); 10665 } 10666 final int NI = p.intents.size(); 10667 int j; 10668 for (j = 0; j < NI; j++) { 10669 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10670 if (DEBUG_SHOW_INFO) { 10671 Log.v(TAG, " IntentFilter:"); 10672 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10673 } 10674 removeFilter(intent); 10675 } 10676 } 10677 10678 @Override 10679 protected boolean allowFilterResult( 10680 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 10681 ProviderInfo filterPi = filter.provider.info; 10682 for (int i = dest.size() - 1; i >= 0; i--) { 10683 ProviderInfo destPi = dest.get(i).providerInfo; 10684 if (destPi.name == filterPi.name 10685 && destPi.packageName == filterPi.packageName) { 10686 return false; 10687 } 10688 } 10689 return true; 10690 } 10691 10692 @Override 10693 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 10694 return new PackageParser.ProviderIntentInfo[size]; 10695 } 10696 10697 @Override 10698 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 10699 if (!sUserManager.exists(userId)) 10700 return true; 10701 PackageParser.Package p = filter.provider.owner; 10702 if (p != null) { 10703 PackageSetting ps = (PackageSetting) p.mExtras; 10704 if (ps != null) { 10705 // System apps are never considered stopped for purposes of 10706 // filtering, because there may be no way for the user to 10707 // actually re-launch them. 10708 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10709 && ps.getStopped(userId); 10710 } 10711 } 10712 return false; 10713 } 10714 10715 @Override 10716 protected boolean isPackageForFilter(String packageName, 10717 PackageParser.ProviderIntentInfo info) { 10718 return packageName.equals(info.provider.owner.packageName); 10719 } 10720 10721 @Override 10722 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 10723 int match, int userId) { 10724 if (!sUserManager.exists(userId)) 10725 return null; 10726 final PackageParser.ProviderIntentInfo info = filter; 10727 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 10728 return null; 10729 } 10730 final PackageParser.Provider provider = info.provider; 10731 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 10732 if (ps == null) { 10733 return null; 10734 } 10735 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 10736 ps.readUserState(userId), userId); 10737 if (pi == null) { 10738 return null; 10739 } 10740 final ResolveInfo res = new ResolveInfo(); 10741 res.providerInfo = pi; 10742 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 10743 res.filter = filter; 10744 } 10745 res.priority = info.getPriority(); 10746 res.preferredOrder = provider.owner.mPreferredOrder; 10747 res.match = match; 10748 res.isDefault = info.hasDefault; 10749 res.labelRes = info.labelRes; 10750 res.nonLocalizedLabel = info.nonLocalizedLabel; 10751 res.icon = info.icon; 10752 res.system = res.providerInfo.applicationInfo.isSystemApp(); 10753 return res; 10754 } 10755 10756 @Override 10757 protected void sortResults(List<ResolveInfo> results) { 10758 Collections.sort(results, mResolvePrioritySorter); 10759 } 10760 10761 @Override 10762 protected void dumpFilter(PrintWriter out, String prefix, 10763 PackageParser.ProviderIntentInfo filter) { 10764 out.print(prefix); 10765 out.print( 10766 Integer.toHexString(System.identityHashCode(filter.provider))); 10767 out.print(' '); 10768 filter.provider.printComponentShortName(out); 10769 out.print(" filter "); 10770 out.println(Integer.toHexString(System.identityHashCode(filter))); 10771 } 10772 10773 @Override 10774 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 10775 return filter.provider; 10776 } 10777 10778 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10779 PackageParser.Provider provider = (PackageParser.Provider)label; 10780 out.print(prefix); out.print( 10781 Integer.toHexString(System.identityHashCode(provider))); 10782 out.print(' '); 10783 provider.printComponentShortName(out); 10784 if (count > 1) { 10785 out.print(" ("); out.print(count); out.print(" filters)"); 10786 } 10787 out.println(); 10788 } 10789 10790 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 10791 = new ArrayMap<ComponentName, PackageParser.Provider>(); 10792 private int mFlags; 10793 } 10794 10795 private static final class EphemeralIntentResolver 10796 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 10797 @Override 10798 protected EphemeralResolveIntentInfo[] newArray(int size) { 10799 return new EphemeralResolveIntentInfo[size]; 10800 } 10801 10802 @Override 10803 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 10804 return true; 10805 } 10806 10807 @Override 10808 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 10809 int userId) { 10810 if (!sUserManager.exists(userId)) { 10811 return null; 10812 } 10813 return info.getEphemeralResolveInfo(); 10814 } 10815 } 10816 10817 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 10818 new Comparator<ResolveInfo>() { 10819 public int compare(ResolveInfo r1, ResolveInfo r2) { 10820 int v1 = r1.priority; 10821 int v2 = r2.priority; 10822 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 10823 if (v1 != v2) { 10824 return (v1 > v2) ? -1 : 1; 10825 } 10826 v1 = r1.preferredOrder; 10827 v2 = r2.preferredOrder; 10828 if (v1 != v2) { 10829 return (v1 > v2) ? -1 : 1; 10830 } 10831 if (r1.isDefault != r2.isDefault) { 10832 return r1.isDefault ? -1 : 1; 10833 } 10834 v1 = r1.match; 10835 v2 = r2.match; 10836 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 10837 if (v1 != v2) { 10838 return (v1 > v2) ? -1 : 1; 10839 } 10840 if (r1.system != r2.system) { 10841 return r1.system ? -1 : 1; 10842 } 10843 if (r1.activityInfo != null) { 10844 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 10845 } 10846 if (r1.serviceInfo != null) { 10847 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 10848 } 10849 if (r1.providerInfo != null) { 10850 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 10851 } 10852 return 0; 10853 } 10854 }; 10855 10856 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 10857 new Comparator<ProviderInfo>() { 10858 public int compare(ProviderInfo p1, ProviderInfo p2) { 10859 final int v1 = p1.initOrder; 10860 final int v2 = p2.initOrder; 10861 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 10862 } 10863 }; 10864 10865 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 10866 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 10867 final int[] userIds) { 10868 mHandler.post(new Runnable() { 10869 @Override 10870 public void run() { 10871 try { 10872 final IActivityManager am = ActivityManagerNative.getDefault(); 10873 if (am == null) return; 10874 final int[] resolvedUserIds; 10875 if (userIds == null) { 10876 resolvedUserIds = am.getRunningUserIds(); 10877 } else { 10878 resolvedUserIds = userIds; 10879 } 10880 for (int id : resolvedUserIds) { 10881 final Intent intent = new Intent(action, 10882 pkg != null ? Uri.fromParts("package", pkg, null) : null); 10883 if (extras != null) { 10884 intent.putExtras(extras); 10885 } 10886 if (targetPkg != null) { 10887 intent.setPackage(targetPkg); 10888 } 10889 // Modify the UID when posting to other users 10890 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 10891 if (uid > 0 && UserHandle.getUserId(uid) != id) { 10892 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 10893 intent.putExtra(Intent.EXTRA_UID, uid); 10894 } 10895 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 10896 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 10897 if (DEBUG_BROADCASTS) { 10898 RuntimeException here = new RuntimeException("here"); 10899 here.fillInStackTrace(); 10900 Slog.d(TAG, "Sending to user " + id + ": " 10901 + intent.toShortString(false, true, false, false) 10902 + " " + intent.getExtras(), here); 10903 } 10904 am.broadcastIntent(null, intent, null, finishedReceiver, 10905 0, null, null, null, android.app.AppOpsManager.OP_NONE, 10906 null, finishedReceiver != null, false, id); 10907 } 10908 } catch (RemoteException ex) { 10909 } 10910 } 10911 }); 10912 } 10913 10914 /** 10915 * Check if the external storage media is available. This is true if there 10916 * is a mounted external storage medium or if the external storage is 10917 * emulated. 10918 */ 10919 private boolean isExternalMediaAvailable() { 10920 return mMediaMounted || Environment.isExternalStorageEmulated(); 10921 } 10922 10923 @Override 10924 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 10925 // writer 10926 synchronized (mPackages) { 10927 if (!isExternalMediaAvailable()) { 10928 // If the external storage is no longer mounted at this point, 10929 // the caller may not have been able to delete all of this 10930 // packages files and can not delete any more. Bail. 10931 return null; 10932 } 10933 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 10934 if (lastPackage != null) { 10935 pkgs.remove(lastPackage); 10936 } 10937 if (pkgs.size() > 0) { 10938 return pkgs.get(0); 10939 } 10940 } 10941 return null; 10942 } 10943 10944 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 10945 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 10946 userId, andCode ? 1 : 0, packageName); 10947 if (mSystemReady) { 10948 msg.sendToTarget(); 10949 } else { 10950 if (mPostSystemReadyMessages == null) { 10951 mPostSystemReadyMessages = new ArrayList<>(); 10952 } 10953 mPostSystemReadyMessages.add(msg); 10954 } 10955 } 10956 10957 void startCleaningPackages() { 10958 // reader 10959 if (!isExternalMediaAvailable()) { 10960 return; 10961 } 10962 synchronized (mPackages) { 10963 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 10964 return; 10965 } 10966 } 10967 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 10968 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 10969 IActivityManager am = ActivityManagerNative.getDefault(); 10970 if (am != null) { 10971 try { 10972 am.startService(null, intent, null, mContext.getOpPackageName(), 10973 UserHandle.USER_SYSTEM); 10974 } catch (RemoteException e) { 10975 } 10976 } 10977 } 10978 10979 @Override 10980 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 10981 int installFlags, String installerPackageName, int userId) { 10982 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 10983 10984 final int callingUid = Binder.getCallingUid(); 10985 enforceCrossUserPermission(callingUid, userId, 10986 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 10987 10988 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 10989 try { 10990 if (observer != null) { 10991 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 10992 } 10993 } catch (RemoteException re) { 10994 } 10995 return; 10996 } 10997 10998 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 10999 installFlags |= PackageManager.INSTALL_FROM_ADB; 11000 11001 } else { 11002 // Caller holds INSTALL_PACKAGES permission, so we're less strict 11003 // about installerPackageName. 11004 11005 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 11006 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 11007 } 11008 11009 UserHandle user; 11010 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 11011 user = UserHandle.ALL; 11012 } else { 11013 user = new UserHandle(userId); 11014 } 11015 11016 // Only system components can circumvent runtime permissions when installing. 11017 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 11018 && mContext.checkCallingOrSelfPermission(Manifest.permission 11019 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 11020 throw new SecurityException("You need the " 11021 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 11022 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 11023 } 11024 11025 final File originFile = new File(originPath); 11026 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 11027 11028 final Message msg = mHandler.obtainMessage(INIT_COPY); 11029 final VerificationInfo verificationInfo = new VerificationInfo( 11030 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 11031 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 11032 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 11033 null /*packageAbiOverride*/, null /*grantedPermissions*/, 11034 null /*certificates*/); 11035 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 11036 msg.obj = params; 11037 11038 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 11039 System.identityHashCode(msg.obj)); 11040 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11041 System.identityHashCode(msg.obj)); 11042 11043 mHandler.sendMessage(msg); 11044 } 11045 11046 void installStage(String packageName, File stagedDir, String stagedCid, 11047 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 11048 String installerPackageName, int installerUid, UserHandle user, 11049 Certificate[][] certificates) { 11050 if (DEBUG_EPHEMERAL) { 11051 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11052 Slog.d(TAG, "Ephemeral install of " + packageName); 11053 } 11054 } 11055 final VerificationInfo verificationInfo = new VerificationInfo( 11056 sessionParams.originatingUri, sessionParams.referrerUri, 11057 sessionParams.originatingUid, installerUid); 11058 11059 final OriginInfo origin; 11060 if (stagedDir != null) { 11061 origin = OriginInfo.fromStagedFile(stagedDir); 11062 } else { 11063 origin = OriginInfo.fromStagedContainer(stagedCid); 11064 } 11065 11066 final Message msg = mHandler.obtainMessage(INIT_COPY); 11067 final InstallParams params = new InstallParams(origin, null, observer, 11068 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 11069 verificationInfo, user, sessionParams.abiOverride, 11070 sessionParams.grantedRuntimePermissions, certificates); 11071 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 11072 msg.obj = params; 11073 11074 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 11075 System.identityHashCode(msg.obj)); 11076 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11077 System.identityHashCode(msg.obj)); 11078 11079 mHandler.sendMessage(msg); 11080 } 11081 11082 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 11083 int userId) { 11084 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 11085 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId); 11086 } 11087 11088 private void sendPackageAddedForUser(String packageName, boolean isSystem, 11089 int appId, int userId) { 11090 Bundle extras = new Bundle(1); 11091 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId)); 11092 11093 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 11094 packageName, extras, 0, null, null, new int[] {userId}); 11095 try { 11096 IActivityManager am = ActivityManagerNative.getDefault(); 11097 if (isSystem && am.isUserRunning(userId, 0)) { 11098 // The just-installed/enabled app is bundled on the system, so presumed 11099 // to be able to run automatically without needing an explicit launch. 11100 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 11101 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 11102 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 11103 .setPackage(packageName); 11104 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 11105 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 11106 } 11107 } catch (RemoteException e) { 11108 // shouldn't happen 11109 Slog.w(TAG, "Unable to bootstrap installed package", e); 11110 } 11111 } 11112 11113 @Override 11114 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 11115 int userId) { 11116 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11117 PackageSetting pkgSetting; 11118 final int uid = Binder.getCallingUid(); 11119 enforceCrossUserPermission(uid, userId, 11120 true /* requireFullPermission */, true /* checkShell */, 11121 "setApplicationHiddenSetting for user " + userId); 11122 11123 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 11124 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 11125 return false; 11126 } 11127 11128 long callingId = Binder.clearCallingIdentity(); 11129 try { 11130 boolean sendAdded = false; 11131 boolean sendRemoved = false; 11132 // writer 11133 synchronized (mPackages) { 11134 pkgSetting = mSettings.mPackages.get(packageName); 11135 if (pkgSetting == null) { 11136 return false; 11137 } 11138 if (pkgSetting.getHidden(userId) != hidden) { 11139 pkgSetting.setHidden(hidden, userId); 11140 mSettings.writePackageRestrictionsLPr(userId); 11141 if (hidden) { 11142 sendRemoved = true; 11143 } else { 11144 sendAdded = true; 11145 } 11146 } 11147 } 11148 if (sendAdded) { 11149 sendPackageAddedForUser(packageName, pkgSetting, userId); 11150 return true; 11151 } 11152 if (sendRemoved) { 11153 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 11154 "hiding pkg"); 11155 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 11156 return true; 11157 } 11158 } finally { 11159 Binder.restoreCallingIdentity(callingId); 11160 } 11161 return false; 11162 } 11163 11164 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 11165 int userId) { 11166 final PackageRemovedInfo info = new PackageRemovedInfo(); 11167 info.removedPackage = packageName; 11168 info.removedUsers = new int[] {userId}; 11169 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 11170 info.sendPackageRemovedBroadcasts(true /*killApp*/); 11171 } 11172 11173 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 11174 if (pkgList.length > 0) { 11175 Bundle extras = new Bundle(1); 11176 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 11177 11178 sendPackageBroadcast( 11179 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 11180 : Intent.ACTION_PACKAGES_UNSUSPENDED, 11181 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 11182 new int[] {userId}); 11183 } 11184 } 11185 11186 /** 11187 * Returns true if application is not found or there was an error. Otherwise it returns 11188 * the hidden state of the package for the given user. 11189 */ 11190 @Override 11191 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 11192 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11193 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11194 true /* requireFullPermission */, false /* checkShell */, 11195 "getApplicationHidden for user " + userId); 11196 PackageSetting pkgSetting; 11197 long callingId = Binder.clearCallingIdentity(); 11198 try { 11199 // writer 11200 synchronized (mPackages) { 11201 pkgSetting = mSettings.mPackages.get(packageName); 11202 if (pkgSetting == null) { 11203 return true; 11204 } 11205 return pkgSetting.getHidden(userId); 11206 } 11207 } finally { 11208 Binder.restoreCallingIdentity(callingId); 11209 } 11210 } 11211 11212 /** 11213 * @hide 11214 */ 11215 @Override 11216 public int installExistingPackageAsUser(String packageName, int userId) { 11217 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 11218 null); 11219 PackageSetting pkgSetting; 11220 final int uid = Binder.getCallingUid(); 11221 enforceCrossUserPermission(uid, userId, 11222 true /* requireFullPermission */, true /* checkShell */, 11223 "installExistingPackage for user " + userId); 11224 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11225 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 11226 } 11227 11228 long callingId = Binder.clearCallingIdentity(); 11229 try { 11230 boolean installed = false; 11231 11232 // writer 11233 synchronized (mPackages) { 11234 pkgSetting = mSettings.mPackages.get(packageName); 11235 if (pkgSetting == null) { 11236 return PackageManager.INSTALL_FAILED_INVALID_URI; 11237 } 11238 if (!pkgSetting.getInstalled(userId)) { 11239 pkgSetting.setInstalled(true, userId); 11240 pkgSetting.setHidden(false, userId); 11241 mSettings.writePackageRestrictionsLPr(userId); 11242 installed = true; 11243 } 11244 } 11245 11246 if (installed) { 11247 if (pkgSetting.pkg != null) { 11248 synchronized (mInstallLock) { 11249 // We don't need to freeze for a brand new install 11250 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 11251 } 11252 } 11253 sendPackageAddedForUser(packageName, pkgSetting, userId); 11254 } 11255 } finally { 11256 Binder.restoreCallingIdentity(callingId); 11257 } 11258 11259 return PackageManager.INSTALL_SUCCEEDED; 11260 } 11261 11262 boolean isUserRestricted(int userId, String restrictionKey) { 11263 Bundle restrictions = sUserManager.getUserRestrictions(userId); 11264 if (restrictions.getBoolean(restrictionKey, false)) { 11265 Log.w(TAG, "User is restricted: " + restrictionKey); 11266 return true; 11267 } 11268 return false; 11269 } 11270 11271 @Override 11272 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 11273 int userId) { 11274 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11275 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11276 true /* requireFullPermission */, true /* checkShell */, 11277 "setPackagesSuspended for user " + userId); 11278 11279 if (ArrayUtils.isEmpty(packageNames)) { 11280 return packageNames; 11281 } 11282 11283 // List of package names for whom the suspended state has changed. 11284 List<String> changedPackages = new ArrayList<>(packageNames.length); 11285 // List of package names for whom the suspended state is not set as requested in this 11286 // method. 11287 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 11288 for (int i = 0; i < packageNames.length; i++) { 11289 String packageName = packageNames[i]; 11290 long callingId = Binder.clearCallingIdentity(); 11291 try { 11292 boolean changed = false; 11293 final int appId; 11294 synchronized (mPackages) { 11295 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11296 if (pkgSetting == null) { 11297 Slog.w(TAG, "Could not find package setting for package \"" + packageName 11298 + "\". Skipping suspending/un-suspending."); 11299 unactionedPackages.add(packageName); 11300 continue; 11301 } 11302 appId = pkgSetting.appId; 11303 if (pkgSetting.getSuspended(userId) != suspended) { 11304 if (!canSuspendPackageForUserLocked(packageName, userId)) { 11305 unactionedPackages.add(packageName); 11306 continue; 11307 } 11308 pkgSetting.setSuspended(suspended, userId); 11309 mSettings.writePackageRestrictionsLPr(userId); 11310 changed = true; 11311 changedPackages.add(packageName); 11312 } 11313 } 11314 11315 if (changed && suspended) { 11316 killApplication(packageName, UserHandle.getUid(userId, appId), 11317 "suspending package"); 11318 } 11319 } finally { 11320 Binder.restoreCallingIdentity(callingId); 11321 } 11322 } 11323 11324 if (!changedPackages.isEmpty()) { 11325 sendPackagesSuspendedForUser(changedPackages.toArray( 11326 new String[changedPackages.size()]), userId, suspended); 11327 } 11328 11329 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 11330 } 11331 11332 @Override 11333 public boolean isPackageSuspendedForUser(String packageName, int userId) { 11334 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11335 true /* requireFullPermission */, false /* checkShell */, 11336 "isPackageSuspendedForUser for user " + userId); 11337 synchronized (mPackages) { 11338 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11339 if (pkgSetting == null) { 11340 throw new IllegalArgumentException("Unknown target package: " + packageName); 11341 } 11342 return pkgSetting.getSuspended(userId); 11343 } 11344 } 11345 11346 /** 11347 * TODO: cache and disallow blocking the active dialer. 11348 * 11349 * @see also DefaultPermissionGrantPolicy#grantDefaultSystemHandlerPermissions 11350 */ 11351 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 11352 if (isPackageDeviceAdmin(packageName, userId)) { 11353 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11354 + "\": has an active device admin"); 11355 return false; 11356 } 11357 11358 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 11359 if (packageName.equals(activeLauncherPackageName)) { 11360 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11361 + "\": contains the active launcher"); 11362 return false; 11363 } 11364 11365 if (packageName.equals(mRequiredInstallerPackage)) { 11366 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11367 + "\": required for package installation"); 11368 return false; 11369 } 11370 11371 if (packageName.equals(mRequiredVerifierPackage)) { 11372 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11373 + "\": required for package verification"); 11374 return false; 11375 } 11376 11377 final PackageParser.Package pkg = mPackages.get(packageName); 11378 if (pkg != null && isPrivilegedApp(pkg)) { 11379 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11380 + "\": is a privileged app"); 11381 return false; 11382 } 11383 11384 return true; 11385 } 11386 11387 private String getActiveLauncherPackageName(int userId) { 11388 Intent intent = new Intent(Intent.ACTION_MAIN); 11389 intent.addCategory(Intent.CATEGORY_HOME); 11390 ResolveInfo resolveInfo = resolveIntent( 11391 intent, 11392 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 11393 PackageManager.MATCH_DEFAULT_ONLY, 11394 userId); 11395 11396 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 11397 } 11398 11399 @Override 11400 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 11401 mContext.enforceCallingOrSelfPermission( 11402 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11403 "Only package verification agents can verify applications"); 11404 11405 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11406 final PackageVerificationResponse response = new PackageVerificationResponse( 11407 verificationCode, Binder.getCallingUid()); 11408 msg.arg1 = id; 11409 msg.obj = response; 11410 mHandler.sendMessage(msg); 11411 } 11412 11413 @Override 11414 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 11415 long millisecondsToDelay) { 11416 mContext.enforceCallingOrSelfPermission( 11417 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11418 "Only package verification agents can extend verification timeouts"); 11419 11420 final PackageVerificationState state = mPendingVerification.get(id); 11421 final PackageVerificationResponse response = new PackageVerificationResponse( 11422 verificationCodeAtTimeout, Binder.getCallingUid()); 11423 11424 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 11425 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 11426 } 11427 if (millisecondsToDelay < 0) { 11428 millisecondsToDelay = 0; 11429 } 11430 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 11431 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 11432 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 11433 } 11434 11435 if ((state != null) && !state.timeoutExtended()) { 11436 state.extendTimeout(); 11437 11438 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11439 msg.arg1 = id; 11440 msg.obj = response; 11441 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 11442 } 11443 } 11444 11445 private void broadcastPackageVerified(int verificationId, Uri packageUri, 11446 int verificationCode, UserHandle user) { 11447 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 11448 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 11449 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11450 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11451 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 11452 11453 mContext.sendBroadcastAsUser(intent, user, 11454 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 11455 } 11456 11457 private ComponentName matchComponentForVerifier(String packageName, 11458 List<ResolveInfo> receivers) { 11459 ActivityInfo targetReceiver = null; 11460 11461 final int NR = receivers.size(); 11462 for (int i = 0; i < NR; i++) { 11463 final ResolveInfo info = receivers.get(i); 11464 if (info.activityInfo == null) { 11465 continue; 11466 } 11467 11468 if (packageName.equals(info.activityInfo.packageName)) { 11469 targetReceiver = info.activityInfo; 11470 break; 11471 } 11472 } 11473 11474 if (targetReceiver == null) { 11475 return null; 11476 } 11477 11478 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 11479 } 11480 11481 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 11482 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 11483 if (pkgInfo.verifiers.length == 0) { 11484 return null; 11485 } 11486 11487 final int N = pkgInfo.verifiers.length; 11488 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 11489 for (int i = 0; i < N; i++) { 11490 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 11491 11492 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 11493 receivers); 11494 if (comp == null) { 11495 continue; 11496 } 11497 11498 final int verifierUid = getUidForVerifier(verifierInfo); 11499 if (verifierUid == -1) { 11500 continue; 11501 } 11502 11503 if (DEBUG_VERIFY) { 11504 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 11505 + " with the correct signature"); 11506 } 11507 sufficientVerifiers.add(comp); 11508 verificationState.addSufficientVerifier(verifierUid); 11509 } 11510 11511 return sufficientVerifiers; 11512 } 11513 11514 private int getUidForVerifier(VerifierInfo verifierInfo) { 11515 synchronized (mPackages) { 11516 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 11517 if (pkg == null) { 11518 return -1; 11519 } else if (pkg.mSignatures.length != 1) { 11520 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11521 + " has more than one signature; ignoring"); 11522 return -1; 11523 } 11524 11525 /* 11526 * If the public key of the package's signature does not match 11527 * our expected public key, then this is a different package and 11528 * we should skip. 11529 */ 11530 11531 final byte[] expectedPublicKey; 11532 try { 11533 final Signature verifierSig = pkg.mSignatures[0]; 11534 final PublicKey publicKey = verifierSig.getPublicKey(); 11535 expectedPublicKey = publicKey.getEncoded(); 11536 } catch (CertificateException e) { 11537 return -1; 11538 } 11539 11540 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 11541 11542 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 11543 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11544 + " does not have the expected public key; ignoring"); 11545 return -1; 11546 } 11547 11548 return pkg.applicationInfo.uid; 11549 } 11550 } 11551 11552 @Override 11553 public void finishPackageInstall(int token) { 11554 enforceSystemOrRoot("Only the system is allowed to finish installs"); 11555 11556 if (DEBUG_INSTALL) { 11557 Slog.v(TAG, "BM finishing package install for " + token); 11558 } 11559 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 11560 11561 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 11562 mHandler.sendMessage(msg); 11563 } 11564 11565 /** 11566 * Get the verification agent timeout. 11567 * 11568 * @return verification timeout in milliseconds 11569 */ 11570 private long getVerificationTimeout() { 11571 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 11572 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 11573 DEFAULT_VERIFICATION_TIMEOUT); 11574 } 11575 11576 /** 11577 * Get the default verification agent response code. 11578 * 11579 * @return default verification response code 11580 */ 11581 private int getDefaultVerificationResponse() { 11582 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11583 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 11584 DEFAULT_VERIFICATION_RESPONSE); 11585 } 11586 11587 /** 11588 * Check whether or not package verification has been enabled. 11589 * 11590 * @return true if verification should be performed 11591 */ 11592 private boolean isVerificationEnabled(int userId, int installFlags) { 11593 if (!DEFAULT_VERIFY_ENABLE) { 11594 return false; 11595 } 11596 // Ephemeral apps don't get the full verification treatment 11597 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11598 if (DEBUG_EPHEMERAL) { 11599 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 11600 } 11601 return false; 11602 } 11603 11604 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 11605 11606 // Check if installing from ADB 11607 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 11608 // Do not run verification in a test harness environment 11609 if (ActivityManager.isRunningInTestHarness()) { 11610 return false; 11611 } 11612 if (ensureVerifyAppsEnabled) { 11613 return true; 11614 } 11615 // Check if the developer does not want package verification for ADB installs 11616 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11617 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 11618 return false; 11619 } 11620 } 11621 11622 if (ensureVerifyAppsEnabled) { 11623 return true; 11624 } 11625 11626 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11627 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 11628 } 11629 11630 @Override 11631 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 11632 throws RemoteException { 11633 mContext.enforceCallingOrSelfPermission( 11634 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 11635 "Only intentfilter verification agents can verify applications"); 11636 11637 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 11638 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 11639 Binder.getCallingUid(), verificationCode, failedDomains); 11640 msg.arg1 = id; 11641 msg.obj = response; 11642 mHandler.sendMessage(msg); 11643 } 11644 11645 @Override 11646 public int getIntentVerificationStatus(String packageName, int userId) { 11647 synchronized (mPackages) { 11648 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 11649 } 11650 } 11651 11652 @Override 11653 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 11654 mContext.enforceCallingOrSelfPermission( 11655 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11656 11657 boolean result = false; 11658 synchronized (mPackages) { 11659 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 11660 } 11661 if (result) { 11662 scheduleWritePackageRestrictionsLocked(userId); 11663 } 11664 return result; 11665 } 11666 11667 @Override 11668 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 11669 String packageName) { 11670 synchronized (mPackages) { 11671 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 11672 } 11673 } 11674 11675 @Override 11676 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 11677 if (TextUtils.isEmpty(packageName)) { 11678 return ParceledListSlice.emptyList(); 11679 } 11680 synchronized (mPackages) { 11681 PackageParser.Package pkg = mPackages.get(packageName); 11682 if (pkg == null || pkg.activities == null) { 11683 return ParceledListSlice.emptyList(); 11684 } 11685 final int count = pkg.activities.size(); 11686 ArrayList<IntentFilter> result = new ArrayList<>(); 11687 for (int n=0; n<count; n++) { 11688 PackageParser.Activity activity = pkg.activities.get(n); 11689 if (activity.intents != null && activity.intents.size() > 0) { 11690 result.addAll(activity.intents); 11691 } 11692 } 11693 return new ParceledListSlice<>(result); 11694 } 11695 } 11696 11697 @Override 11698 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 11699 mContext.enforceCallingOrSelfPermission( 11700 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11701 11702 synchronized (mPackages) { 11703 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 11704 if (packageName != null) { 11705 result |= updateIntentVerificationStatus(packageName, 11706 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 11707 userId); 11708 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 11709 packageName, userId); 11710 } 11711 return result; 11712 } 11713 } 11714 11715 @Override 11716 public String getDefaultBrowserPackageName(int userId) { 11717 synchronized (mPackages) { 11718 return mSettings.getDefaultBrowserPackageNameLPw(userId); 11719 } 11720 } 11721 11722 /** 11723 * Get the "allow unknown sources" setting. 11724 * 11725 * @return the current "allow unknown sources" setting 11726 */ 11727 private int getUnknownSourcesSettings() { 11728 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 11729 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 11730 -1); 11731 } 11732 11733 @Override 11734 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 11735 final int uid = Binder.getCallingUid(); 11736 // writer 11737 synchronized (mPackages) { 11738 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 11739 if (targetPackageSetting == null) { 11740 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 11741 } 11742 11743 PackageSetting installerPackageSetting; 11744 if (installerPackageName != null) { 11745 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 11746 if (installerPackageSetting == null) { 11747 throw new IllegalArgumentException("Unknown installer package: " 11748 + installerPackageName); 11749 } 11750 } else { 11751 installerPackageSetting = null; 11752 } 11753 11754 Signature[] callerSignature; 11755 Object obj = mSettings.getUserIdLPr(uid); 11756 if (obj != null) { 11757 if (obj instanceof SharedUserSetting) { 11758 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 11759 } else if (obj instanceof PackageSetting) { 11760 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 11761 } else { 11762 throw new SecurityException("Bad object " + obj + " for uid " + uid); 11763 } 11764 } else { 11765 throw new SecurityException("Unknown calling UID: " + uid); 11766 } 11767 11768 // Verify: can't set installerPackageName to a package that is 11769 // not signed with the same cert as the caller. 11770 if (installerPackageSetting != null) { 11771 if (compareSignatures(callerSignature, 11772 installerPackageSetting.signatures.mSignatures) 11773 != PackageManager.SIGNATURE_MATCH) { 11774 throw new SecurityException( 11775 "Caller does not have same cert as new installer package " 11776 + installerPackageName); 11777 } 11778 } 11779 11780 // Verify: if target already has an installer package, it must 11781 // be signed with the same cert as the caller. 11782 if (targetPackageSetting.installerPackageName != null) { 11783 PackageSetting setting = mSettings.mPackages.get( 11784 targetPackageSetting.installerPackageName); 11785 // If the currently set package isn't valid, then it's always 11786 // okay to change it. 11787 if (setting != null) { 11788 if (compareSignatures(callerSignature, 11789 setting.signatures.mSignatures) 11790 != PackageManager.SIGNATURE_MATCH) { 11791 throw new SecurityException( 11792 "Caller does not have same cert as old installer package " 11793 + targetPackageSetting.installerPackageName); 11794 } 11795 } 11796 } 11797 11798 // Okay! 11799 targetPackageSetting.installerPackageName = installerPackageName; 11800 if (installerPackageName != null) { 11801 mSettings.mInstallerPackages.add(installerPackageName); 11802 } 11803 scheduleWriteSettingsLocked(); 11804 } 11805 } 11806 11807 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 11808 // Queue up an async operation since the package installation may take a little while. 11809 mHandler.post(new Runnable() { 11810 public void run() { 11811 mHandler.removeCallbacks(this); 11812 // Result object to be returned 11813 PackageInstalledInfo res = new PackageInstalledInfo(); 11814 res.setReturnCode(currentStatus); 11815 res.uid = -1; 11816 res.pkg = null; 11817 res.removedInfo = null; 11818 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11819 args.doPreInstall(res.returnCode); 11820 synchronized (mInstallLock) { 11821 installPackageTracedLI(args, res); 11822 } 11823 args.doPostInstall(res.returnCode, res.uid); 11824 } 11825 11826 // A restore should be performed at this point if (a) the install 11827 // succeeded, (b) the operation is not an update, and (c) the new 11828 // package has not opted out of backup participation. 11829 final boolean update = res.removedInfo != null 11830 && res.removedInfo.removedPackage != null; 11831 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 11832 boolean doRestore = !update 11833 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 11834 11835 // Set up the post-install work request bookkeeping. This will be used 11836 // and cleaned up by the post-install event handling regardless of whether 11837 // there's a restore pass performed. Token values are >= 1. 11838 int token; 11839 if (mNextInstallToken < 0) mNextInstallToken = 1; 11840 token = mNextInstallToken++; 11841 11842 PostInstallData data = new PostInstallData(args, res); 11843 mRunningInstalls.put(token, data); 11844 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 11845 11846 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 11847 // Pass responsibility to the Backup Manager. It will perform a 11848 // restore if appropriate, then pass responsibility back to the 11849 // Package Manager to run the post-install observer callbacks 11850 // and broadcasts. 11851 IBackupManager bm = IBackupManager.Stub.asInterface( 11852 ServiceManager.getService(Context.BACKUP_SERVICE)); 11853 if (bm != null) { 11854 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 11855 + " to BM for possible restore"); 11856 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 11857 try { 11858 // TODO: http://b/22388012 11859 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 11860 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 11861 } else { 11862 doRestore = false; 11863 } 11864 } catch (RemoteException e) { 11865 // can't happen; the backup manager is local 11866 } catch (Exception e) { 11867 Slog.e(TAG, "Exception trying to enqueue restore", e); 11868 doRestore = false; 11869 } 11870 } else { 11871 Slog.e(TAG, "Backup Manager not found!"); 11872 doRestore = false; 11873 } 11874 } 11875 11876 if (!doRestore) { 11877 // No restore possible, or the Backup Manager was mysteriously not 11878 // available -- just fire the post-install work request directly. 11879 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 11880 11881 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 11882 11883 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 11884 mHandler.sendMessage(msg); 11885 } 11886 } 11887 }); 11888 } 11889 11890 private abstract class HandlerParams { 11891 private static final int MAX_RETRIES = 4; 11892 11893 /** 11894 * Number of times startCopy() has been attempted and had a non-fatal 11895 * error. 11896 */ 11897 private int mRetries = 0; 11898 11899 /** User handle for the user requesting the information or installation. */ 11900 private final UserHandle mUser; 11901 String traceMethod; 11902 int traceCookie; 11903 11904 HandlerParams(UserHandle user) { 11905 mUser = user; 11906 } 11907 11908 UserHandle getUser() { 11909 return mUser; 11910 } 11911 11912 HandlerParams setTraceMethod(String traceMethod) { 11913 this.traceMethod = traceMethod; 11914 return this; 11915 } 11916 11917 HandlerParams setTraceCookie(int traceCookie) { 11918 this.traceCookie = traceCookie; 11919 return this; 11920 } 11921 11922 final boolean startCopy() { 11923 boolean res; 11924 try { 11925 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 11926 11927 if (++mRetries > MAX_RETRIES) { 11928 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 11929 mHandler.sendEmptyMessage(MCS_GIVE_UP); 11930 handleServiceError(); 11931 return false; 11932 } else { 11933 handleStartCopy(); 11934 res = true; 11935 } 11936 } catch (RemoteException e) { 11937 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 11938 mHandler.sendEmptyMessage(MCS_RECONNECT); 11939 res = false; 11940 } 11941 handleReturnCode(); 11942 return res; 11943 } 11944 11945 final void serviceError() { 11946 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 11947 handleServiceError(); 11948 handleReturnCode(); 11949 } 11950 11951 abstract void handleStartCopy() throws RemoteException; 11952 abstract void handleServiceError(); 11953 abstract void handleReturnCode(); 11954 } 11955 11956 class MeasureParams extends HandlerParams { 11957 private final PackageStats mStats; 11958 private boolean mSuccess; 11959 11960 private final IPackageStatsObserver mObserver; 11961 11962 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 11963 super(new UserHandle(stats.userHandle)); 11964 mObserver = observer; 11965 mStats = stats; 11966 } 11967 11968 @Override 11969 public String toString() { 11970 return "MeasureParams{" 11971 + Integer.toHexString(System.identityHashCode(this)) 11972 + " " + mStats.packageName + "}"; 11973 } 11974 11975 @Override 11976 void handleStartCopy() throws RemoteException { 11977 synchronized (mInstallLock) { 11978 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 11979 } 11980 11981 if (mSuccess) { 11982 final boolean mounted; 11983 if (Environment.isExternalStorageEmulated()) { 11984 mounted = true; 11985 } else { 11986 final String status = Environment.getExternalStorageState(); 11987 mounted = (Environment.MEDIA_MOUNTED.equals(status) 11988 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 11989 } 11990 11991 if (mounted) { 11992 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 11993 11994 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 11995 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 11996 11997 mStats.externalDataSize = calculateDirectorySize(mContainerService, 11998 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 11999 12000 // Always subtract cache size, since it's a subdirectory 12001 mStats.externalDataSize -= mStats.externalCacheSize; 12002 12003 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 12004 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 12005 12006 mStats.externalObbSize = calculateDirectorySize(mContainerService, 12007 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 12008 } 12009 } 12010 } 12011 12012 @Override 12013 void handleReturnCode() { 12014 if (mObserver != null) { 12015 try { 12016 mObserver.onGetStatsCompleted(mStats, mSuccess); 12017 } catch (RemoteException e) { 12018 Slog.i(TAG, "Observer no longer exists."); 12019 } 12020 } 12021 } 12022 12023 @Override 12024 void handleServiceError() { 12025 Slog.e(TAG, "Could not measure application " + mStats.packageName 12026 + " external storage"); 12027 } 12028 } 12029 12030 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 12031 throws RemoteException { 12032 long result = 0; 12033 for (File path : paths) { 12034 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 12035 } 12036 return result; 12037 } 12038 12039 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 12040 for (File path : paths) { 12041 try { 12042 mcs.clearDirectory(path.getAbsolutePath()); 12043 } catch (RemoteException e) { 12044 } 12045 } 12046 } 12047 12048 static class OriginInfo { 12049 /** 12050 * Location where install is coming from, before it has been 12051 * copied/renamed into place. This could be a single monolithic APK 12052 * file, or a cluster directory. This location may be untrusted. 12053 */ 12054 final File file; 12055 final String cid; 12056 12057 /** 12058 * Flag indicating that {@link #file} or {@link #cid} has already been 12059 * staged, meaning downstream users don't need to defensively copy the 12060 * contents. 12061 */ 12062 final boolean staged; 12063 12064 /** 12065 * Flag indicating that {@link #file} or {@link #cid} is an already 12066 * installed app that is being moved. 12067 */ 12068 final boolean existing; 12069 12070 final String resolvedPath; 12071 final File resolvedFile; 12072 12073 static OriginInfo fromNothing() { 12074 return new OriginInfo(null, null, false, false); 12075 } 12076 12077 static OriginInfo fromUntrustedFile(File file) { 12078 return new OriginInfo(file, null, false, false); 12079 } 12080 12081 static OriginInfo fromExistingFile(File file) { 12082 return new OriginInfo(file, null, false, true); 12083 } 12084 12085 static OriginInfo fromStagedFile(File file) { 12086 return new OriginInfo(file, null, true, false); 12087 } 12088 12089 static OriginInfo fromStagedContainer(String cid) { 12090 return new OriginInfo(null, cid, true, false); 12091 } 12092 12093 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 12094 this.file = file; 12095 this.cid = cid; 12096 this.staged = staged; 12097 this.existing = existing; 12098 12099 if (cid != null) { 12100 resolvedPath = PackageHelper.getSdDir(cid); 12101 resolvedFile = new File(resolvedPath); 12102 } else if (file != null) { 12103 resolvedPath = file.getAbsolutePath(); 12104 resolvedFile = file; 12105 } else { 12106 resolvedPath = null; 12107 resolvedFile = null; 12108 } 12109 } 12110 } 12111 12112 static class MoveInfo { 12113 final int moveId; 12114 final String fromUuid; 12115 final String toUuid; 12116 final String packageName; 12117 final String dataAppName; 12118 final int appId; 12119 final String seinfo; 12120 final int targetSdkVersion; 12121 12122 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 12123 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 12124 this.moveId = moveId; 12125 this.fromUuid = fromUuid; 12126 this.toUuid = toUuid; 12127 this.packageName = packageName; 12128 this.dataAppName = dataAppName; 12129 this.appId = appId; 12130 this.seinfo = seinfo; 12131 this.targetSdkVersion = targetSdkVersion; 12132 } 12133 } 12134 12135 static class VerificationInfo { 12136 /** A constant used to indicate that a uid value is not present. */ 12137 public static final int NO_UID = -1; 12138 12139 /** URI referencing where the package was downloaded from. */ 12140 final Uri originatingUri; 12141 12142 /** HTTP referrer URI associated with the originatingURI. */ 12143 final Uri referrer; 12144 12145 /** UID of the application that the install request originated from. */ 12146 final int originatingUid; 12147 12148 /** UID of application requesting the install */ 12149 final int installerUid; 12150 12151 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 12152 this.originatingUri = originatingUri; 12153 this.referrer = referrer; 12154 this.originatingUid = originatingUid; 12155 this.installerUid = installerUid; 12156 } 12157 } 12158 12159 class InstallParams extends HandlerParams { 12160 final OriginInfo origin; 12161 final MoveInfo move; 12162 final IPackageInstallObserver2 observer; 12163 int installFlags; 12164 final String installerPackageName; 12165 final String volumeUuid; 12166 private InstallArgs mArgs; 12167 private int mRet; 12168 final String packageAbiOverride; 12169 final String[] grantedRuntimePermissions; 12170 final VerificationInfo verificationInfo; 12171 final Certificate[][] certificates; 12172 12173 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12174 int installFlags, String installerPackageName, String volumeUuid, 12175 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 12176 String[] grantedPermissions, Certificate[][] certificates) { 12177 super(user); 12178 this.origin = origin; 12179 this.move = move; 12180 this.observer = observer; 12181 this.installFlags = installFlags; 12182 this.installerPackageName = installerPackageName; 12183 this.volumeUuid = volumeUuid; 12184 this.verificationInfo = verificationInfo; 12185 this.packageAbiOverride = packageAbiOverride; 12186 this.grantedRuntimePermissions = grantedPermissions; 12187 this.certificates = certificates; 12188 } 12189 12190 @Override 12191 public String toString() { 12192 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 12193 + " file=" + origin.file + " cid=" + origin.cid + "}"; 12194 } 12195 12196 private int installLocationPolicy(PackageInfoLite pkgLite) { 12197 String packageName = pkgLite.packageName; 12198 int installLocation = pkgLite.installLocation; 12199 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12200 // reader 12201 synchronized (mPackages) { 12202 // Currently installed package which the new package is attempting to replace or 12203 // null if no such package is installed. 12204 PackageParser.Package installedPkg = mPackages.get(packageName); 12205 // Package which currently owns the data which the new package will own if installed. 12206 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 12207 // will be null whereas dataOwnerPkg will contain information about the package 12208 // which was uninstalled while keeping its data. 12209 PackageParser.Package dataOwnerPkg = installedPkg; 12210 if (dataOwnerPkg == null) { 12211 PackageSetting ps = mSettings.mPackages.get(packageName); 12212 if (ps != null) { 12213 dataOwnerPkg = ps.pkg; 12214 } 12215 } 12216 12217 if (dataOwnerPkg != null) { 12218 // If installed, the package will get access to data left on the device by its 12219 // predecessor. As a security measure, this is permited only if this is not a 12220 // version downgrade or if the predecessor package is marked as debuggable and 12221 // a downgrade is explicitly requested. 12222 // 12223 // On debuggable platform builds, downgrades are permitted even for 12224 // non-debuggable packages to make testing easier. Debuggable platform builds do 12225 // not offer security guarantees and thus it's OK to disable some security 12226 // mechanisms to make debugging/testing easier on those builds. However, even on 12227 // debuggable builds downgrades of packages are permitted only if requested via 12228 // installFlags. This is because we aim to keep the behavior of debuggable 12229 // platform builds as close as possible to the behavior of non-debuggable 12230 // platform builds. 12231 final boolean downgradeRequested = 12232 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 12233 final boolean packageDebuggable = 12234 (dataOwnerPkg.applicationInfo.flags 12235 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 12236 final boolean downgradePermitted = 12237 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 12238 if (!downgradePermitted) { 12239 try { 12240 checkDowngrade(dataOwnerPkg, pkgLite); 12241 } catch (PackageManagerException e) { 12242 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 12243 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 12244 } 12245 } 12246 } 12247 12248 if (installedPkg != null) { 12249 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12250 // Check for updated system application. 12251 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 12252 if (onSd) { 12253 Slog.w(TAG, "Cannot install update to system app on sdcard"); 12254 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 12255 } 12256 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12257 } else { 12258 if (onSd) { 12259 // Install flag overrides everything. 12260 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12261 } 12262 // If current upgrade specifies particular preference 12263 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 12264 // Application explicitly specified internal. 12265 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12266 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 12267 // App explictly prefers external. Let policy decide 12268 } else { 12269 // Prefer previous location 12270 if (isExternal(installedPkg)) { 12271 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12272 } 12273 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12274 } 12275 } 12276 } else { 12277 // Invalid install. Return error code 12278 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 12279 } 12280 } 12281 } 12282 // All the special cases have been taken care of. 12283 // Return result based on recommended install location. 12284 if (onSd) { 12285 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12286 } 12287 return pkgLite.recommendedInstallLocation; 12288 } 12289 12290 /* 12291 * Invoke remote method to get package information and install 12292 * location values. Override install location based on default 12293 * policy if needed and then create install arguments based 12294 * on the install location. 12295 */ 12296 public void handleStartCopy() throws RemoteException { 12297 int ret = PackageManager.INSTALL_SUCCEEDED; 12298 12299 // If we're already staged, we've firmly committed to an install location 12300 if (origin.staged) { 12301 if (origin.file != null) { 12302 installFlags |= PackageManager.INSTALL_INTERNAL; 12303 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12304 } else if (origin.cid != null) { 12305 installFlags |= PackageManager.INSTALL_EXTERNAL; 12306 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12307 } else { 12308 throw new IllegalStateException("Invalid stage location"); 12309 } 12310 } 12311 12312 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12313 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 12314 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12315 PackageInfoLite pkgLite = null; 12316 12317 if (onInt && onSd) { 12318 // Check if both bits are set. 12319 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 12320 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12321 } else if (onSd && ephemeral) { 12322 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 12323 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12324 } else { 12325 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 12326 packageAbiOverride); 12327 12328 if (DEBUG_EPHEMERAL && ephemeral) { 12329 Slog.v(TAG, "pkgLite for install: " + pkgLite); 12330 } 12331 12332 /* 12333 * If we have too little free space, try to free cache 12334 * before giving up. 12335 */ 12336 if (!origin.staged && pkgLite.recommendedInstallLocation 12337 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12338 // TODO: focus freeing disk space on the target device 12339 final StorageManager storage = StorageManager.from(mContext); 12340 final long lowThreshold = storage.getStorageLowBytes( 12341 Environment.getDataDirectory()); 12342 12343 final long sizeBytes = mContainerService.calculateInstalledSize( 12344 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 12345 12346 try { 12347 mInstaller.freeCache(null, sizeBytes + lowThreshold); 12348 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 12349 installFlags, packageAbiOverride); 12350 } catch (InstallerException e) { 12351 Slog.w(TAG, "Failed to free cache", e); 12352 } 12353 12354 /* 12355 * The cache free must have deleted the file we 12356 * downloaded to install. 12357 * 12358 * TODO: fix the "freeCache" call to not delete 12359 * the file we care about. 12360 */ 12361 if (pkgLite.recommendedInstallLocation 12362 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12363 pkgLite.recommendedInstallLocation 12364 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 12365 } 12366 } 12367 } 12368 12369 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12370 int loc = pkgLite.recommendedInstallLocation; 12371 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 12372 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12373 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 12374 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 12375 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12376 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12377 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 12378 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 12379 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12380 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 12381 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 12382 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 12383 } else { 12384 // Override with defaults if needed. 12385 loc = installLocationPolicy(pkgLite); 12386 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 12387 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 12388 } else if (!onSd && !onInt) { 12389 // Override install location with flags 12390 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 12391 // Set the flag to install on external media. 12392 installFlags |= PackageManager.INSTALL_EXTERNAL; 12393 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12394 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 12395 if (DEBUG_EPHEMERAL) { 12396 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 12397 } 12398 installFlags |= PackageManager.INSTALL_EPHEMERAL; 12399 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 12400 |PackageManager.INSTALL_INTERNAL); 12401 } else { 12402 // Make sure the flag for installing on external 12403 // media is unset 12404 installFlags |= PackageManager.INSTALL_INTERNAL; 12405 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12406 } 12407 } 12408 } 12409 } 12410 12411 final InstallArgs args = createInstallArgs(this); 12412 mArgs = args; 12413 12414 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12415 // TODO: http://b/22976637 12416 // Apps installed for "all" users use the device owner to verify the app 12417 UserHandle verifierUser = getUser(); 12418 if (verifierUser == UserHandle.ALL) { 12419 verifierUser = UserHandle.SYSTEM; 12420 } 12421 12422 /* 12423 * Determine if we have any installed package verifiers. If we 12424 * do, then we'll defer to them to verify the packages. 12425 */ 12426 final int requiredUid = mRequiredVerifierPackage == null ? -1 12427 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 12428 verifierUser.getIdentifier()); 12429 if (!origin.existing && requiredUid != -1 12430 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 12431 final Intent verification = new Intent( 12432 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 12433 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 12434 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 12435 PACKAGE_MIME_TYPE); 12436 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 12437 12438 // Query all live verifiers based on current user state 12439 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 12440 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 12441 12442 if (DEBUG_VERIFY) { 12443 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 12444 + verification.toString() + " with " + pkgLite.verifiers.length 12445 + " optional verifiers"); 12446 } 12447 12448 final int verificationId = mPendingVerificationToken++; 12449 12450 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 12451 12452 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 12453 installerPackageName); 12454 12455 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 12456 installFlags); 12457 12458 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 12459 pkgLite.packageName); 12460 12461 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 12462 pkgLite.versionCode); 12463 12464 if (verificationInfo != null) { 12465 if (verificationInfo.originatingUri != null) { 12466 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 12467 verificationInfo.originatingUri); 12468 } 12469 if (verificationInfo.referrer != null) { 12470 verification.putExtra(Intent.EXTRA_REFERRER, 12471 verificationInfo.referrer); 12472 } 12473 if (verificationInfo.originatingUid >= 0) { 12474 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 12475 verificationInfo.originatingUid); 12476 } 12477 if (verificationInfo.installerUid >= 0) { 12478 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 12479 verificationInfo.installerUid); 12480 } 12481 } 12482 12483 final PackageVerificationState verificationState = new PackageVerificationState( 12484 requiredUid, args); 12485 12486 mPendingVerification.append(verificationId, verificationState); 12487 12488 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 12489 receivers, verificationState); 12490 12491 /* 12492 * If any sufficient verifiers were listed in the package 12493 * manifest, attempt to ask them. 12494 */ 12495 if (sufficientVerifiers != null) { 12496 final int N = sufficientVerifiers.size(); 12497 if (N == 0) { 12498 Slog.i(TAG, "Additional verifiers required, but none installed."); 12499 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 12500 } else { 12501 for (int i = 0; i < N; i++) { 12502 final ComponentName verifierComponent = sufficientVerifiers.get(i); 12503 12504 final Intent sufficientIntent = new Intent(verification); 12505 sufficientIntent.setComponent(verifierComponent); 12506 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 12507 } 12508 } 12509 } 12510 12511 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 12512 mRequiredVerifierPackage, receivers); 12513 if (ret == PackageManager.INSTALL_SUCCEEDED 12514 && mRequiredVerifierPackage != null) { 12515 Trace.asyncTraceBegin( 12516 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 12517 /* 12518 * Send the intent to the required verification agent, 12519 * but only start the verification timeout after the 12520 * target BroadcastReceivers have run. 12521 */ 12522 verification.setComponent(requiredVerifierComponent); 12523 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 12524 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12525 new BroadcastReceiver() { 12526 @Override 12527 public void onReceive(Context context, Intent intent) { 12528 final Message msg = mHandler 12529 .obtainMessage(CHECK_PENDING_VERIFICATION); 12530 msg.arg1 = verificationId; 12531 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 12532 } 12533 }, null, 0, null, null); 12534 12535 /* 12536 * We don't want the copy to proceed until verification 12537 * succeeds, so null out this field. 12538 */ 12539 mArgs = null; 12540 } 12541 } else { 12542 /* 12543 * No package verification is enabled, so immediately start 12544 * the remote call to initiate copy using temporary file. 12545 */ 12546 ret = args.copyApk(mContainerService, true); 12547 } 12548 } 12549 12550 mRet = ret; 12551 } 12552 12553 @Override 12554 void handleReturnCode() { 12555 // If mArgs is null, then MCS couldn't be reached. When it 12556 // reconnects, it will try again to install. At that point, this 12557 // will succeed. 12558 if (mArgs != null) { 12559 processPendingInstall(mArgs, mRet); 12560 } 12561 } 12562 12563 @Override 12564 void handleServiceError() { 12565 mArgs = createInstallArgs(this); 12566 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12567 } 12568 12569 public boolean isForwardLocked() { 12570 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12571 } 12572 } 12573 12574 /** 12575 * Used during creation of InstallArgs 12576 * 12577 * @param installFlags package installation flags 12578 * @return true if should be installed on external storage 12579 */ 12580 private static boolean installOnExternalAsec(int installFlags) { 12581 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 12582 return false; 12583 } 12584 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 12585 return true; 12586 } 12587 return false; 12588 } 12589 12590 /** 12591 * Used during creation of InstallArgs 12592 * 12593 * @param installFlags package installation flags 12594 * @return true if should be installed as forward locked 12595 */ 12596 private static boolean installForwardLocked(int installFlags) { 12597 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12598 } 12599 12600 private InstallArgs createInstallArgs(InstallParams params) { 12601 if (params.move != null) { 12602 return new MoveInstallArgs(params); 12603 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 12604 return new AsecInstallArgs(params); 12605 } else { 12606 return new FileInstallArgs(params); 12607 } 12608 } 12609 12610 /** 12611 * Create args that describe an existing installed package. Typically used 12612 * when cleaning up old installs, or used as a move source. 12613 */ 12614 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 12615 String resourcePath, String[] instructionSets) { 12616 final boolean isInAsec; 12617 if (installOnExternalAsec(installFlags)) { 12618 /* Apps on SD card are always in ASEC containers. */ 12619 isInAsec = true; 12620 } else if (installForwardLocked(installFlags) 12621 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 12622 /* 12623 * Forward-locked apps are only in ASEC containers if they're the 12624 * new style 12625 */ 12626 isInAsec = true; 12627 } else { 12628 isInAsec = false; 12629 } 12630 12631 if (isInAsec) { 12632 return new AsecInstallArgs(codePath, instructionSets, 12633 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 12634 } else { 12635 return new FileInstallArgs(codePath, resourcePath, instructionSets); 12636 } 12637 } 12638 12639 static abstract class InstallArgs { 12640 /** @see InstallParams#origin */ 12641 final OriginInfo origin; 12642 /** @see InstallParams#move */ 12643 final MoveInfo move; 12644 12645 final IPackageInstallObserver2 observer; 12646 // Always refers to PackageManager flags only 12647 final int installFlags; 12648 final String installerPackageName; 12649 final String volumeUuid; 12650 final UserHandle user; 12651 final String abiOverride; 12652 final String[] installGrantPermissions; 12653 /** If non-null, drop an async trace when the install completes */ 12654 final String traceMethod; 12655 final int traceCookie; 12656 final Certificate[][] certificates; 12657 12658 // The list of instruction sets supported by this app. This is currently 12659 // only used during the rmdex() phase to clean up resources. We can get rid of this 12660 // if we move dex files under the common app path. 12661 /* nullable */ String[] instructionSets; 12662 12663 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12664 int installFlags, String installerPackageName, String volumeUuid, 12665 UserHandle user, String[] instructionSets, 12666 String abiOverride, String[] installGrantPermissions, 12667 String traceMethod, int traceCookie, Certificate[][] certificates) { 12668 this.origin = origin; 12669 this.move = move; 12670 this.installFlags = installFlags; 12671 this.observer = observer; 12672 this.installerPackageName = installerPackageName; 12673 this.volumeUuid = volumeUuid; 12674 this.user = user; 12675 this.instructionSets = instructionSets; 12676 this.abiOverride = abiOverride; 12677 this.installGrantPermissions = installGrantPermissions; 12678 this.traceMethod = traceMethod; 12679 this.traceCookie = traceCookie; 12680 this.certificates = certificates; 12681 } 12682 12683 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 12684 abstract int doPreInstall(int status); 12685 12686 /** 12687 * Rename package into final resting place. All paths on the given 12688 * scanned package should be updated to reflect the rename. 12689 */ 12690 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 12691 abstract int doPostInstall(int status, int uid); 12692 12693 /** @see PackageSettingBase#codePathString */ 12694 abstract String getCodePath(); 12695 /** @see PackageSettingBase#resourcePathString */ 12696 abstract String getResourcePath(); 12697 12698 // Need installer lock especially for dex file removal. 12699 abstract void cleanUpResourcesLI(); 12700 abstract boolean doPostDeleteLI(boolean delete); 12701 12702 /** 12703 * Called before the source arguments are copied. This is used mostly 12704 * for MoveParams when it needs to read the source file to put it in the 12705 * destination. 12706 */ 12707 int doPreCopy() { 12708 return PackageManager.INSTALL_SUCCEEDED; 12709 } 12710 12711 /** 12712 * Called after the source arguments are copied. This is used mostly for 12713 * MoveParams when it needs to read the source file to put it in the 12714 * destination. 12715 */ 12716 int doPostCopy(int uid) { 12717 return PackageManager.INSTALL_SUCCEEDED; 12718 } 12719 12720 protected boolean isFwdLocked() { 12721 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12722 } 12723 12724 protected boolean isExternalAsec() { 12725 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12726 } 12727 12728 protected boolean isEphemeral() { 12729 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12730 } 12731 12732 UserHandle getUser() { 12733 return user; 12734 } 12735 } 12736 12737 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 12738 if (!allCodePaths.isEmpty()) { 12739 if (instructionSets == null) { 12740 throw new IllegalStateException("instructionSet == null"); 12741 } 12742 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 12743 for (String codePath : allCodePaths) { 12744 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 12745 try { 12746 mInstaller.rmdex(codePath, dexCodeInstructionSet); 12747 } catch (InstallerException ignored) { 12748 } 12749 } 12750 } 12751 } 12752 } 12753 12754 /** 12755 * Logic to handle installation of non-ASEC applications, including copying 12756 * and renaming logic. 12757 */ 12758 class FileInstallArgs extends InstallArgs { 12759 private File codeFile; 12760 private File resourceFile; 12761 12762 // Example topology: 12763 // /data/app/com.example/base.apk 12764 // /data/app/com.example/split_foo.apk 12765 // /data/app/com.example/lib/arm/libfoo.so 12766 // /data/app/com.example/lib/arm64/libfoo.so 12767 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 12768 12769 /** New install */ 12770 FileInstallArgs(InstallParams params) { 12771 super(params.origin, params.move, params.observer, params.installFlags, 12772 params.installerPackageName, params.volumeUuid, 12773 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 12774 params.grantedRuntimePermissions, 12775 params.traceMethod, params.traceCookie, params.certificates); 12776 if (isFwdLocked()) { 12777 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 12778 } 12779 } 12780 12781 /** Existing install */ 12782 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 12783 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 12784 null, null, null, 0, null /*certificates*/); 12785 this.codeFile = (codePath != null) ? new File(codePath) : null; 12786 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 12787 } 12788 12789 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12790 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 12791 try { 12792 return doCopyApk(imcs, temp); 12793 } finally { 12794 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12795 } 12796 } 12797 12798 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12799 if (origin.staged) { 12800 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 12801 codeFile = origin.file; 12802 resourceFile = origin.file; 12803 return PackageManager.INSTALL_SUCCEEDED; 12804 } 12805 12806 try { 12807 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12808 final File tempDir = 12809 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 12810 codeFile = tempDir; 12811 resourceFile = tempDir; 12812 } catch (IOException e) { 12813 Slog.w(TAG, "Failed to create copy file: " + e); 12814 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12815 } 12816 12817 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 12818 @Override 12819 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 12820 if (!FileUtils.isValidExtFilename(name)) { 12821 throw new IllegalArgumentException("Invalid filename: " + name); 12822 } 12823 try { 12824 final File file = new File(codeFile, name); 12825 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 12826 O_RDWR | O_CREAT, 0644); 12827 Os.chmod(file.getAbsolutePath(), 0644); 12828 return new ParcelFileDescriptor(fd); 12829 } catch (ErrnoException e) { 12830 throw new RemoteException("Failed to open: " + e.getMessage()); 12831 } 12832 } 12833 }; 12834 12835 int ret = PackageManager.INSTALL_SUCCEEDED; 12836 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 12837 if (ret != PackageManager.INSTALL_SUCCEEDED) { 12838 Slog.e(TAG, "Failed to copy package"); 12839 return ret; 12840 } 12841 12842 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 12843 NativeLibraryHelper.Handle handle = null; 12844 try { 12845 handle = NativeLibraryHelper.Handle.create(codeFile); 12846 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 12847 abiOverride); 12848 } catch (IOException e) { 12849 Slog.e(TAG, "Copying native libraries failed", e); 12850 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12851 } finally { 12852 IoUtils.closeQuietly(handle); 12853 } 12854 12855 return ret; 12856 } 12857 12858 int doPreInstall(int status) { 12859 if (status != PackageManager.INSTALL_SUCCEEDED) { 12860 cleanUp(); 12861 } 12862 return status; 12863 } 12864 12865 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 12866 if (status != PackageManager.INSTALL_SUCCEEDED) { 12867 cleanUp(); 12868 return false; 12869 } 12870 12871 final File targetDir = codeFile.getParentFile(); 12872 final File beforeCodeFile = codeFile; 12873 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 12874 12875 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 12876 try { 12877 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 12878 } catch (ErrnoException e) { 12879 Slog.w(TAG, "Failed to rename", e); 12880 return false; 12881 } 12882 12883 if (!SELinux.restoreconRecursive(afterCodeFile)) { 12884 Slog.w(TAG, "Failed to restorecon"); 12885 return false; 12886 } 12887 12888 // Reflect the rename internally 12889 codeFile = afterCodeFile; 12890 resourceFile = afterCodeFile; 12891 12892 // Reflect the rename in scanned details 12893 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 12894 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 12895 afterCodeFile, pkg.baseCodePath)); 12896 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 12897 afterCodeFile, pkg.splitCodePaths)); 12898 12899 // Reflect the rename in app info 12900 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 12901 pkg.setApplicationInfoCodePath(pkg.codePath); 12902 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 12903 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 12904 pkg.setApplicationInfoResourcePath(pkg.codePath); 12905 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 12906 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 12907 12908 return true; 12909 } 12910 12911 int doPostInstall(int status, int uid) { 12912 if (status != PackageManager.INSTALL_SUCCEEDED) { 12913 cleanUp(); 12914 } 12915 return status; 12916 } 12917 12918 @Override 12919 String getCodePath() { 12920 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 12921 } 12922 12923 @Override 12924 String getResourcePath() { 12925 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 12926 } 12927 12928 private boolean cleanUp() { 12929 if (codeFile == null || !codeFile.exists()) { 12930 return false; 12931 } 12932 12933 removeCodePathLI(codeFile); 12934 12935 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 12936 resourceFile.delete(); 12937 } 12938 12939 return true; 12940 } 12941 12942 void cleanUpResourcesLI() { 12943 // Try enumerating all code paths before deleting 12944 List<String> allCodePaths = Collections.EMPTY_LIST; 12945 if (codeFile != null && codeFile.exists()) { 12946 try { 12947 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 12948 allCodePaths = pkg.getAllCodePaths(); 12949 } catch (PackageParserException e) { 12950 // Ignored; we tried our best 12951 } 12952 } 12953 12954 cleanUp(); 12955 removeDexFiles(allCodePaths, instructionSets); 12956 } 12957 12958 boolean doPostDeleteLI(boolean delete) { 12959 // XXX err, shouldn't we respect the delete flag? 12960 cleanUpResourcesLI(); 12961 return true; 12962 } 12963 } 12964 12965 private boolean isAsecExternal(String cid) { 12966 final String asecPath = PackageHelper.getSdFilesystem(cid); 12967 return !asecPath.startsWith(mAsecInternalPath); 12968 } 12969 12970 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 12971 PackageManagerException { 12972 if (copyRet < 0) { 12973 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 12974 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 12975 throw new PackageManagerException(copyRet, message); 12976 } 12977 } 12978 } 12979 12980 /** 12981 * Extract the MountService "container ID" from the full code path of an 12982 * .apk. 12983 */ 12984 static String cidFromCodePath(String fullCodePath) { 12985 int eidx = fullCodePath.lastIndexOf("/"); 12986 String subStr1 = fullCodePath.substring(0, eidx); 12987 int sidx = subStr1.lastIndexOf("/"); 12988 return subStr1.substring(sidx+1, eidx); 12989 } 12990 12991 /** 12992 * Logic to handle installation of ASEC applications, including copying and 12993 * renaming logic. 12994 */ 12995 class AsecInstallArgs extends InstallArgs { 12996 static final String RES_FILE_NAME = "pkg.apk"; 12997 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 12998 12999 String cid; 13000 String packagePath; 13001 String resourcePath; 13002 13003 /** New install */ 13004 AsecInstallArgs(InstallParams params) { 13005 super(params.origin, params.move, params.observer, params.installFlags, 13006 params.installerPackageName, params.volumeUuid, 13007 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13008 params.grantedRuntimePermissions, 13009 params.traceMethod, params.traceCookie, params.certificates); 13010 } 13011 13012 /** Existing install */ 13013 AsecInstallArgs(String fullCodePath, String[] instructionSets, 13014 boolean isExternal, boolean isForwardLocked) { 13015 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 13016 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13017 instructionSets, null, null, null, 0, null /*certificates*/); 13018 // Hackily pretend we're still looking at a full code path 13019 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 13020 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 13021 } 13022 13023 // Extract cid from fullCodePath 13024 int eidx = fullCodePath.lastIndexOf("/"); 13025 String subStr1 = fullCodePath.substring(0, eidx); 13026 int sidx = subStr1.lastIndexOf("/"); 13027 cid = subStr1.substring(sidx+1, eidx); 13028 setMountPath(subStr1); 13029 } 13030 13031 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 13032 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 13033 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13034 instructionSets, null, null, null, 0, null /*certificates*/); 13035 this.cid = cid; 13036 setMountPath(PackageHelper.getSdDir(cid)); 13037 } 13038 13039 void createCopyFile() { 13040 cid = mInstallerService.allocateExternalStageCidLegacy(); 13041 } 13042 13043 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13044 if (origin.staged && origin.cid != null) { 13045 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 13046 cid = origin.cid; 13047 setMountPath(PackageHelper.getSdDir(cid)); 13048 return PackageManager.INSTALL_SUCCEEDED; 13049 } 13050 13051 if (temp) { 13052 createCopyFile(); 13053 } else { 13054 /* 13055 * Pre-emptively destroy the container since it's destroyed if 13056 * copying fails due to it existing anyway. 13057 */ 13058 PackageHelper.destroySdDir(cid); 13059 } 13060 13061 final String newMountPath = imcs.copyPackageToContainer( 13062 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 13063 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 13064 13065 if (newMountPath != null) { 13066 setMountPath(newMountPath); 13067 return PackageManager.INSTALL_SUCCEEDED; 13068 } else { 13069 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13070 } 13071 } 13072 13073 @Override 13074 String getCodePath() { 13075 return packagePath; 13076 } 13077 13078 @Override 13079 String getResourcePath() { 13080 return resourcePath; 13081 } 13082 13083 int doPreInstall(int status) { 13084 if (status != PackageManager.INSTALL_SUCCEEDED) { 13085 // Destroy container 13086 PackageHelper.destroySdDir(cid); 13087 } else { 13088 boolean mounted = PackageHelper.isContainerMounted(cid); 13089 if (!mounted) { 13090 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 13091 Process.SYSTEM_UID); 13092 if (newMountPath != null) { 13093 setMountPath(newMountPath); 13094 } else { 13095 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13096 } 13097 } 13098 } 13099 return status; 13100 } 13101 13102 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13103 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 13104 String newMountPath = null; 13105 if (PackageHelper.isContainerMounted(cid)) { 13106 // Unmount the container 13107 if (!PackageHelper.unMountSdDir(cid)) { 13108 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 13109 return false; 13110 } 13111 } 13112 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13113 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 13114 " which might be stale. Will try to clean up."); 13115 // Clean up the stale container and proceed to recreate. 13116 if (!PackageHelper.destroySdDir(newCacheId)) { 13117 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 13118 return false; 13119 } 13120 // Successfully cleaned up stale container. Try to rename again. 13121 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13122 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 13123 + " inspite of cleaning it up."); 13124 return false; 13125 } 13126 } 13127 if (!PackageHelper.isContainerMounted(newCacheId)) { 13128 Slog.w(TAG, "Mounting container " + newCacheId); 13129 newMountPath = PackageHelper.mountSdDir(newCacheId, 13130 getEncryptKey(), Process.SYSTEM_UID); 13131 } else { 13132 newMountPath = PackageHelper.getSdDir(newCacheId); 13133 } 13134 if (newMountPath == null) { 13135 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 13136 return false; 13137 } 13138 Log.i(TAG, "Succesfully renamed " + cid + 13139 " to " + newCacheId + 13140 " at new path: " + newMountPath); 13141 cid = newCacheId; 13142 13143 final File beforeCodeFile = new File(packagePath); 13144 setMountPath(newMountPath); 13145 final File afterCodeFile = new File(packagePath); 13146 13147 // Reflect the rename in scanned details 13148 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13149 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13150 afterCodeFile, pkg.baseCodePath)); 13151 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13152 afterCodeFile, pkg.splitCodePaths)); 13153 13154 // Reflect the rename in app info 13155 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13156 pkg.setApplicationInfoCodePath(pkg.codePath); 13157 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13158 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13159 pkg.setApplicationInfoResourcePath(pkg.codePath); 13160 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13161 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13162 13163 return true; 13164 } 13165 13166 private void setMountPath(String mountPath) { 13167 final File mountFile = new File(mountPath); 13168 13169 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 13170 if (monolithicFile.exists()) { 13171 packagePath = monolithicFile.getAbsolutePath(); 13172 if (isFwdLocked()) { 13173 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 13174 } else { 13175 resourcePath = packagePath; 13176 } 13177 } else { 13178 packagePath = mountFile.getAbsolutePath(); 13179 resourcePath = packagePath; 13180 } 13181 } 13182 13183 int doPostInstall(int status, int uid) { 13184 if (status != PackageManager.INSTALL_SUCCEEDED) { 13185 cleanUp(); 13186 } else { 13187 final int groupOwner; 13188 final String protectedFile; 13189 if (isFwdLocked()) { 13190 groupOwner = UserHandle.getSharedAppGid(uid); 13191 protectedFile = RES_FILE_NAME; 13192 } else { 13193 groupOwner = -1; 13194 protectedFile = null; 13195 } 13196 13197 if (uid < Process.FIRST_APPLICATION_UID 13198 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 13199 Slog.e(TAG, "Failed to finalize " + cid); 13200 PackageHelper.destroySdDir(cid); 13201 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13202 } 13203 13204 boolean mounted = PackageHelper.isContainerMounted(cid); 13205 if (!mounted) { 13206 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 13207 } 13208 } 13209 return status; 13210 } 13211 13212 private void cleanUp() { 13213 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 13214 13215 // Destroy secure container 13216 PackageHelper.destroySdDir(cid); 13217 } 13218 13219 private List<String> getAllCodePaths() { 13220 final File codeFile = new File(getCodePath()); 13221 if (codeFile != null && codeFile.exists()) { 13222 try { 13223 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13224 return pkg.getAllCodePaths(); 13225 } catch (PackageParserException e) { 13226 // Ignored; we tried our best 13227 } 13228 } 13229 return Collections.EMPTY_LIST; 13230 } 13231 13232 void cleanUpResourcesLI() { 13233 // Enumerate all code paths before deleting 13234 cleanUpResourcesLI(getAllCodePaths()); 13235 } 13236 13237 private void cleanUpResourcesLI(List<String> allCodePaths) { 13238 cleanUp(); 13239 removeDexFiles(allCodePaths, instructionSets); 13240 } 13241 13242 String getPackageName() { 13243 return getAsecPackageName(cid); 13244 } 13245 13246 boolean doPostDeleteLI(boolean delete) { 13247 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 13248 final List<String> allCodePaths = getAllCodePaths(); 13249 boolean mounted = PackageHelper.isContainerMounted(cid); 13250 if (mounted) { 13251 // Unmount first 13252 if (PackageHelper.unMountSdDir(cid)) { 13253 mounted = false; 13254 } 13255 } 13256 if (!mounted && delete) { 13257 cleanUpResourcesLI(allCodePaths); 13258 } 13259 return !mounted; 13260 } 13261 13262 @Override 13263 int doPreCopy() { 13264 if (isFwdLocked()) { 13265 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 13266 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 13267 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13268 } 13269 } 13270 13271 return PackageManager.INSTALL_SUCCEEDED; 13272 } 13273 13274 @Override 13275 int doPostCopy(int uid) { 13276 if (isFwdLocked()) { 13277 if (uid < Process.FIRST_APPLICATION_UID 13278 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 13279 RES_FILE_NAME)) { 13280 Slog.e(TAG, "Failed to finalize " + cid); 13281 PackageHelper.destroySdDir(cid); 13282 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13283 } 13284 } 13285 13286 return PackageManager.INSTALL_SUCCEEDED; 13287 } 13288 } 13289 13290 /** 13291 * Logic to handle movement of existing installed applications. 13292 */ 13293 class MoveInstallArgs extends InstallArgs { 13294 private File codeFile; 13295 private File resourceFile; 13296 13297 /** New install */ 13298 MoveInstallArgs(InstallParams params) { 13299 super(params.origin, params.move, params.observer, params.installFlags, 13300 params.installerPackageName, params.volumeUuid, 13301 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13302 params.grantedRuntimePermissions, 13303 params.traceMethod, params.traceCookie, params.certificates); 13304 } 13305 13306 int copyApk(IMediaContainerService imcs, boolean temp) { 13307 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 13308 + move.fromUuid + " to " + move.toUuid); 13309 synchronized (mInstaller) { 13310 try { 13311 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 13312 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 13313 } catch (InstallerException e) { 13314 Slog.w(TAG, "Failed to move app", e); 13315 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13316 } 13317 } 13318 13319 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 13320 resourceFile = codeFile; 13321 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 13322 13323 return PackageManager.INSTALL_SUCCEEDED; 13324 } 13325 13326 int doPreInstall(int status) { 13327 if (status != PackageManager.INSTALL_SUCCEEDED) { 13328 cleanUp(move.toUuid); 13329 } 13330 return status; 13331 } 13332 13333 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13334 if (status != PackageManager.INSTALL_SUCCEEDED) { 13335 cleanUp(move.toUuid); 13336 return false; 13337 } 13338 13339 // Reflect the move in app info 13340 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13341 pkg.setApplicationInfoCodePath(pkg.codePath); 13342 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13343 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13344 pkg.setApplicationInfoResourcePath(pkg.codePath); 13345 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13346 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13347 13348 return true; 13349 } 13350 13351 int doPostInstall(int status, int uid) { 13352 if (status == PackageManager.INSTALL_SUCCEEDED) { 13353 cleanUp(move.fromUuid); 13354 } else { 13355 cleanUp(move.toUuid); 13356 } 13357 return status; 13358 } 13359 13360 @Override 13361 String getCodePath() { 13362 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13363 } 13364 13365 @Override 13366 String getResourcePath() { 13367 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13368 } 13369 13370 private boolean cleanUp(String volumeUuid) { 13371 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 13372 move.dataAppName); 13373 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 13374 synchronized (mInstallLock) { 13375 // Clean up both app data and code 13376 // All package moves are frozen until finished 13377 try { 13378 mInstaller.destroyAppData(volumeUuid, move.packageName, UserHandle.USER_ALL, 13379 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 13380 } catch (InstallerException e) { 13381 Slog.w(TAG, String.valueOf(e)); 13382 } 13383 removeCodePathLI(codeFile); 13384 } 13385 return true; 13386 } 13387 13388 void cleanUpResourcesLI() { 13389 throw new UnsupportedOperationException(); 13390 } 13391 13392 boolean doPostDeleteLI(boolean delete) { 13393 throw new UnsupportedOperationException(); 13394 } 13395 } 13396 13397 static String getAsecPackageName(String packageCid) { 13398 int idx = packageCid.lastIndexOf("-"); 13399 if (idx == -1) { 13400 return packageCid; 13401 } 13402 return packageCid.substring(0, idx); 13403 } 13404 13405 // Utility method used to create code paths based on package name and available index. 13406 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 13407 String idxStr = ""; 13408 int idx = 1; 13409 // Fall back to default value of idx=1 if prefix is not 13410 // part of oldCodePath 13411 if (oldCodePath != null) { 13412 String subStr = oldCodePath; 13413 // Drop the suffix right away 13414 if (suffix != null && subStr.endsWith(suffix)) { 13415 subStr = subStr.substring(0, subStr.length() - suffix.length()); 13416 } 13417 // If oldCodePath already contains prefix find out the 13418 // ending index to either increment or decrement. 13419 int sidx = subStr.lastIndexOf(prefix); 13420 if (sidx != -1) { 13421 subStr = subStr.substring(sidx + prefix.length()); 13422 if (subStr != null) { 13423 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 13424 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 13425 } 13426 try { 13427 idx = Integer.parseInt(subStr); 13428 if (idx <= 1) { 13429 idx++; 13430 } else { 13431 idx--; 13432 } 13433 } catch(NumberFormatException e) { 13434 } 13435 } 13436 } 13437 } 13438 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 13439 return prefix + idxStr; 13440 } 13441 13442 private File getNextCodePath(File targetDir, String packageName) { 13443 int suffix = 1; 13444 File result; 13445 do { 13446 result = new File(targetDir, packageName + "-" + suffix); 13447 suffix++; 13448 } while (result.exists()); 13449 return result; 13450 } 13451 13452 // Utility method that returns the relative package path with respect 13453 // to the installation directory. Like say for /data/data/com.test-1.apk 13454 // string com.test-1 is returned. 13455 static String deriveCodePathName(String codePath) { 13456 if (codePath == null) { 13457 return null; 13458 } 13459 final File codeFile = new File(codePath); 13460 final String name = codeFile.getName(); 13461 if (codeFile.isDirectory()) { 13462 return name; 13463 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 13464 final int lastDot = name.lastIndexOf('.'); 13465 return name.substring(0, lastDot); 13466 } else { 13467 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 13468 return null; 13469 } 13470 } 13471 13472 static class PackageInstalledInfo { 13473 String name; 13474 int uid; 13475 // The set of users that originally had this package installed. 13476 int[] origUsers; 13477 // The set of users that now have this package installed. 13478 int[] newUsers; 13479 PackageParser.Package pkg; 13480 int returnCode; 13481 String returnMsg; 13482 PackageRemovedInfo removedInfo; 13483 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 13484 13485 public void setError(int code, String msg) { 13486 setReturnCode(code); 13487 setReturnMessage(msg); 13488 Slog.w(TAG, msg); 13489 } 13490 13491 public void setError(String msg, PackageParserException e) { 13492 setReturnCode(e.error); 13493 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13494 Slog.w(TAG, msg, e); 13495 } 13496 13497 public void setError(String msg, PackageManagerException e) { 13498 returnCode = e.error; 13499 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13500 Slog.w(TAG, msg, e); 13501 } 13502 13503 public void setReturnCode(int returnCode) { 13504 this.returnCode = returnCode; 13505 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13506 for (int i = 0; i < childCount; i++) { 13507 addedChildPackages.valueAt(i).returnCode = returnCode; 13508 } 13509 } 13510 13511 private void setReturnMessage(String returnMsg) { 13512 this.returnMsg = returnMsg; 13513 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13514 for (int i = 0; i < childCount; i++) { 13515 addedChildPackages.valueAt(i).returnMsg = returnMsg; 13516 } 13517 } 13518 13519 // In some error cases we want to convey more info back to the observer 13520 String origPackage; 13521 String origPermission; 13522 } 13523 13524 /* 13525 * Install a non-existing package. 13526 */ 13527 private void installNewPackageLIF(PackageParser.Package pkg, int parseFlags, int scanFlags, 13528 UserHandle user, String installerPackageName, String volumeUuid, 13529 PackageInstalledInfo res) { 13530 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 13531 13532 // Remember this for later, in case we need to rollback this install 13533 String pkgName = pkg.packageName; 13534 13535 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 13536 13537 synchronized(mPackages) { 13538 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 13539 // A package with the same name is already installed, though 13540 // it has been renamed to an older name. The package we 13541 // are trying to install should be installed as an update to 13542 // the existing one, but that has not been requested, so bail. 13543 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13544 + " without first uninstalling package running as " 13545 + mSettings.mRenamedPackages.get(pkgName)); 13546 return; 13547 } 13548 if (mPackages.containsKey(pkgName)) { 13549 // Don't allow installation over an existing package with the same name. 13550 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13551 + " without first uninstalling."); 13552 return; 13553 } 13554 } 13555 13556 try { 13557 PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 13558 System.currentTimeMillis(), user); 13559 13560 updateSettingsLI(newPackage, installerPackageName, null, res, user); 13561 13562 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13563 prepareAppDataAfterInstallLIF(newPackage); 13564 13565 } else { 13566 // Remove package from internal structures, but keep around any 13567 // data that might have already existed 13568 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 13569 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 13570 } 13571 } catch (PackageManagerException e) { 13572 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13573 } 13574 13575 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13576 } 13577 13578 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 13579 // Can't rotate keys during boot or if sharedUser. 13580 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 13581 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 13582 return false; 13583 } 13584 // app is using upgradeKeySets; make sure all are valid 13585 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13586 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 13587 for (int i = 0; i < upgradeKeySets.length; i++) { 13588 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 13589 Slog.wtf(TAG, "Package " 13590 + (oldPs.name != null ? oldPs.name : "<null>") 13591 + " contains upgrade-key-set reference to unknown key-set: " 13592 + upgradeKeySets[i] 13593 + " reverting to signatures check."); 13594 return false; 13595 } 13596 } 13597 return true; 13598 } 13599 13600 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 13601 // Upgrade keysets are being used. Determine if new package has a superset of the 13602 // required keys. 13603 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 13604 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13605 for (int i = 0; i < upgradeKeySets.length; i++) { 13606 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 13607 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 13608 return true; 13609 } 13610 } 13611 return false; 13612 } 13613 13614 private void replacePackageLIF(PackageParser.Package pkg, int parseFlags, int scanFlags, 13615 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 13616 final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 13617 13618 final PackageParser.Package oldPackage; 13619 final String pkgName = pkg.packageName; 13620 final int[] allUsers; 13621 13622 // First find the old package info and check signatures 13623 synchronized(mPackages) { 13624 oldPackage = mPackages.get(pkgName); 13625 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 13626 if (isEphemeral && !oldIsEphemeral) { 13627 // can't downgrade from full to ephemeral 13628 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 13629 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 13630 return; 13631 } 13632 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 13633 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13634 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 13635 if (!checkUpgradeKeySetLP(ps, pkg)) { 13636 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13637 "New package not signed by keys specified by upgrade-keysets: " 13638 + pkgName); 13639 return; 13640 } 13641 } else { 13642 // default to original signature matching 13643 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 13644 != PackageManager.SIGNATURE_MATCH) { 13645 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13646 "New package has a different signature: " + pkgName); 13647 return; 13648 } 13649 } 13650 13651 // In case of rollback, remember per-user/profile install state 13652 allUsers = sUserManager.getUserIds(); 13653 } 13654 13655 // Update what is removed 13656 res.removedInfo = new PackageRemovedInfo(); 13657 res.removedInfo.uid = oldPackage.applicationInfo.uid; 13658 res.removedInfo.removedPackage = oldPackage.packageName; 13659 res.removedInfo.isUpdate = true; 13660 final int childCount = (oldPackage.childPackages != null) 13661 ? oldPackage.childPackages.size() : 0; 13662 for (int i = 0; i < childCount; i++) { 13663 boolean childPackageUpdated = false; 13664 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 13665 if (res.addedChildPackages != null) { 13666 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 13667 if (childRes != null) { 13668 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 13669 childRes.removedInfo.removedPackage = childPkg.packageName; 13670 childRes.removedInfo.isUpdate = true; 13671 childPackageUpdated = true; 13672 } 13673 } 13674 if (!childPackageUpdated) { 13675 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 13676 childRemovedRes.removedPackage = childPkg.packageName; 13677 childRemovedRes.isUpdate = false; 13678 childRemovedRes.dataRemoved = true; 13679 synchronized (mPackages) { 13680 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 13681 if (childPs != null) { 13682 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 13683 } 13684 } 13685 if (res.removedInfo.removedChildPackages == null) { 13686 res.removedInfo.removedChildPackages = new ArrayMap<>(); 13687 } 13688 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 13689 } 13690 } 13691 13692 boolean sysPkg = (isSystemApp(oldPackage)); 13693 if (sysPkg) { 13694 replaceSystemPackageLIF(oldPackage, pkg, parseFlags, scanFlags, 13695 user, allUsers, installerPackageName, res); 13696 } else { 13697 replaceNonSystemPackageLIF(oldPackage, pkg, parseFlags, scanFlags, 13698 user, allUsers, installerPackageName, res); 13699 } 13700 } 13701 13702 public List<String> getPreviousCodePaths(String packageName) { 13703 final PackageSetting ps = mSettings.mPackages.get(packageName); 13704 final List<String> result = new ArrayList<String>(); 13705 if (ps != null && ps.oldCodePaths != null) { 13706 result.addAll(ps.oldCodePaths); 13707 } 13708 return result; 13709 } 13710 13711 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 13712 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 13713 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 13714 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 13715 + deletedPackage); 13716 13717 String pkgName = deletedPackage.packageName; 13718 boolean deletedPkg = true; 13719 boolean addedPkg = false; 13720 boolean updatedSettings = false; 13721 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 13722 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 13723 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 13724 13725 final long origUpdateTime = (pkg.mExtras != null) 13726 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 13727 13728 // First delete the existing package while retaining the data directory 13729 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 13730 res.removedInfo, true, pkg)) { 13731 // If the existing package wasn't successfully deleted 13732 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 13733 deletedPkg = false; 13734 } else { 13735 // Successfully deleted the old package; proceed with replace. 13736 13737 // If deleted package lived in a container, give users a chance to 13738 // relinquish resources before killing. 13739 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 13740 if (DEBUG_INSTALL) { 13741 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 13742 } 13743 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 13744 final ArrayList<String> pkgList = new ArrayList<String>(1); 13745 pkgList.add(deletedPackage.applicationInfo.packageName); 13746 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 13747 } 13748 13749 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 13750 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 13751 clearAppProfilesLIF(pkg); 13752 13753 try { 13754 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, 13755 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 13756 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 13757 13758 // Update the in-memory copy of the previous code paths. 13759 PackageSetting ps = mSettings.mPackages.get(pkgName); 13760 if (!killApp) { 13761 if (ps.oldCodePaths == null) { 13762 ps.oldCodePaths = new ArraySet<>(); 13763 } 13764 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 13765 if (deletedPackage.splitCodePaths != null) { 13766 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 13767 } 13768 } else { 13769 ps.oldCodePaths = null; 13770 } 13771 if (ps.childPackageNames != null) { 13772 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 13773 final String childPkgName = ps.childPackageNames.get(i); 13774 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 13775 childPs.oldCodePaths = ps.oldCodePaths; 13776 } 13777 } 13778 prepareAppDataAfterInstallLIF(newPackage); 13779 addedPkg = true; 13780 } catch (PackageManagerException e) { 13781 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13782 } 13783 } 13784 13785 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 13786 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 13787 13788 // Revert all internal state mutations and added folders for the failed install 13789 if (addedPkg) { 13790 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 13791 res.removedInfo, true, null); 13792 } 13793 13794 // Restore the old package 13795 if (deletedPkg) { 13796 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 13797 File restoreFile = new File(deletedPackage.codePath); 13798 // Parse old package 13799 boolean oldExternal = isExternal(deletedPackage); 13800 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 13801 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 13802 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 13803 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 13804 try { 13805 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 13806 null); 13807 } catch (PackageManagerException e) { 13808 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 13809 + e.getMessage()); 13810 return; 13811 } 13812 13813 synchronized (mPackages) { 13814 // Ensure the installer package name up to date 13815 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 13816 13817 // Update permissions for restored package 13818 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 13819 13820 mSettings.writeLPr(); 13821 } 13822 13823 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 13824 } 13825 } else { 13826 synchronized (mPackages) { 13827 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 13828 if (ps != null) { 13829 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 13830 if (res.removedInfo.removedChildPackages != null) { 13831 final int childCount = res.removedInfo.removedChildPackages.size(); 13832 // Iterate in reverse as we may modify the collection 13833 for (int i = childCount - 1; i >= 0; i--) { 13834 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 13835 if (res.addedChildPackages.containsKey(childPackageName)) { 13836 res.removedInfo.removedChildPackages.removeAt(i); 13837 } else { 13838 PackageRemovedInfo childInfo = res.removedInfo 13839 .removedChildPackages.valueAt(i); 13840 childInfo.removedForAllUsers = mPackages.get( 13841 childInfo.removedPackage) == null; 13842 } 13843 } 13844 } 13845 } 13846 } 13847 } 13848 } 13849 13850 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 13851 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 13852 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 13853 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 13854 + ", old=" + deletedPackage); 13855 13856 final boolean disabledSystem; 13857 13858 // Set the system/privileged flags as needed 13859 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 13860 if ((deletedPackage.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 13861 != 0) { 13862 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 13863 } 13864 13865 // Remove existing system package 13866 removePackageLI(deletedPackage, true); 13867 13868 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 13869 if (!disabledSystem) { 13870 // We didn't need to disable the .apk as a current system package, 13871 // which means we are replacing another update that is already 13872 // installed. We need to make sure to delete the older one's .apk. 13873 res.removedInfo.args = createInstallArgsForExisting(0, 13874 deletedPackage.applicationInfo.getCodePath(), 13875 deletedPackage.applicationInfo.getResourcePath(), 13876 getAppDexInstructionSets(deletedPackage.applicationInfo)); 13877 } else { 13878 res.removedInfo.args = null; 13879 } 13880 13881 // Successfully disabled the old package. Now proceed with re-installation 13882 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 13883 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 13884 clearAppProfilesLIF(pkg); 13885 13886 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 13887 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 13888 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 13889 13890 PackageParser.Package newPackage = null; 13891 try { 13892 // Add the package to the internal data structures 13893 newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user); 13894 13895 // Set the update and install times 13896 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 13897 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 13898 System.currentTimeMillis()); 13899 13900 // Check for shared user id changes 13901 String invalidPackageName = getParentOrChildPackageChangedSharedUser( 13902 deletedPackage, newPackage); 13903 if (invalidPackageName != null) { 13904 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 13905 "Forbidding shared user change from " + deletedPkgSetting.sharedUser 13906 + " to " + invalidPackageName); 13907 } 13908 13909 // Update the package dynamic state if succeeded 13910 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13911 // Now that the install succeeded make sure we remove data 13912 // directories for any child package the update removed. 13913 final int deletedChildCount = (deletedPackage.childPackages != null) 13914 ? deletedPackage.childPackages.size() : 0; 13915 final int newChildCount = (newPackage.childPackages != null) 13916 ? newPackage.childPackages.size() : 0; 13917 for (int i = 0; i < deletedChildCount; i++) { 13918 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 13919 boolean childPackageDeleted = true; 13920 for (int j = 0; j < newChildCount; j++) { 13921 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 13922 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 13923 childPackageDeleted = false; 13924 break; 13925 } 13926 } 13927 if (childPackageDeleted) { 13928 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 13929 deletedChildPkg.packageName); 13930 if (ps != null && res.removedInfo.removedChildPackages != null) { 13931 PackageRemovedInfo removedChildRes = res.removedInfo 13932 .removedChildPackages.get(deletedChildPkg.packageName); 13933 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 13934 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 13935 } 13936 } 13937 } 13938 13939 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 13940 prepareAppDataAfterInstallLIF(newPackage); 13941 } 13942 } catch (PackageManagerException e) { 13943 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 13944 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13945 } 13946 13947 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 13948 // Re installation failed. Restore old information 13949 // Remove new pkg information 13950 if (newPackage != null) { 13951 removeInstalledPackageLI(newPackage, true); 13952 } 13953 // Add back the old system package 13954 try { 13955 scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 13956 } catch (PackageManagerException e) { 13957 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 13958 } 13959 13960 synchronized (mPackages) { 13961 if (disabledSystem) { 13962 enableSystemPackageLPw(deletedPackage); 13963 } 13964 13965 // Ensure the installer package name up to date 13966 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 13967 13968 // Update permissions for restored package 13969 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 13970 13971 mSettings.writeLPr(); 13972 } 13973 13974 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 13975 + " after failed upgrade"); 13976 } 13977 } 13978 13979 /** 13980 * Checks whether the parent or any of the child packages have a change shared 13981 * user. For a package to be a valid update the shred users of the parent and 13982 * the children should match. We may later support changing child shared users. 13983 * @param oldPkg The updated package. 13984 * @param newPkg The update package. 13985 * @return The shared user that change between the versions. 13986 */ 13987 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 13988 PackageParser.Package newPkg) { 13989 // Check parent shared user 13990 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 13991 return newPkg.packageName; 13992 } 13993 // Check child shared users 13994 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 13995 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 13996 for (int i = 0; i < newChildCount; i++) { 13997 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 13998 // If this child was present, did it have the same shared user? 13999 for (int j = 0; j < oldChildCount; j++) { 14000 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 14001 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 14002 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 14003 return newChildPkg.packageName; 14004 } 14005 } 14006 } 14007 return null; 14008 } 14009 14010 private void removeNativeBinariesLI(PackageSetting ps) { 14011 // Remove the lib path for the parent package 14012 if (ps != null) { 14013 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 14014 // Remove the lib path for the child packages 14015 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 14016 for (int i = 0; i < childCount; i++) { 14017 PackageSetting childPs = null; 14018 synchronized (mPackages) { 14019 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 14020 } 14021 if (childPs != null) { 14022 NativeLibraryHelper.removeNativeBinariesLI(childPs 14023 .legacyNativeLibraryPathString); 14024 } 14025 } 14026 } 14027 } 14028 14029 private void enableSystemPackageLPw(PackageParser.Package pkg) { 14030 // Enable the parent package 14031 mSettings.enableSystemPackageLPw(pkg.packageName); 14032 // Enable the child packages 14033 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14034 for (int i = 0; i < childCount; i++) { 14035 PackageParser.Package childPkg = pkg.childPackages.get(i); 14036 mSettings.enableSystemPackageLPw(childPkg.packageName); 14037 } 14038 } 14039 14040 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 14041 PackageParser.Package newPkg) { 14042 // Disable the parent package (parent always replaced) 14043 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 14044 // Disable the child packages 14045 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14046 for (int i = 0; i < childCount; i++) { 14047 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 14048 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 14049 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 14050 } 14051 return disabled; 14052 } 14053 14054 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 14055 String installerPackageName) { 14056 // Enable the parent package 14057 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 14058 // Enable the child packages 14059 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14060 for (int i = 0; i < childCount; i++) { 14061 PackageParser.Package childPkg = pkg.childPackages.get(i); 14062 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 14063 } 14064 } 14065 14066 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 14067 // Collect all used permissions in the UID 14068 ArraySet<String> usedPermissions = new ArraySet<>(); 14069 final int packageCount = su.packages.size(); 14070 for (int i = 0; i < packageCount; i++) { 14071 PackageSetting ps = su.packages.valueAt(i); 14072 if (ps.pkg == null) { 14073 continue; 14074 } 14075 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 14076 for (int j = 0; j < requestedPermCount; j++) { 14077 String permission = ps.pkg.requestedPermissions.get(j); 14078 BasePermission bp = mSettings.mPermissions.get(permission); 14079 if (bp != null) { 14080 usedPermissions.add(permission); 14081 } 14082 } 14083 } 14084 14085 PermissionsState permissionsState = su.getPermissionsState(); 14086 // Prune install permissions 14087 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 14088 final int installPermCount = installPermStates.size(); 14089 for (int i = installPermCount - 1; i >= 0; i--) { 14090 PermissionState permissionState = installPermStates.get(i); 14091 if (!usedPermissions.contains(permissionState.getName())) { 14092 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14093 if (bp != null) { 14094 permissionsState.revokeInstallPermission(bp); 14095 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 14096 PackageManager.MASK_PERMISSION_FLAGS, 0); 14097 } 14098 } 14099 } 14100 14101 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 14102 14103 // Prune runtime permissions 14104 for (int userId : allUserIds) { 14105 List<PermissionState> runtimePermStates = permissionsState 14106 .getRuntimePermissionStates(userId); 14107 final int runtimePermCount = runtimePermStates.size(); 14108 for (int i = runtimePermCount - 1; i >= 0; i--) { 14109 PermissionState permissionState = runtimePermStates.get(i); 14110 if (!usedPermissions.contains(permissionState.getName())) { 14111 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14112 if (bp != null) { 14113 permissionsState.revokeRuntimePermission(bp, userId); 14114 permissionsState.updatePermissionFlags(bp, userId, 14115 PackageManager.MASK_PERMISSION_FLAGS, 0); 14116 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 14117 runtimePermissionChangedUserIds, userId); 14118 } 14119 } 14120 } 14121 } 14122 14123 return runtimePermissionChangedUserIds; 14124 } 14125 14126 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 14127 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 14128 // Update the parent package setting 14129 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 14130 res, user); 14131 // Update the child packages setting 14132 final int childCount = (newPackage.childPackages != null) 14133 ? newPackage.childPackages.size() : 0; 14134 for (int i = 0; i < childCount; i++) { 14135 PackageParser.Package childPackage = newPackage.childPackages.get(i); 14136 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 14137 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 14138 childRes.origUsers, childRes, user); 14139 } 14140 } 14141 14142 private void updateSettingsInternalLI(PackageParser.Package newPackage, 14143 String installerPackageName, int[] allUsers, int[] installedForUsers, 14144 PackageInstalledInfo res, UserHandle user) { 14145 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 14146 14147 String pkgName = newPackage.packageName; 14148 synchronized (mPackages) { 14149 //write settings. the installStatus will be incomplete at this stage. 14150 //note that the new package setting would have already been 14151 //added to mPackages. It hasn't been persisted yet. 14152 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 14153 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14154 mSettings.writeLPr(); 14155 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14156 } 14157 14158 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 14159 synchronized (mPackages) { 14160 updatePermissionsLPw(newPackage.packageName, newPackage, 14161 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 14162 ? UPDATE_PERMISSIONS_ALL : 0)); 14163 // For system-bundled packages, we assume that installing an upgraded version 14164 // of the package implies that the user actually wants to run that new code, 14165 // so we enable the package. 14166 PackageSetting ps = mSettings.mPackages.get(pkgName); 14167 final int userId = user.getIdentifier(); 14168 if (ps != null) { 14169 if (isSystemApp(newPackage)) { 14170 if (DEBUG_INSTALL) { 14171 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 14172 } 14173 // Enable system package for requested users 14174 if (res.origUsers != null) { 14175 for (int origUserId : res.origUsers) { 14176 if (userId == UserHandle.USER_ALL || userId == origUserId) { 14177 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 14178 origUserId, installerPackageName); 14179 } 14180 } 14181 } 14182 // Also convey the prior install/uninstall state 14183 if (allUsers != null && installedForUsers != null) { 14184 for (int currentUserId : allUsers) { 14185 final boolean installed = ArrayUtils.contains( 14186 installedForUsers, currentUserId); 14187 if (DEBUG_INSTALL) { 14188 Slog.d(TAG, " user " + currentUserId + " => " + installed); 14189 } 14190 ps.setInstalled(installed, currentUserId); 14191 } 14192 // these install state changes will be persisted in the 14193 // upcoming call to mSettings.writeLPr(). 14194 } 14195 } 14196 // It's implied that when a user requests installation, they want the app to be 14197 // installed and enabled. 14198 if (userId != UserHandle.USER_ALL) { 14199 ps.setInstalled(true, userId); 14200 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 14201 } 14202 } 14203 res.name = pkgName; 14204 res.uid = newPackage.applicationInfo.uid; 14205 res.pkg = newPackage; 14206 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 14207 mSettings.setInstallerPackageName(pkgName, installerPackageName); 14208 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14209 //to update install status 14210 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14211 mSettings.writeLPr(); 14212 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14213 } 14214 14215 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14216 } 14217 14218 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 14219 try { 14220 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 14221 installPackageLI(args, res); 14222 } finally { 14223 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14224 } 14225 } 14226 14227 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 14228 final int installFlags = args.installFlags; 14229 final String installerPackageName = args.installerPackageName; 14230 final String volumeUuid = args.volumeUuid; 14231 final File tmpPackageFile = new File(args.getCodePath()); 14232 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 14233 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 14234 || (args.volumeUuid != null)); 14235 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 14236 boolean replace = false; 14237 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 14238 if (args.move != null) { 14239 // moving a complete application; perform an initial scan on the new install location 14240 scanFlags |= SCAN_INITIAL; 14241 } 14242 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 14243 scanFlags |= SCAN_DONT_KILL_APP; 14244 } 14245 14246 // Result object to be returned 14247 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14248 14249 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 14250 14251 // Sanity check 14252 if (ephemeral && (forwardLocked || onExternal)) { 14253 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 14254 + " external=" + onExternal); 14255 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14256 return; 14257 } 14258 14259 // Retrieve PackageSettings and parse package 14260 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 14261 | PackageParser.PARSE_ENFORCE_CODE 14262 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 14263 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 14264 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0); 14265 PackageParser pp = new PackageParser(); 14266 pp.setSeparateProcesses(mSeparateProcesses); 14267 pp.setDisplayMetrics(mMetrics); 14268 14269 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 14270 final PackageParser.Package pkg; 14271 try { 14272 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 14273 } catch (PackageParserException e) { 14274 res.setError("Failed parse during installPackageLI", e); 14275 return; 14276 } finally { 14277 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14278 } 14279 14280 // If we are installing a clustered package add results for the children 14281 if (pkg.childPackages != null) { 14282 synchronized (mPackages) { 14283 final int childCount = pkg.childPackages.size(); 14284 for (int i = 0; i < childCount; i++) { 14285 PackageParser.Package childPkg = pkg.childPackages.get(i); 14286 PackageInstalledInfo childRes = new PackageInstalledInfo(); 14287 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14288 childRes.pkg = childPkg; 14289 childRes.name = childPkg.packageName; 14290 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14291 if (childPs != null) { 14292 childRes.origUsers = childPs.queryInstalledUsers( 14293 sUserManager.getUserIds(), true); 14294 } 14295 if ((mPackages.containsKey(childPkg.packageName))) { 14296 childRes.removedInfo = new PackageRemovedInfo(); 14297 childRes.removedInfo.removedPackage = childPkg.packageName; 14298 } 14299 if (res.addedChildPackages == null) { 14300 res.addedChildPackages = new ArrayMap<>(); 14301 } 14302 res.addedChildPackages.put(childPkg.packageName, childRes); 14303 } 14304 } 14305 } 14306 14307 // If package doesn't declare API override, mark that we have an install 14308 // time CPU ABI override. 14309 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 14310 pkg.cpuAbiOverride = args.abiOverride; 14311 } 14312 14313 String pkgName = res.name = pkg.packageName; 14314 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 14315 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 14316 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 14317 return; 14318 } 14319 } 14320 14321 try { 14322 // either use what we've been given or parse directly from the APK 14323 if (args.certificates != null) { 14324 try { 14325 PackageParser.populateCertificates(pkg, args.certificates); 14326 } catch (PackageParserException e) { 14327 // there was something wrong with the certificates we were given; 14328 // try to pull them from the APK 14329 PackageParser.collectCertificates(pkg, parseFlags); 14330 } 14331 } else { 14332 PackageParser.collectCertificates(pkg, parseFlags); 14333 } 14334 } catch (PackageParserException e) { 14335 res.setError("Failed collect during installPackageLI", e); 14336 return; 14337 } 14338 14339 // Get rid of all references to package scan path via parser. 14340 pp = null; 14341 String oldCodePath = null; 14342 boolean systemApp = false; 14343 synchronized (mPackages) { 14344 // Check if installing already existing package 14345 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14346 String oldName = mSettings.mRenamedPackages.get(pkgName); 14347 if (pkg.mOriginalPackages != null 14348 && pkg.mOriginalPackages.contains(oldName) 14349 && mPackages.containsKey(oldName)) { 14350 // This package is derived from an original package, 14351 // and this device has been updating from that original 14352 // name. We must continue using the original name, so 14353 // rename the new package here. 14354 pkg.setPackageName(oldName); 14355 pkgName = pkg.packageName; 14356 replace = true; 14357 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 14358 + oldName + " pkgName=" + pkgName); 14359 } else if (mPackages.containsKey(pkgName)) { 14360 // This package, under its official name, already exists 14361 // on the device; we should replace it. 14362 replace = true; 14363 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 14364 } 14365 14366 // Child packages are installed through the parent package 14367 if (pkg.parentPackage != null) { 14368 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14369 "Package " + pkg.packageName + " is child of package " 14370 + pkg.parentPackage.parentPackage + ". Child packages " 14371 + "can be updated only through the parent package."); 14372 return; 14373 } 14374 14375 if (replace) { 14376 // Prevent apps opting out from runtime permissions 14377 PackageParser.Package oldPackage = mPackages.get(pkgName); 14378 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 14379 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 14380 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 14381 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 14382 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 14383 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 14384 + " doesn't support runtime permissions but the old" 14385 + " target SDK " + oldTargetSdk + " does."); 14386 return; 14387 } 14388 14389 // Prevent installing of child packages 14390 if (oldPackage.parentPackage != null) { 14391 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14392 "Package " + pkg.packageName + " is child of package " 14393 + oldPackage.parentPackage + ". Child packages " 14394 + "can be updated only through the parent package."); 14395 return; 14396 } 14397 } 14398 } 14399 14400 PackageSetting ps = mSettings.mPackages.get(pkgName); 14401 if (ps != null) { 14402 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 14403 14404 // Quick sanity check that we're signed correctly if updating; 14405 // we'll check this again later when scanning, but we want to 14406 // bail early here before tripping over redefined permissions. 14407 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14408 if (!checkUpgradeKeySetLP(ps, pkg)) { 14409 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 14410 + pkg.packageName + " upgrade keys do not match the " 14411 + "previously installed version"); 14412 return; 14413 } 14414 } else { 14415 try { 14416 verifySignaturesLP(ps, pkg); 14417 } catch (PackageManagerException e) { 14418 res.setError(e.error, e.getMessage()); 14419 return; 14420 } 14421 } 14422 14423 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 14424 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 14425 systemApp = (ps.pkg.applicationInfo.flags & 14426 ApplicationInfo.FLAG_SYSTEM) != 0; 14427 } 14428 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14429 } 14430 14431 // Check whether the newly-scanned package wants to define an already-defined perm 14432 int N = pkg.permissions.size(); 14433 for (int i = N-1; i >= 0; i--) { 14434 PackageParser.Permission perm = pkg.permissions.get(i); 14435 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 14436 if (bp != null) { 14437 // If the defining package is signed with our cert, it's okay. This 14438 // also includes the "updating the same package" case, of course. 14439 // "updating same package" could also involve key-rotation. 14440 final boolean sigsOk; 14441 if (bp.sourcePackage.equals(pkg.packageName) 14442 && (bp.packageSetting instanceof PackageSetting) 14443 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 14444 scanFlags))) { 14445 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 14446 } else { 14447 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 14448 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 14449 } 14450 if (!sigsOk) { 14451 // If the owning package is the system itself, we log but allow 14452 // install to proceed; we fail the install on all other permission 14453 // redefinitions. 14454 if (!bp.sourcePackage.equals("android")) { 14455 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 14456 + pkg.packageName + " attempting to redeclare permission " 14457 + perm.info.name + " already owned by " + bp.sourcePackage); 14458 res.origPermission = perm.info.name; 14459 res.origPackage = bp.sourcePackage; 14460 return; 14461 } else { 14462 Slog.w(TAG, "Package " + pkg.packageName 14463 + " attempting to redeclare system permission " 14464 + perm.info.name + "; ignoring new declaration"); 14465 pkg.permissions.remove(i); 14466 } 14467 } 14468 } 14469 } 14470 } 14471 14472 if (systemApp) { 14473 if (onExternal) { 14474 // Abort update; system app can't be replaced with app on sdcard 14475 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 14476 "Cannot install updates to system apps on sdcard"); 14477 return; 14478 } else if (ephemeral) { 14479 // Abort update; system app can't be replaced with an ephemeral app 14480 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 14481 "Cannot update a system app with an ephemeral app"); 14482 return; 14483 } 14484 } 14485 14486 if (args.move != null) { 14487 // We did an in-place move, so dex is ready to roll 14488 scanFlags |= SCAN_NO_DEX; 14489 scanFlags |= SCAN_MOVE; 14490 14491 synchronized (mPackages) { 14492 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14493 if (ps == null) { 14494 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 14495 "Missing settings for moved package " + pkgName); 14496 } 14497 14498 // We moved the entire application as-is, so bring over the 14499 // previously derived ABI information. 14500 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 14501 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 14502 } 14503 14504 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 14505 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 14506 scanFlags |= SCAN_NO_DEX; 14507 14508 try { 14509 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 14510 args.abiOverride : pkg.cpuAbiOverride); 14511 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 14512 true /* extract libs */); 14513 } catch (PackageManagerException pme) { 14514 Slog.e(TAG, "Error deriving application ABI", pme); 14515 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 14516 return; 14517 } 14518 14519 14520 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 14521 // Do not run PackageDexOptimizer through the local performDexOpt 14522 // method because `pkg` is not in `mPackages` yet. 14523 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instructionSets */, 14524 false /* checkProfiles */, getCompilerFilterForReason(REASON_INSTALL)); 14525 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14526 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 14527 String msg = "Extracking package failed for " + pkgName; 14528 res.setError(INSTALL_FAILED_DEXOPT, msg); 14529 return; 14530 } 14531 } 14532 14533 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 14534 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 14535 return; 14536 } 14537 14538 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 14539 14540 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 14541 "installPackageLI")) { 14542 if (replace) { 14543 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 14544 installerPackageName, res); 14545 } else { 14546 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 14547 args.user, installerPackageName, volumeUuid, res); 14548 } 14549 } 14550 synchronized (mPackages) { 14551 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14552 if (ps != null) { 14553 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14554 } 14555 14556 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14557 for (int i = 0; i < childCount; i++) { 14558 PackageParser.Package childPkg = pkg.childPackages.get(i); 14559 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14560 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14561 if (childPs != null) { 14562 childRes.newUsers = childPs.queryInstalledUsers( 14563 sUserManager.getUserIds(), true); 14564 } 14565 } 14566 } 14567 } 14568 14569 private void startIntentFilterVerifications(int userId, boolean replacing, 14570 PackageParser.Package pkg) { 14571 if (mIntentFilterVerifierComponent == null) { 14572 Slog.w(TAG, "No IntentFilter verification will not be done as " 14573 + "there is no IntentFilterVerifier available!"); 14574 return; 14575 } 14576 14577 final int verifierUid = getPackageUid( 14578 mIntentFilterVerifierComponent.getPackageName(), 14579 MATCH_DEBUG_TRIAGED_MISSING, 14580 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 14581 14582 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14583 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 14584 mHandler.sendMessage(msg); 14585 14586 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14587 for (int i = 0; i < childCount; i++) { 14588 PackageParser.Package childPkg = pkg.childPackages.get(i); 14589 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14590 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 14591 mHandler.sendMessage(msg); 14592 } 14593 } 14594 14595 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 14596 PackageParser.Package pkg) { 14597 int size = pkg.activities.size(); 14598 if (size == 0) { 14599 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14600 "No activity, so no need to verify any IntentFilter!"); 14601 return; 14602 } 14603 14604 final boolean hasDomainURLs = hasDomainURLs(pkg); 14605 if (!hasDomainURLs) { 14606 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14607 "No domain URLs, so no need to verify any IntentFilter!"); 14608 return; 14609 } 14610 14611 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 14612 + " if any IntentFilter from the " + size 14613 + " Activities needs verification ..."); 14614 14615 int count = 0; 14616 final String packageName = pkg.packageName; 14617 14618 synchronized (mPackages) { 14619 // If this is a new install and we see that we've already run verification for this 14620 // package, we have nothing to do: it means the state was restored from backup. 14621 if (!replacing) { 14622 IntentFilterVerificationInfo ivi = 14623 mSettings.getIntentFilterVerificationLPr(packageName); 14624 if (ivi != null) { 14625 if (DEBUG_DOMAIN_VERIFICATION) { 14626 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 14627 + ivi.getStatusString()); 14628 } 14629 return; 14630 } 14631 } 14632 14633 // If any filters need to be verified, then all need to be. 14634 boolean needToVerify = false; 14635 for (PackageParser.Activity a : pkg.activities) { 14636 for (ActivityIntentInfo filter : a.intents) { 14637 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 14638 if (DEBUG_DOMAIN_VERIFICATION) { 14639 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 14640 } 14641 needToVerify = true; 14642 break; 14643 } 14644 } 14645 } 14646 14647 if (needToVerify) { 14648 final int verificationId = mIntentFilterVerificationToken++; 14649 for (PackageParser.Activity a : pkg.activities) { 14650 for (ActivityIntentInfo filter : a.intents) { 14651 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 14652 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14653 "Verification needed for IntentFilter:" + filter.toString()); 14654 mIntentFilterVerifier.addOneIntentFilterVerification( 14655 verifierUid, userId, verificationId, filter, packageName); 14656 count++; 14657 } 14658 } 14659 } 14660 } 14661 } 14662 14663 if (count > 0) { 14664 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 14665 + " IntentFilter verification" + (count > 1 ? "s" : "") 14666 + " for userId:" + userId); 14667 mIntentFilterVerifier.startVerifications(userId); 14668 } else { 14669 if (DEBUG_DOMAIN_VERIFICATION) { 14670 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 14671 } 14672 } 14673 } 14674 14675 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 14676 final ComponentName cn = filter.activity.getComponentName(); 14677 final String packageName = cn.getPackageName(); 14678 14679 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 14680 packageName); 14681 if (ivi == null) { 14682 return true; 14683 } 14684 int status = ivi.getStatus(); 14685 switch (status) { 14686 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 14687 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 14688 return true; 14689 14690 default: 14691 // Nothing to do 14692 return false; 14693 } 14694 } 14695 14696 private static boolean isMultiArch(ApplicationInfo info) { 14697 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 14698 } 14699 14700 private static boolean isExternal(PackageParser.Package pkg) { 14701 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 14702 } 14703 14704 private static boolean isExternal(PackageSetting ps) { 14705 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 14706 } 14707 14708 private static boolean isEphemeral(PackageParser.Package pkg) { 14709 return pkg.applicationInfo.isEphemeralApp(); 14710 } 14711 14712 private static boolean isEphemeral(PackageSetting ps) { 14713 return ps.pkg != null && isEphemeral(ps.pkg); 14714 } 14715 14716 private static boolean isSystemApp(PackageParser.Package pkg) { 14717 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 14718 } 14719 14720 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 14721 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14722 } 14723 14724 private static boolean hasDomainURLs(PackageParser.Package pkg) { 14725 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 14726 } 14727 14728 private static boolean isSystemApp(PackageSetting ps) { 14729 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 14730 } 14731 14732 private static boolean isUpdatedSystemApp(PackageSetting ps) { 14733 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 14734 } 14735 14736 private int packageFlagsToInstallFlags(PackageSetting ps) { 14737 int installFlags = 0; 14738 if (isEphemeral(ps)) { 14739 installFlags |= PackageManager.INSTALL_EPHEMERAL; 14740 } 14741 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 14742 // This existing package was an external ASEC install when we have 14743 // the external flag without a UUID 14744 installFlags |= PackageManager.INSTALL_EXTERNAL; 14745 } 14746 if (ps.isForwardLocked()) { 14747 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 14748 } 14749 return installFlags; 14750 } 14751 14752 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 14753 if (isExternal(pkg)) { 14754 if (TextUtils.isEmpty(pkg.volumeUuid)) { 14755 return StorageManager.UUID_PRIMARY_PHYSICAL; 14756 } else { 14757 return pkg.volumeUuid; 14758 } 14759 } else { 14760 return StorageManager.UUID_PRIVATE_INTERNAL; 14761 } 14762 } 14763 14764 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 14765 if (isExternal(pkg)) { 14766 if (TextUtils.isEmpty(pkg.volumeUuid)) { 14767 return mSettings.getExternalVersion(); 14768 } else { 14769 return mSettings.findOrCreateVersion(pkg.volumeUuid); 14770 } 14771 } else { 14772 return mSettings.getInternalVersion(); 14773 } 14774 } 14775 14776 private void deleteTempPackageFiles() { 14777 final FilenameFilter filter = new FilenameFilter() { 14778 public boolean accept(File dir, String name) { 14779 return name.startsWith("vmdl") && name.endsWith(".tmp"); 14780 } 14781 }; 14782 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 14783 file.delete(); 14784 } 14785 } 14786 14787 @Override 14788 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 14789 int flags) { 14790 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 14791 flags); 14792 } 14793 14794 @Override 14795 public void deletePackage(final String packageName, 14796 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 14797 mContext.enforceCallingOrSelfPermission( 14798 android.Manifest.permission.DELETE_PACKAGES, null); 14799 Preconditions.checkNotNull(packageName); 14800 Preconditions.checkNotNull(observer); 14801 final int uid = Binder.getCallingUid(); 14802 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 14803 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 14804 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 14805 mContext.enforceCallingOrSelfPermission( 14806 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 14807 "deletePackage for user " + userId); 14808 } 14809 14810 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 14811 try { 14812 observer.onPackageDeleted(packageName, 14813 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 14814 } catch (RemoteException re) { 14815 } 14816 return; 14817 } 14818 14819 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 14820 try { 14821 observer.onPackageDeleted(packageName, 14822 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 14823 } catch (RemoteException re) { 14824 } 14825 return; 14826 } 14827 14828 if (DEBUG_REMOVE) { 14829 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 14830 + " deleteAllUsers: " + deleteAllUsers ); 14831 } 14832 // Queue up an async operation since the package deletion may take a little while. 14833 mHandler.post(new Runnable() { 14834 public void run() { 14835 mHandler.removeCallbacks(this); 14836 int returnCode; 14837 if (!deleteAllUsers) { 14838 returnCode = deletePackageX(packageName, userId, deleteFlags); 14839 } else { 14840 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 14841 // If nobody is blocking uninstall, proceed with delete for all users 14842 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 14843 returnCode = deletePackageX(packageName, userId, deleteFlags); 14844 } else { 14845 // Otherwise uninstall individually for users with blockUninstalls=false 14846 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 14847 for (int userId : users) { 14848 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 14849 returnCode = deletePackageX(packageName, userId, userFlags); 14850 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 14851 Slog.w(TAG, "Package delete failed for user " + userId 14852 + ", returnCode " + returnCode); 14853 } 14854 } 14855 } 14856 // The app has only been marked uninstalled for certain users. 14857 // We still need to report that delete was blocked 14858 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 14859 } 14860 } 14861 try { 14862 observer.onPackageDeleted(packageName, returnCode, null); 14863 } catch (RemoteException e) { 14864 Log.i(TAG, "Observer no longer exists."); 14865 } //end catch 14866 } //end run 14867 }); 14868 } 14869 14870 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 14871 int[] result = EMPTY_INT_ARRAY; 14872 for (int userId : userIds) { 14873 if (getBlockUninstallForUser(packageName, userId)) { 14874 result = ArrayUtils.appendInt(result, userId); 14875 } 14876 } 14877 return result; 14878 } 14879 14880 @Override 14881 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 14882 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 14883 } 14884 14885 private boolean isPackageDeviceAdmin(String packageName, int userId) { 14886 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 14887 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 14888 try { 14889 if (dpm != null) { 14890 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 14891 /* callingUserOnly =*/ false); 14892 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 14893 : deviceOwnerComponentName.getPackageName(); 14894 // Does the package contains the device owner? 14895 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 14896 // this check is probably not needed, since DO should be registered as a device 14897 // admin on some user too. (Original bug for this: b/17657954) 14898 if (packageName.equals(deviceOwnerPackageName)) { 14899 return true; 14900 } 14901 // Does it contain a device admin for any user? 14902 int[] users; 14903 if (userId == UserHandle.USER_ALL) { 14904 users = sUserManager.getUserIds(); 14905 } else { 14906 users = new int[]{userId}; 14907 } 14908 for (int i = 0; i < users.length; ++i) { 14909 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 14910 return true; 14911 } 14912 } 14913 } 14914 } catch (RemoteException e) { 14915 } 14916 return false; 14917 } 14918 14919 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 14920 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 14921 } 14922 14923 /** 14924 * This method is an internal method that could be get invoked either 14925 * to delete an installed package or to clean up a failed installation. 14926 * After deleting an installed package, a broadcast is sent to notify any 14927 * listeners that the package has been removed. For cleaning up a failed 14928 * installation, the broadcast is not necessary since the package's 14929 * installation wouldn't have sent the initial broadcast either 14930 * The key steps in deleting a package are 14931 * deleting the package information in internal structures like mPackages, 14932 * deleting the packages base directories through installd 14933 * updating mSettings to reflect current status 14934 * persisting settings for later use 14935 * sending a broadcast if necessary 14936 */ 14937 private int deletePackageX(String packageName, int userId, int deleteFlags) { 14938 final PackageRemovedInfo info = new PackageRemovedInfo(); 14939 final boolean res; 14940 14941 final UserHandle removeForUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 14942 ? UserHandle.ALL : new UserHandle(userId); 14943 14944 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 14945 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 14946 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 14947 } 14948 14949 PackageSetting uninstalledPs = null; 14950 14951 // for the uninstall-updates case and restricted profiles, remember the per- 14952 // user handle installed state 14953 int[] allUsers; 14954 synchronized (mPackages) { 14955 uninstalledPs = mSettings.mPackages.get(packageName); 14956 if (uninstalledPs == null) { 14957 Slog.w(TAG, "Not removing non-existent package " + packageName); 14958 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 14959 } 14960 allUsers = sUserManager.getUserIds(); 14961 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 14962 } 14963 14964 synchronized (mInstallLock) { 14965 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 14966 try (PackageFreezer freezer = freezePackageForDelete(packageName, deleteFlags, 14967 "deletePackageX")) { 14968 res = deletePackageLIF(packageName, removeForUser, true, allUsers, 14969 deleteFlags | REMOVE_CHATTY, info, true, null); 14970 } 14971 synchronized (mPackages) { 14972 if (res) { 14973 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 14974 } 14975 } 14976 } 14977 14978 if (res) { 14979 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 14980 info.sendPackageRemovedBroadcasts(killApp); 14981 info.sendSystemPackageUpdatedBroadcasts(); 14982 info.sendSystemPackageAppearedBroadcasts(); 14983 } 14984 // Force a gc here. 14985 Runtime.getRuntime().gc(); 14986 // Delete the resources here after sending the broadcast to let 14987 // other processes clean up before deleting resources. 14988 if (info.args != null) { 14989 synchronized (mInstallLock) { 14990 info.args.doPostDeleteLI(true); 14991 } 14992 } 14993 14994 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 14995 } 14996 14997 class PackageRemovedInfo { 14998 String removedPackage; 14999 int uid = -1; 15000 int removedAppId = -1; 15001 int[] origUsers; 15002 int[] removedUsers = null; 15003 boolean isRemovedPackageSystemUpdate = false; 15004 boolean isUpdate; 15005 boolean dataRemoved; 15006 boolean removedForAllUsers; 15007 // Clean up resources deleted packages. 15008 InstallArgs args = null; 15009 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 15010 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 15011 15012 void sendPackageRemovedBroadcasts(boolean killApp) { 15013 sendPackageRemovedBroadcastInternal(killApp); 15014 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 15015 for (int i = 0; i < childCount; i++) { 15016 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15017 childInfo.sendPackageRemovedBroadcastInternal(killApp); 15018 } 15019 } 15020 15021 void sendSystemPackageUpdatedBroadcasts() { 15022 if (isRemovedPackageSystemUpdate) { 15023 sendSystemPackageUpdatedBroadcastsInternal(); 15024 final int childCount = (removedChildPackages != null) 15025 ? removedChildPackages.size() : 0; 15026 for (int i = 0; i < childCount; i++) { 15027 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15028 if (childInfo.isRemovedPackageSystemUpdate) { 15029 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 15030 } 15031 } 15032 } 15033 } 15034 15035 void sendSystemPackageAppearedBroadcasts() { 15036 final int packageCount = (appearedChildPackages != null) 15037 ? appearedChildPackages.size() : 0; 15038 for (int i = 0; i < packageCount; i++) { 15039 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 15040 for (int userId : installedInfo.newUsers) { 15041 sendPackageAddedForUser(installedInfo.name, true, 15042 UserHandle.getAppId(installedInfo.uid), userId); 15043 } 15044 } 15045 } 15046 15047 private void sendSystemPackageUpdatedBroadcastsInternal() { 15048 Bundle extras = new Bundle(2); 15049 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15050 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15051 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 15052 extras, 0, null, null, null); 15053 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 15054 extras, 0, null, null, null); 15055 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 15056 null, 0, removedPackage, null, null); 15057 } 15058 15059 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 15060 Bundle extras = new Bundle(2); 15061 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15062 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 15063 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 15064 if (isUpdate || isRemovedPackageSystemUpdate) { 15065 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15066 } 15067 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 15068 if (removedPackage != null) { 15069 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 15070 extras, 0, null, null, removedUsers); 15071 if (dataRemoved && !isRemovedPackageSystemUpdate) { 15072 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 15073 removedPackage, extras, 0, null, null, removedUsers); 15074 } 15075 } 15076 if (removedAppId >= 0) { 15077 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 15078 removedUsers); 15079 } 15080 } 15081 } 15082 15083 /* 15084 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 15085 * flag is not set, the data directory is removed as well. 15086 * make sure this flag is set for partially installed apps. If not its meaningless to 15087 * delete a partially installed application. 15088 */ 15089 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 15090 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 15091 String packageName = ps.name; 15092 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 15093 // Retrieve object to delete permissions for shared user later on 15094 final PackageParser.Package deletedPkg; 15095 final PackageSetting deletedPs; 15096 // reader 15097 synchronized (mPackages) { 15098 deletedPkg = mPackages.get(packageName); 15099 deletedPs = mSettings.mPackages.get(packageName); 15100 if (outInfo != null) { 15101 outInfo.removedPackage = packageName; 15102 outInfo.removedUsers = deletedPs != null 15103 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 15104 : null; 15105 } 15106 } 15107 15108 removePackageLI(ps, (flags & REMOVE_CHATTY) != 0); 15109 15110 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 15111 destroyAppDataLIF(deletedPkg, UserHandle.USER_ALL, 15112 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15113 destroyAppProfilesLIF(deletedPkg); 15114 if (outInfo != null) { 15115 outInfo.dataRemoved = true; 15116 } 15117 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 15118 } 15119 15120 // writer 15121 synchronized (mPackages) { 15122 if (deletedPs != null) { 15123 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 15124 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 15125 clearDefaultBrowserIfNeeded(packageName); 15126 if (outInfo != null) { 15127 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 15128 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 15129 } 15130 updatePermissionsLPw(deletedPs.name, null, 0); 15131 if (deletedPs.sharedUser != null) { 15132 // Remove permissions associated with package. Since runtime 15133 // permissions are per user we have to kill the removed package 15134 // or packages running under the shared user of the removed 15135 // package if revoking the permissions requested only by the removed 15136 // package is successful and this causes a change in gids. 15137 for (int userId : UserManagerService.getInstance().getUserIds()) { 15138 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 15139 userId); 15140 if (userIdToKill == UserHandle.USER_ALL 15141 || userIdToKill >= UserHandle.USER_SYSTEM) { 15142 // If gids changed for this user, kill all affected packages. 15143 mHandler.post(new Runnable() { 15144 @Override 15145 public void run() { 15146 // This has to happen with no lock held. 15147 killApplication(deletedPs.name, deletedPs.appId, 15148 KILL_APP_REASON_GIDS_CHANGED); 15149 } 15150 }); 15151 break; 15152 } 15153 } 15154 } 15155 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 15156 } 15157 // make sure to preserve per-user disabled state if this removal was just 15158 // a downgrade of a system app to the factory package 15159 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 15160 if (DEBUG_REMOVE) { 15161 Slog.d(TAG, "Propagating install state across downgrade"); 15162 } 15163 for (int userId : allUserHandles) { 15164 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15165 if (DEBUG_REMOVE) { 15166 Slog.d(TAG, " user " + userId + " => " + installed); 15167 } 15168 ps.setInstalled(installed, userId); 15169 } 15170 } 15171 } 15172 // can downgrade to reader 15173 if (writeSettings) { 15174 // Save settings now 15175 mSettings.writeLPr(); 15176 } 15177 } 15178 if (outInfo != null) { 15179 // A user ID was deleted here. Go through all users and remove it 15180 // from KeyStore. 15181 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 15182 } 15183 } 15184 15185 static boolean locationIsPrivileged(File path) { 15186 try { 15187 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 15188 .getCanonicalPath(); 15189 return path.getCanonicalPath().startsWith(privilegedAppDir); 15190 } catch (IOException e) { 15191 Slog.e(TAG, "Unable to access code path " + path); 15192 } 15193 return false; 15194 } 15195 15196 /* 15197 * Tries to delete system package. 15198 */ 15199 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 15200 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 15201 boolean writeSettings) { 15202 if (deletedPs.parentPackageName != null) { 15203 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 15204 return false; 15205 } 15206 15207 final boolean applyUserRestrictions 15208 = (allUserHandles != null) && (outInfo.origUsers != null); 15209 final PackageSetting disabledPs; 15210 // Confirm if the system package has been updated 15211 // An updated system app can be deleted. This will also have to restore 15212 // the system pkg from system partition 15213 // reader 15214 synchronized (mPackages) { 15215 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 15216 } 15217 15218 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 15219 + " disabledPs=" + disabledPs); 15220 15221 if (disabledPs == null) { 15222 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 15223 return false; 15224 } else if (DEBUG_REMOVE) { 15225 Slog.d(TAG, "Deleting system pkg from data partition"); 15226 } 15227 15228 if (DEBUG_REMOVE) { 15229 if (applyUserRestrictions) { 15230 Slog.d(TAG, "Remembering install states:"); 15231 for (int userId : allUserHandles) { 15232 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 15233 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 15234 } 15235 } 15236 } 15237 15238 // Delete the updated package 15239 outInfo.isRemovedPackageSystemUpdate = true; 15240 if (outInfo.removedChildPackages != null) { 15241 final int childCount = (deletedPs.childPackageNames != null) 15242 ? deletedPs.childPackageNames.size() : 0; 15243 for (int i = 0; i < childCount; i++) { 15244 String childPackageName = deletedPs.childPackageNames.get(i); 15245 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 15246 .contains(childPackageName)) { 15247 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15248 childPackageName); 15249 if (childInfo != null) { 15250 childInfo.isRemovedPackageSystemUpdate = true; 15251 } 15252 } 15253 } 15254 } 15255 15256 if (disabledPs.versionCode < deletedPs.versionCode) { 15257 // Delete data for downgrades 15258 flags &= ~PackageManager.DELETE_KEEP_DATA; 15259 } else { 15260 // Preserve data by setting flag 15261 flags |= PackageManager.DELETE_KEEP_DATA; 15262 } 15263 15264 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 15265 outInfo, writeSettings, disabledPs.pkg); 15266 if (!ret) { 15267 return false; 15268 } 15269 15270 // writer 15271 synchronized (mPackages) { 15272 // Reinstate the old system package 15273 enableSystemPackageLPw(disabledPs.pkg); 15274 // Remove any native libraries from the upgraded package. 15275 removeNativeBinariesLI(deletedPs); 15276 } 15277 15278 // Install the system package 15279 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 15280 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 15281 if (locationIsPrivileged(disabledPs.codePath)) { 15282 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 15283 } 15284 15285 final PackageParser.Package newPkg; 15286 try { 15287 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 15288 } catch (PackageManagerException e) { 15289 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 15290 + e.getMessage()); 15291 return false; 15292 } 15293 15294 prepareAppDataAfterInstallLIF(newPkg); 15295 15296 // writer 15297 synchronized (mPackages) { 15298 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 15299 15300 // Propagate the permissions state as we do not want to drop on the floor 15301 // runtime permissions. The update permissions method below will take 15302 // care of removing obsolete permissions and grant install permissions. 15303 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 15304 updatePermissionsLPw(newPkg.packageName, newPkg, 15305 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 15306 15307 if (applyUserRestrictions) { 15308 if (DEBUG_REMOVE) { 15309 Slog.d(TAG, "Propagating install state across reinstall"); 15310 } 15311 for (int userId : allUserHandles) { 15312 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15313 if (DEBUG_REMOVE) { 15314 Slog.d(TAG, " user " + userId + " => " + installed); 15315 } 15316 ps.setInstalled(installed, userId); 15317 15318 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 15319 } 15320 // Regardless of writeSettings we need to ensure that this restriction 15321 // state propagation is persisted 15322 mSettings.writeAllUsersPackageRestrictionsLPr(); 15323 } 15324 // can downgrade to reader here 15325 if (writeSettings) { 15326 mSettings.writeLPr(); 15327 } 15328 } 15329 return true; 15330 } 15331 15332 private boolean deleteInstalledPackageLIF(PackageSetting ps, 15333 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 15334 PackageRemovedInfo outInfo, boolean writeSettings, 15335 PackageParser.Package replacingPackage) { 15336 synchronized (mPackages) { 15337 if (outInfo != null) { 15338 outInfo.uid = ps.appId; 15339 } 15340 15341 if (outInfo != null && outInfo.removedChildPackages != null) { 15342 final int childCount = (ps.childPackageNames != null) 15343 ? ps.childPackageNames.size() : 0; 15344 for (int i = 0; i < childCount; i++) { 15345 String childPackageName = ps.childPackageNames.get(i); 15346 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 15347 if (childPs == null) { 15348 return false; 15349 } 15350 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15351 childPackageName); 15352 if (childInfo != null) { 15353 childInfo.uid = childPs.appId; 15354 } 15355 } 15356 } 15357 } 15358 15359 // Delete package data from internal structures and also remove data if flag is set 15360 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 15361 15362 // Delete the child packages data 15363 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 15364 for (int i = 0; i < childCount; i++) { 15365 PackageSetting childPs; 15366 synchronized (mPackages) { 15367 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 15368 } 15369 if (childPs != null) { 15370 PackageRemovedInfo childOutInfo = (outInfo != null 15371 && outInfo.removedChildPackages != null) 15372 ? outInfo.removedChildPackages.get(childPs.name) : null; 15373 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 15374 && (replacingPackage != null 15375 && !replacingPackage.hasChildPackage(childPs.name)) 15376 ? flags & ~DELETE_KEEP_DATA : flags; 15377 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 15378 deleteFlags, writeSettings); 15379 } 15380 } 15381 15382 // Delete application code and resources only for parent packages 15383 if (ps.parentPackageName == null) { 15384 if (deleteCodeAndResources && (outInfo != null)) { 15385 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 15386 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 15387 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 15388 } 15389 } 15390 15391 return true; 15392 } 15393 15394 @Override 15395 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 15396 int userId) { 15397 mContext.enforceCallingOrSelfPermission( 15398 android.Manifest.permission.DELETE_PACKAGES, null); 15399 synchronized (mPackages) { 15400 PackageSetting ps = mSettings.mPackages.get(packageName); 15401 if (ps == null) { 15402 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 15403 return false; 15404 } 15405 if (!ps.getInstalled(userId)) { 15406 // Can't block uninstall for an app that is not installed or enabled. 15407 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 15408 return false; 15409 } 15410 ps.setBlockUninstall(blockUninstall, userId); 15411 mSettings.writePackageRestrictionsLPr(userId); 15412 } 15413 return true; 15414 } 15415 15416 @Override 15417 public boolean getBlockUninstallForUser(String packageName, int userId) { 15418 synchronized (mPackages) { 15419 PackageSetting ps = mSettings.mPackages.get(packageName); 15420 if (ps == null) { 15421 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 15422 return false; 15423 } 15424 return ps.getBlockUninstall(userId); 15425 } 15426 } 15427 15428 @Override 15429 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 15430 int callingUid = Binder.getCallingUid(); 15431 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 15432 throw new SecurityException( 15433 "setRequiredForSystemUser can only be run by the system or root"); 15434 } 15435 synchronized (mPackages) { 15436 PackageSetting ps = mSettings.mPackages.get(packageName); 15437 if (ps == null) { 15438 Log.w(TAG, "Package doesn't exist: " + packageName); 15439 return false; 15440 } 15441 if (systemUserApp) { 15442 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15443 } else { 15444 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15445 } 15446 mSettings.writeLPr(); 15447 } 15448 return true; 15449 } 15450 15451 /* 15452 * This method handles package deletion in general 15453 */ 15454 private boolean deletePackageLIF(String packageName, UserHandle user, 15455 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 15456 PackageRemovedInfo outInfo, boolean writeSettings, 15457 PackageParser.Package replacingPackage) { 15458 if (packageName == null) { 15459 Slog.w(TAG, "Attempt to delete null packageName."); 15460 return false; 15461 } 15462 15463 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 15464 15465 PackageSetting ps; 15466 15467 synchronized (mPackages) { 15468 ps = mSettings.mPackages.get(packageName); 15469 if (ps == null) { 15470 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 15471 return false; 15472 } 15473 15474 if (ps.parentPackageName != null && (!isSystemApp(ps) 15475 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 15476 if (DEBUG_REMOVE) { 15477 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 15478 + ((user == null) ? UserHandle.USER_ALL : user)); 15479 } 15480 final int removedUserId = (user != null) ? user.getIdentifier() 15481 : UserHandle.USER_ALL; 15482 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 15483 return false; 15484 } 15485 markPackageUninstalledForUserLPw(ps, user); 15486 scheduleWritePackageRestrictionsLocked(user); 15487 return true; 15488 } 15489 } 15490 15491 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 15492 && user.getIdentifier() != UserHandle.USER_ALL)) { 15493 // The caller is asking that the package only be deleted for a single 15494 // user. To do this, we just mark its uninstalled state and delete 15495 // its data. If this is a system app, we only allow this to happen if 15496 // they have set the special DELETE_SYSTEM_APP which requests different 15497 // semantics than normal for uninstalling system apps. 15498 markPackageUninstalledForUserLPw(ps, user); 15499 15500 if (!isSystemApp(ps)) { 15501 // Do not uninstall the APK if an app should be cached 15502 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 15503 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 15504 // Other user still have this package installed, so all 15505 // we need to do is clear this user's data and save that 15506 // it is uninstalled. 15507 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 15508 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 15509 return false; 15510 } 15511 scheduleWritePackageRestrictionsLocked(user); 15512 return true; 15513 } else { 15514 // We need to set it back to 'installed' so the uninstall 15515 // broadcasts will be sent correctly. 15516 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 15517 ps.setInstalled(true, user.getIdentifier()); 15518 } 15519 } else { 15520 // This is a system app, so we assume that the 15521 // other users still have this package installed, so all 15522 // we need to do is clear this user's data and save that 15523 // it is uninstalled. 15524 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 15525 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 15526 return false; 15527 } 15528 scheduleWritePackageRestrictionsLocked(user); 15529 return true; 15530 } 15531 } 15532 15533 // If we are deleting a composite package for all users, keep track 15534 // of result for each child. 15535 if (ps.childPackageNames != null && outInfo != null) { 15536 synchronized (mPackages) { 15537 final int childCount = ps.childPackageNames.size(); 15538 outInfo.removedChildPackages = new ArrayMap<>(childCount); 15539 for (int i = 0; i < childCount; i++) { 15540 String childPackageName = ps.childPackageNames.get(i); 15541 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 15542 childInfo.removedPackage = childPackageName; 15543 outInfo.removedChildPackages.put(childPackageName, childInfo); 15544 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 15545 if (childPs != null) { 15546 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 15547 } 15548 } 15549 } 15550 } 15551 15552 boolean ret = false; 15553 if (isSystemApp(ps)) { 15554 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 15555 // When an updated system application is deleted we delete the existing resources 15556 // as well and fall back to existing code in system partition 15557 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 15558 } else { 15559 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 15560 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 15561 outInfo, writeSettings, replacingPackage); 15562 } 15563 15564 // Take a note whether we deleted the package for all users 15565 if (outInfo != null) { 15566 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 15567 if (outInfo.removedChildPackages != null) { 15568 synchronized (mPackages) { 15569 final int childCount = outInfo.removedChildPackages.size(); 15570 for (int i = 0; i < childCount; i++) { 15571 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 15572 if (childInfo != null) { 15573 childInfo.removedForAllUsers = mPackages.get( 15574 childInfo.removedPackage) == null; 15575 } 15576 } 15577 } 15578 } 15579 // If we uninstalled an update to a system app there may be some 15580 // child packages that appeared as they are declared in the system 15581 // app but were not declared in the update. 15582 if (isSystemApp(ps)) { 15583 synchronized (mPackages) { 15584 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 15585 final int childCount = (updatedPs.childPackageNames != null) 15586 ? updatedPs.childPackageNames.size() : 0; 15587 for (int i = 0; i < childCount; i++) { 15588 String childPackageName = updatedPs.childPackageNames.get(i); 15589 if (outInfo.removedChildPackages == null 15590 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 15591 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 15592 if (childPs == null) { 15593 continue; 15594 } 15595 PackageInstalledInfo installRes = new PackageInstalledInfo(); 15596 installRes.name = childPackageName; 15597 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 15598 installRes.pkg = mPackages.get(childPackageName); 15599 installRes.uid = childPs.pkg.applicationInfo.uid; 15600 if (outInfo.appearedChildPackages == null) { 15601 outInfo.appearedChildPackages = new ArrayMap<>(); 15602 } 15603 outInfo.appearedChildPackages.put(childPackageName, installRes); 15604 } 15605 } 15606 } 15607 } 15608 } 15609 15610 return ret; 15611 } 15612 15613 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 15614 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 15615 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 15616 for (int nextUserId : userIds) { 15617 if (DEBUG_REMOVE) { 15618 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 15619 } 15620 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 15621 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 15622 false /*hidden*/, false /*suspended*/, null, null, null, 15623 false /*blockUninstall*/, 15624 ps.readUserState(nextUserId).domainVerificationStatus, 0); 15625 } 15626 } 15627 15628 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 15629 PackageRemovedInfo outInfo) { 15630 final PackageParser.Package pkg; 15631 synchronized (mPackages) { 15632 pkg = mPackages.get(ps.name); 15633 } 15634 15635 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 15636 : new int[] {userId}; 15637 for (int nextUserId : userIds) { 15638 if (DEBUG_REMOVE) { 15639 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 15640 + nextUserId); 15641 } 15642 15643 destroyAppDataLIF(pkg, userId, 15644 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15645 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 15646 schedulePackageCleaning(ps.name, nextUserId, false); 15647 synchronized (mPackages) { 15648 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 15649 scheduleWritePackageRestrictionsLocked(nextUserId); 15650 } 15651 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 15652 } 15653 } 15654 15655 if (outInfo != null) { 15656 outInfo.removedPackage = ps.name; 15657 outInfo.removedAppId = ps.appId; 15658 outInfo.removedUsers = userIds; 15659 } 15660 15661 return true; 15662 } 15663 15664 private final class ClearStorageConnection implements ServiceConnection { 15665 IMediaContainerService mContainerService; 15666 15667 @Override 15668 public void onServiceConnected(ComponentName name, IBinder service) { 15669 synchronized (this) { 15670 mContainerService = IMediaContainerService.Stub.asInterface(service); 15671 notifyAll(); 15672 } 15673 } 15674 15675 @Override 15676 public void onServiceDisconnected(ComponentName name) { 15677 } 15678 } 15679 15680 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 15681 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 15682 15683 final boolean mounted; 15684 if (Environment.isExternalStorageEmulated()) { 15685 mounted = true; 15686 } else { 15687 final String status = Environment.getExternalStorageState(); 15688 15689 mounted = status.equals(Environment.MEDIA_MOUNTED) 15690 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 15691 } 15692 15693 if (!mounted) { 15694 return; 15695 } 15696 15697 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 15698 int[] users; 15699 if (userId == UserHandle.USER_ALL) { 15700 users = sUserManager.getUserIds(); 15701 } else { 15702 users = new int[] { userId }; 15703 } 15704 final ClearStorageConnection conn = new ClearStorageConnection(); 15705 if (mContext.bindServiceAsUser( 15706 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 15707 try { 15708 for (int curUser : users) { 15709 long timeout = SystemClock.uptimeMillis() + 5000; 15710 synchronized (conn) { 15711 long now = SystemClock.uptimeMillis(); 15712 while (conn.mContainerService == null && now < timeout) { 15713 try { 15714 conn.wait(timeout - now); 15715 } catch (InterruptedException e) { 15716 } 15717 } 15718 } 15719 if (conn.mContainerService == null) { 15720 return; 15721 } 15722 15723 final UserEnvironment userEnv = new UserEnvironment(curUser); 15724 clearDirectory(conn.mContainerService, 15725 userEnv.buildExternalStorageAppCacheDirs(packageName)); 15726 if (allData) { 15727 clearDirectory(conn.mContainerService, 15728 userEnv.buildExternalStorageAppDataDirs(packageName)); 15729 clearDirectory(conn.mContainerService, 15730 userEnv.buildExternalStorageAppMediaDirs(packageName)); 15731 } 15732 } 15733 } finally { 15734 mContext.unbindService(conn); 15735 } 15736 } 15737 } 15738 15739 @Override 15740 public void clearApplicationProfileData(String packageName) { 15741 enforceSystemOrRoot("Only the system can clear all profile data"); 15742 15743 final PackageParser.Package pkg; 15744 synchronized (mPackages) { 15745 pkg = mPackages.get(packageName); 15746 } 15747 15748 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 15749 synchronized (mInstallLock) { 15750 clearAppProfilesLIF(pkg); 15751 } 15752 } 15753 } 15754 15755 @Override 15756 public void clearApplicationUserData(final String packageName, 15757 final IPackageDataObserver observer, final int userId) { 15758 mContext.enforceCallingOrSelfPermission( 15759 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 15760 15761 enforceCrossUserPermission(Binder.getCallingUid(), userId, 15762 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 15763 15764 final DevicePolicyManagerInternal dpmi = LocalServices 15765 .getService(DevicePolicyManagerInternal.class); 15766 if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) { 15767 throw new SecurityException("Cannot clear data for a device owner or a profile owner"); 15768 } 15769 // Queue up an async operation since the package deletion may take a little while. 15770 mHandler.post(new Runnable() { 15771 public void run() { 15772 mHandler.removeCallbacks(this); 15773 final boolean succeeded; 15774 try (PackageFreezer freezer = freezePackage(packageName, 15775 "clearApplicationUserData")) { 15776 synchronized (mInstallLock) { 15777 succeeded = clearApplicationUserDataLIF(packageName, userId); 15778 } 15779 clearExternalStorageDataSync(packageName, userId, true); 15780 } 15781 if (succeeded) { 15782 // invoke DeviceStorageMonitor's update method to clear any notifications 15783 DeviceStorageMonitorInternal dsm = LocalServices 15784 .getService(DeviceStorageMonitorInternal.class); 15785 if (dsm != null) { 15786 dsm.checkMemory(); 15787 } 15788 } 15789 if(observer != null) { 15790 try { 15791 observer.onRemoveCompleted(packageName, succeeded); 15792 } catch (RemoteException e) { 15793 Log.i(TAG, "Observer no longer exists."); 15794 } 15795 } //end if observer 15796 } //end run 15797 }); 15798 } 15799 15800 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 15801 if (packageName == null) { 15802 Slog.w(TAG, "Attempt to delete null packageName."); 15803 return false; 15804 } 15805 15806 // Try finding details about the requested package 15807 PackageParser.Package pkg; 15808 synchronized (mPackages) { 15809 pkg = mPackages.get(packageName); 15810 if (pkg == null) { 15811 final PackageSetting ps = mSettings.mPackages.get(packageName); 15812 if (ps != null) { 15813 pkg = ps.pkg; 15814 } 15815 } 15816 15817 if (pkg == null) { 15818 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 15819 return false; 15820 } 15821 15822 PackageSetting ps = (PackageSetting) pkg.mExtras; 15823 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 15824 } 15825 15826 clearAppDataLIF(pkg, userId, 15827 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15828 15829 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 15830 removeKeystoreDataIfNeeded(userId, appId); 15831 15832 final UserManager um = mContext.getSystemService(UserManager.class); 15833 final int flags; 15834 if (um.isUserUnlocked(userId)) { 15835 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 15836 } else if (um.isUserRunning(userId)) { 15837 flags = StorageManager.FLAG_STORAGE_DE; 15838 } else { 15839 flags = 0; 15840 } 15841 prepareAppDataContentsLIF(pkg, userId, flags); 15842 15843 return true; 15844 } 15845 15846 /** 15847 * Reverts user permission state changes (permissions and flags) in 15848 * all packages for a given user. 15849 * 15850 * @param userId The device user for which to do a reset. 15851 */ 15852 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 15853 final int packageCount = mPackages.size(); 15854 for (int i = 0; i < packageCount; i++) { 15855 PackageParser.Package pkg = mPackages.valueAt(i); 15856 PackageSetting ps = (PackageSetting) pkg.mExtras; 15857 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 15858 } 15859 } 15860 15861 /** 15862 * Reverts user permission state changes (permissions and flags). 15863 * 15864 * @param ps The package for which to reset. 15865 * @param userId The device user for which to do a reset. 15866 */ 15867 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 15868 final PackageSetting ps, final int userId) { 15869 if (ps.pkg == null) { 15870 return; 15871 } 15872 15873 // These are flags that can change base on user actions. 15874 final int userSettableMask = FLAG_PERMISSION_USER_SET 15875 | FLAG_PERMISSION_USER_FIXED 15876 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 15877 | FLAG_PERMISSION_REVIEW_REQUIRED; 15878 15879 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 15880 | FLAG_PERMISSION_POLICY_FIXED; 15881 15882 boolean writeInstallPermissions = false; 15883 boolean writeRuntimePermissions = false; 15884 15885 final int permissionCount = ps.pkg.requestedPermissions.size(); 15886 for (int i = 0; i < permissionCount; i++) { 15887 String permission = ps.pkg.requestedPermissions.get(i); 15888 15889 BasePermission bp = mSettings.mPermissions.get(permission); 15890 if (bp == null) { 15891 continue; 15892 } 15893 15894 // If shared user we just reset the state to which only this app contributed. 15895 if (ps.sharedUser != null) { 15896 boolean used = false; 15897 final int packageCount = ps.sharedUser.packages.size(); 15898 for (int j = 0; j < packageCount; j++) { 15899 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 15900 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 15901 && pkg.pkg.requestedPermissions.contains(permission)) { 15902 used = true; 15903 break; 15904 } 15905 } 15906 if (used) { 15907 continue; 15908 } 15909 } 15910 15911 PermissionsState permissionsState = ps.getPermissionsState(); 15912 15913 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 15914 15915 // Always clear the user settable flags. 15916 final boolean hasInstallState = permissionsState.getInstallPermissionState( 15917 bp.name) != null; 15918 // If permission review is enabled and this is a legacy app, mark the 15919 // permission as requiring a review as this is the initial state. 15920 int flags = 0; 15921 if (Build.PERMISSIONS_REVIEW_REQUIRED 15922 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 15923 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 15924 } 15925 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 15926 if (hasInstallState) { 15927 writeInstallPermissions = true; 15928 } else { 15929 writeRuntimePermissions = true; 15930 } 15931 } 15932 15933 // Below is only runtime permission handling. 15934 if (!bp.isRuntime()) { 15935 continue; 15936 } 15937 15938 // Never clobber system or policy. 15939 if ((oldFlags & policyOrSystemFlags) != 0) { 15940 continue; 15941 } 15942 15943 // If this permission was granted by default, make sure it is. 15944 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 15945 if (permissionsState.grantRuntimePermission(bp, userId) 15946 != PERMISSION_OPERATION_FAILURE) { 15947 writeRuntimePermissions = true; 15948 } 15949 // If permission review is enabled the permissions for a legacy apps 15950 // are represented as constantly granted runtime ones, so don't revoke. 15951 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 15952 // Otherwise, reset the permission. 15953 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 15954 switch (revokeResult) { 15955 case PERMISSION_OPERATION_SUCCESS: 15956 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 15957 writeRuntimePermissions = true; 15958 final int appId = ps.appId; 15959 mHandler.post(new Runnable() { 15960 @Override 15961 public void run() { 15962 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 15963 } 15964 }); 15965 } break; 15966 } 15967 } 15968 } 15969 15970 // Synchronously write as we are taking permissions away. 15971 if (writeRuntimePermissions) { 15972 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 15973 } 15974 15975 // Synchronously write as we are taking permissions away. 15976 if (writeInstallPermissions) { 15977 mSettings.writeLPr(); 15978 } 15979 } 15980 15981 /** 15982 * Remove entries from the keystore daemon. Will only remove it if the 15983 * {@code appId} is valid. 15984 */ 15985 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 15986 if (appId < 0) { 15987 return; 15988 } 15989 15990 final KeyStore keyStore = KeyStore.getInstance(); 15991 if (keyStore != null) { 15992 if (userId == UserHandle.USER_ALL) { 15993 for (final int individual : sUserManager.getUserIds()) { 15994 keyStore.clearUid(UserHandle.getUid(individual, appId)); 15995 } 15996 } else { 15997 keyStore.clearUid(UserHandle.getUid(userId, appId)); 15998 } 15999 } else { 16000 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 16001 } 16002 } 16003 16004 @Override 16005 public void deleteApplicationCacheFiles(final String packageName, 16006 final IPackageDataObserver observer) { 16007 mContext.enforceCallingOrSelfPermission( 16008 android.Manifest.permission.DELETE_CACHE_FILES, null); 16009 // Queue up an async operation since the package deletion may take a little while. 16010 final int userId = UserHandle.getCallingUserId(); 16011 16012 final PackageParser.Package pkg; 16013 synchronized (mPackages) { 16014 pkg = mPackages.get(packageName); 16015 } 16016 16017 mHandler.post(new Runnable() { 16018 public void run() { 16019 try (PackageFreezer freezer = freezePackage(packageName, 16020 "deleteApplicationCacheFiles")) { 16021 synchronized (mInstallLock) { 16022 final int flags = StorageManager.FLAG_STORAGE_DE 16023 | StorageManager.FLAG_STORAGE_CE; 16024 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 16025 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16026 } 16027 clearExternalStorageDataSync(packageName, userId, false); 16028 } 16029 if (observer != null) { 16030 try { 16031 observer.onRemoveCompleted(packageName, true); 16032 } catch (RemoteException e) { 16033 Log.i(TAG, "Observer no longer exists."); 16034 } 16035 } 16036 } 16037 }); 16038 } 16039 16040 @Override 16041 public void getPackageSizeInfo(final String packageName, int userHandle, 16042 final IPackageStatsObserver observer) { 16043 mContext.enforceCallingOrSelfPermission( 16044 android.Manifest.permission.GET_PACKAGE_SIZE, null); 16045 if (packageName == null) { 16046 throw new IllegalArgumentException("Attempt to get size of null packageName"); 16047 } 16048 16049 PackageStats stats = new PackageStats(packageName, userHandle); 16050 16051 /* 16052 * Queue up an async operation since the package measurement may take a 16053 * little while. 16054 */ 16055 Message msg = mHandler.obtainMessage(INIT_COPY); 16056 msg.obj = new MeasureParams(stats, observer); 16057 mHandler.sendMessage(msg); 16058 } 16059 16060 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 16061 final PackageSetting ps; 16062 synchronized (mPackages) { 16063 ps = mSettings.mPackages.get(packageName); 16064 if (ps == null) { 16065 Slog.w(TAG, "Failed to find settings for " + packageName); 16066 return false; 16067 } 16068 } 16069 try { 16070 mInstaller.getAppSize(ps.volumeUuid, packageName, userId, 16071 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 16072 ps.getCeDataInode(userId), ps.codePathString, stats); 16073 return true; 16074 } catch (InstallerException e) { 16075 Slog.w(TAG, String.valueOf(e)); 16076 return false; 16077 } 16078 } 16079 16080 private int getUidTargetSdkVersionLockedLPr(int uid) { 16081 Object obj = mSettings.getUserIdLPr(uid); 16082 if (obj instanceof SharedUserSetting) { 16083 final SharedUserSetting sus = (SharedUserSetting) obj; 16084 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 16085 final Iterator<PackageSetting> it = sus.packages.iterator(); 16086 while (it.hasNext()) { 16087 final PackageSetting ps = it.next(); 16088 if (ps.pkg != null) { 16089 int v = ps.pkg.applicationInfo.targetSdkVersion; 16090 if (v < vers) vers = v; 16091 } 16092 } 16093 return vers; 16094 } else if (obj instanceof PackageSetting) { 16095 final PackageSetting ps = (PackageSetting) obj; 16096 if (ps.pkg != null) { 16097 return ps.pkg.applicationInfo.targetSdkVersion; 16098 } 16099 } 16100 return Build.VERSION_CODES.CUR_DEVELOPMENT; 16101 } 16102 16103 @Override 16104 public void addPreferredActivity(IntentFilter filter, int match, 16105 ComponentName[] set, ComponentName activity, int userId) { 16106 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16107 "Adding preferred"); 16108 } 16109 16110 private void addPreferredActivityInternal(IntentFilter filter, int match, 16111 ComponentName[] set, ComponentName activity, boolean always, int userId, 16112 String opname) { 16113 // writer 16114 int callingUid = Binder.getCallingUid(); 16115 enforceCrossUserPermission(callingUid, userId, 16116 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 16117 if (filter.countActions() == 0) { 16118 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16119 return; 16120 } 16121 synchronized (mPackages) { 16122 if (mContext.checkCallingOrSelfPermission( 16123 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16124 != PackageManager.PERMISSION_GRANTED) { 16125 if (getUidTargetSdkVersionLockedLPr(callingUid) 16126 < Build.VERSION_CODES.FROYO) { 16127 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 16128 + callingUid); 16129 return; 16130 } 16131 mContext.enforceCallingOrSelfPermission( 16132 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16133 } 16134 16135 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 16136 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 16137 + userId + ":"); 16138 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16139 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 16140 scheduleWritePackageRestrictionsLocked(userId); 16141 } 16142 } 16143 16144 @Override 16145 public void replacePreferredActivity(IntentFilter filter, int match, 16146 ComponentName[] set, ComponentName activity, int userId) { 16147 if (filter.countActions() != 1) { 16148 throw new IllegalArgumentException( 16149 "replacePreferredActivity expects filter to have only 1 action."); 16150 } 16151 if (filter.countDataAuthorities() != 0 16152 || filter.countDataPaths() != 0 16153 || filter.countDataSchemes() > 1 16154 || filter.countDataTypes() != 0) { 16155 throw new IllegalArgumentException( 16156 "replacePreferredActivity expects filter to have no data authorities, " + 16157 "paths, or types; and at most one scheme."); 16158 } 16159 16160 final int callingUid = Binder.getCallingUid(); 16161 enforceCrossUserPermission(callingUid, userId, 16162 true /* requireFullPermission */, false /* checkShell */, 16163 "replace preferred activity"); 16164 synchronized (mPackages) { 16165 if (mContext.checkCallingOrSelfPermission( 16166 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16167 != PackageManager.PERMISSION_GRANTED) { 16168 if (getUidTargetSdkVersionLockedLPr(callingUid) 16169 < Build.VERSION_CODES.FROYO) { 16170 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 16171 + Binder.getCallingUid()); 16172 return; 16173 } 16174 mContext.enforceCallingOrSelfPermission( 16175 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16176 } 16177 16178 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16179 if (pir != null) { 16180 // Get all of the existing entries that exactly match this filter. 16181 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 16182 if (existing != null && existing.size() == 1) { 16183 PreferredActivity cur = existing.get(0); 16184 if (DEBUG_PREFERRED) { 16185 Slog.i(TAG, "Checking replace of preferred:"); 16186 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16187 if (!cur.mPref.mAlways) { 16188 Slog.i(TAG, " -- CUR; not mAlways!"); 16189 } else { 16190 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 16191 Slog.i(TAG, " -- CUR: mSet=" 16192 + Arrays.toString(cur.mPref.mSetComponents)); 16193 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 16194 Slog.i(TAG, " -- NEW: mMatch=" 16195 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 16196 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 16197 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 16198 } 16199 } 16200 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 16201 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 16202 && cur.mPref.sameSet(set)) { 16203 // Setting the preferred activity to what it happens to be already 16204 if (DEBUG_PREFERRED) { 16205 Slog.i(TAG, "Replacing with same preferred activity " 16206 + cur.mPref.mShortComponent + " for user " 16207 + userId + ":"); 16208 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16209 } 16210 return; 16211 } 16212 } 16213 16214 if (existing != null) { 16215 if (DEBUG_PREFERRED) { 16216 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 16217 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16218 } 16219 for (int i = 0; i < existing.size(); i++) { 16220 PreferredActivity pa = existing.get(i); 16221 if (DEBUG_PREFERRED) { 16222 Slog.i(TAG, "Removing existing preferred activity " 16223 + pa.mPref.mComponent + ":"); 16224 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 16225 } 16226 pir.removeFilter(pa); 16227 } 16228 } 16229 } 16230 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16231 "Replacing preferred"); 16232 } 16233 } 16234 16235 @Override 16236 public void clearPackagePreferredActivities(String packageName) { 16237 final int uid = Binder.getCallingUid(); 16238 // writer 16239 synchronized (mPackages) { 16240 PackageParser.Package pkg = mPackages.get(packageName); 16241 if (pkg == null || pkg.applicationInfo.uid != uid) { 16242 if (mContext.checkCallingOrSelfPermission( 16243 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16244 != PackageManager.PERMISSION_GRANTED) { 16245 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 16246 < Build.VERSION_CODES.FROYO) { 16247 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 16248 + Binder.getCallingUid()); 16249 return; 16250 } 16251 mContext.enforceCallingOrSelfPermission( 16252 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16253 } 16254 } 16255 16256 int user = UserHandle.getCallingUserId(); 16257 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 16258 scheduleWritePackageRestrictionsLocked(user); 16259 } 16260 } 16261 } 16262 16263 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16264 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 16265 ArrayList<PreferredActivity> removed = null; 16266 boolean changed = false; 16267 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16268 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 16269 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16270 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 16271 continue; 16272 } 16273 Iterator<PreferredActivity> it = pir.filterIterator(); 16274 while (it.hasNext()) { 16275 PreferredActivity pa = it.next(); 16276 // Mark entry for removal only if it matches the package name 16277 // and the entry is of type "always". 16278 if (packageName == null || 16279 (pa.mPref.mComponent.getPackageName().equals(packageName) 16280 && pa.mPref.mAlways)) { 16281 if (removed == null) { 16282 removed = new ArrayList<PreferredActivity>(); 16283 } 16284 removed.add(pa); 16285 } 16286 } 16287 if (removed != null) { 16288 for (int j=0; j<removed.size(); j++) { 16289 PreferredActivity pa = removed.get(j); 16290 pir.removeFilter(pa); 16291 } 16292 changed = true; 16293 } 16294 } 16295 return changed; 16296 } 16297 16298 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16299 private void clearIntentFilterVerificationsLPw(int userId) { 16300 final int packageCount = mPackages.size(); 16301 for (int i = 0; i < packageCount; i++) { 16302 PackageParser.Package pkg = mPackages.valueAt(i); 16303 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 16304 } 16305 } 16306 16307 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16308 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 16309 if (userId == UserHandle.USER_ALL) { 16310 if (mSettings.removeIntentFilterVerificationLPw(packageName, 16311 sUserManager.getUserIds())) { 16312 for (int oneUserId : sUserManager.getUserIds()) { 16313 scheduleWritePackageRestrictionsLocked(oneUserId); 16314 } 16315 } 16316 } else { 16317 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 16318 scheduleWritePackageRestrictionsLocked(userId); 16319 } 16320 } 16321 } 16322 16323 void clearDefaultBrowserIfNeeded(String packageName) { 16324 for (int oneUserId : sUserManager.getUserIds()) { 16325 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 16326 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 16327 if (packageName.equals(defaultBrowserPackageName)) { 16328 setDefaultBrowserPackageName(null, oneUserId); 16329 } 16330 } 16331 } 16332 16333 @Override 16334 public void resetApplicationPreferences(int userId) { 16335 mContext.enforceCallingOrSelfPermission( 16336 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16337 // writer 16338 synchronized (mPackages) { 16339 final long identity = Binder.clearCallingIdentity(); 16340 try { 16341 clearPackagePreferredActivitiesLPw(null, userId); 16342 mSettings.applyDefaultPreferredAppsLPw(this, userId); 16343 // TODO: We have to reset the default SMS and Phone. This requires 16344 // significant refactoring to keep all default apps in the package 16345 // manager (cleaner but more work) or have the services provide 16346 // callbacks to the package manager to request a default app reset. 16347 applyFactoryDefaultBrowserLPw(userId); 16348 clearIntentFilterVerificationsLPw(userId); 16349 primeDomainVerificationsLPw(userId); 16350 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 16351 scheduleWritePackageRestrictionsLocked(userId); 16352 } finally { 16353 Binder.restoreCallingIdentity(identity); 16354 } 16355 } 16356 } 16357 16358 @Override 16359 public int getPreferredActivities(List<IntentFilter> outFilters, 16360 List<ComponentName> outActivities, String packageName) { 16361 16362 int num = 0; 16363 final int userId = UserHandle.getCallingUserId(); 16364 // reader 16365 synchronized (mPackages) { 16366 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16367 if (pir != null) { 16368 final Iterator<PreferredActivity> it = pir.filterIterator(); 16369 while (it.hasNext()) { 16370 final PreferredActivity pa = it.next(); 16371 if (packageName == null 16372 || (pa.mPref.mComponent.getPackageName().equals(packageName) 16373 && pa.mPref.mAlways)) { 16374 if (outFilters != null) { 16375 outFilters.add(new IntentFilter(pa)); 16376 } 16377 if (outActivities != null) { 16378 outActivities.add(pa.mPref.mComponent); 16379 } 16380 } 16381 } 16382 } 16383 } 16384 16385 return num; 16386 } 16387 16388 @Override 16389 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 16390 int userId) { 16391 int callingUid = Binder.getCallingUid(); 16392 if (callingUid != Process.SYSTEM_UID) { 16393 throw new SecurityException( 16394 "addPersistentPreferredActivity can only be run by the system"); 16395 } 16396 if (filter.countActions() == 0) { 16397 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16398 return; 16399 } 16400 synchronized (mPackages) { 16401 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 16402 ":"); 16403 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16404 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 16405 new PersistentPreferredActivity(filter, activity)); 16406 scheduleWritePackageRestrictionsLocked(userId); 16407 } 16408 } 16409 16410 @Override 16411 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 16412 int callingUid = Binder.getCallingUid(); 16413 if (callingUid != Process.SYSTEM_UID) { 16414 throw new SecurityException( 16415 "clearPackagePersistentPreferredActivities can only be run by the system"); 16416 } 16417 ArrayList<PersistentPreferredActivity> removed = null; 16418 boolean changed = false; 16419 synchronized (mPackages) { 16420 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 16421 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 16422 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 16423 .valueAt(i); 16424 if (userId != thisUserId) { 16425 continue; 16426 } 16427 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 16428 while (it.hasNext()) { 16429 PersistentPreferredActivity ppa = it.next(); 16430 // Mark entry for removal only if it matches the package name. 16431 if (ppa.mComponent.getPackageName().equals(packageName)) { 16432 if (removed == null) { 16433 removed = new ArrayList<PersistentPreferredActivity>(); 16434 } 16435 removed.add(ppa); 16436 } 16437 } 16438 if (removed != null) { 16439 for (int j=0; j<removed.size(); j++) { 16440 PersistentPreferredActivity ppa = removed.get(j); 16441 ppir.removeFilter(ppa); 16442 } 16443 changed = true; 16444 } 16445 } 16446 16447 if (changed) { 16448 scheduleWritePackageRestrictionsLocked(userId); 16449 } 16450 } 16451 } 16452 16453 /** 16454 * Common machinery for picking apart a restored XML blob and passing 16455 * it to a caller-supplied functor to be applied to the running system. 16456 */ 16457 private void restoreFromXml(XmlPullParser parser, int userId, 16458 String expectedStartTag, BlobXmlRestorer functor) 16459 throws IOException, XmlPullParserException { 16460 int type; 16461 while ((type = parser.next()) != XmlPullParser.START_TAG 16462 && type != XmlPullParser.END_DOCUMENT) { 16463 } 16464 if (type != XmlPullParser.START_TAG) { 16465 // oops didn't find a start tag?! 16466 if (DEBUG_BACKUP) { 16467 Slog.e(TAG, "Didn't find start tag during restore"); 16468 } 16469 return; 16470 } 16471Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 16472 // this is supposed to be TAG_PREFERRED_BACKUP 16473 if (!expectedStartTag.equals(parser.getName())) { 16474 if (DEBUG_BACKUP) { 16475 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 16476 } 16477 return; 16478 } 16479 16480 // skip interfering stuff, then we're aligned with the backing implementation 16481 while ((type = parser.next()) == XmlPullParser.TEXT) { } 16482Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 16483 functor.apply(parser, userId); 16484 } 16485 16486 private interface BlobXmlRestorer { 16487 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 16488 } 16489 16490 /** 16491 * Non-Binder method, support for the backup/restore mechanism: write the 16492 * full set of preferred activities in its canonical XML format. Returns the 16493 * XML output as a byte array, or null if there is none. 16494 */ 16495 @Override 16496 public byte[] getPreferredActivityBackup(int userId) { 16497 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16498 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 16499 } 16500 16501 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16502 try { 16503 final XmlSerializer serializer = new FastXmlSerializer(); 16504 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16505 serializer.startDocument(null, true); 16506 serializer.startTag(null, TAG_PREFERRED_BACKUP); 16507 16508 synchronized (mPackages) { 16509 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 16510 } 16511 16512 serializer.endTag(null, TAG_PREFERRED_BACKUP); 16513 serializer.endDocument(); 16514 serializer.flush(); 16515 } catch (Exception e) { 16516 if (DEBUG_BACKUP) { 16517 Slog.e(TAG, "Unable to write preferred activities for backup", e); 16518 } 16519 return null; 16520 } 16521 16522 return dataStream.toByteArray(); 16523 } 16524 16525 @Override 16526 public void restorePreferredActivities(byte[] backup, int userId) { 16527 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16528 throw new SecurityException("Only the system may call restorePreferredActivities()"); 16529 } 16530 16531 try { 16532 final XmlPullParser parser = Xml.newPullParser(); 16533 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16534 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 16535 new BlobXmlRestorer() { 16536 @Override 16537 public void apply(XmlPullParser parser, int userId) 16538 throws XmlPullParserException, IOException { 16539 synchronized (mPackages) { 16540 mSettings.readPreferredActivitiesLPw(parser, userId); 16541 } 16542 } 16543 } ); 16544 } catch (Exception e) { 16545 if (DEBUG_BACKUP) { 16546 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16547 } 16548 } 16549 } 16550 16551 /** 16552 * Non-Binder method, support for the backup/restore mechanism: write the 16553 * default browser (etc) settings in its canonical XML format. Returns the default 16554 * browser XML representation as a byte array, or null if there is none. 16555 */ 16556 @Override 16557 public byte[] getDefaultAppsBackup(int userId) { 16558 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16559 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 16560 } 16561 16562 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16563 try { 16564 final XmlSerializer serializer = new FastXmlSerializer(); 16565 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16566 serializer.startDocument(null, true); 16567 serializer.startTag(null, TAG_DEFAULT_APPS); 16568 16569 synchronized (mPackages) { 16570 mSettings.writeDefaultAppsLPr(serializer, userId); 16571 } 16572 16573 serializer.endTag(null, TAG_DEFAULT_APPS); 16574 serializer.endDocument(); 16575 serializer.flush(); 16576 } catch (Exception e) { 16577 if (DEBUG_BACKUP) { 16578 Slog.e(TAG, "Unable to write default apps for backup", e); 16579 } 16580 return null; 16581 } 16582 16583 return dataStream.toByteArray(); 16584 } 16585 16586 @Override 16587 public void restoreDefaultApps(byte[] backup, int userId) { 16588 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16589 throw new SecurityException("Only the system may call restoreDefaultApps()"); 16590 } 16591 16592 try { 16593 final XmlPullParser parser = Xml.newPullParser(); 16594 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16595 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 16596 new BlobXmlRestorer() { 16597 @Override 16598 public void apply(XmlPullParser parser, int userId) 16599 throws XmlPullParserException, IOException { 16600 synchronized (mPackages) { 16601 mSettings.readDefaultAppsLPw(parser, userId); 16602 } 16603 } 16604 } ); 16605 } catch (Exception e) { 16606 if (DEBUG_BACKUP) { 16607 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 16608 } 16609 } 16610 } 16611 16612 @Override 16613 public byte[] getIntentFilterVerificationBackup(int userId) { 16614 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16615 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 16616 } 16617 16618 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16619 try { 16620 final XmlSerializer serializer = new FastXmlSerializer(); 16621 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16622 serializer.startDocument(null, true); 16623 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 16624 16625 synchronized (mPackages) { 16626 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 16627 } 16628 16629 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 16630 serializer.endDocument(); 16631 serializer.flush(); 16632 } catch (Exception e) { 16633 if (DEBUG_BACKUP) { 16634 Slog.e(TAG, "Unable to write default apps for backup", e); 16635 } 16636 return null; 16637 } 16638 16639 return dataStream.toByteArray(); 16640 } 16641 16642 @Override 16643 public void restoreIntentFilterVerification(byte[] backup, int userId) { 16644 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16645 throw new SecurityException("Only the system may call restorePreferredActivities()"); 16646 } 16647 16648 try { 16649 final XmlPullParser parser = Xml.newPullParser(); 16650 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16651 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 16652 new BlobXmlRestorer() { 16653 @Override 16654 public void apply(XmlPullParser parser, int userId) 16655 throws XmlPullParserException, IOException { 16656 synchronized (mPackages) { 16657 mSettings.readAllDomainVerificationsLPr(parser, userId); 16658 mSettings.writeLPr(); 16659 } 16660 } 16661 } ); 16662 } catch (Exception e) { 16663 if (DEBUG_BACKUP) { 16664 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16665 } 16666 } 16667 } 16668 16669 @Override 16670 public byte[] getPermissionGrantBackup(int userId) { 16671 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16672 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 16673 } 16674 16675 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16676 try { 16677 final XmlSerializer serializer = new FastXmlSerializer(); 16678 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16679 serializer.startDocument(null, true); 16680 serializer.startTag(null, TAG_PERMISSION_BACKUP); 16681 16682 synchronized (mPackages) { 16683 serializeRuntimePermissionGrantsLPr(serializer, userId); 16684 } 16685 16686 serializer.endTag(null, TAG_PERMISSION_BACKUP); 16687 serializer.endDocument(); 16688 serializer.flush(); 16689 } catch (Exception e) { 16690 if (DEBUG_BACKUP) { 16691 Slog.e(TAG, "Unable to write default apps for backup", e); 16692 } 16693 return null; 16694 } 16695 16696 return dataStream.toByteArray(); 16697 } 16698 16699 @Override 16700 public void restorePermissionGrants(byte[] backup, int userId) { 16701 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16702 throw new SecurityException("Only the system may call restorePermissionGrants()"); 16703 } 16704 16705 try { 16706 final XmlPullParser parser = Xml.newPullParser(); 16707 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16708 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 16709 new BlobXmlRestorer() { 16710 @Override 16711 public void apply(XmlPullParser parser, int userId) 16712 throws XmlPullParserException, IOException { 16713 synchronized (mPackages) { 16714 processRestoredPermissionGrantsLPr(parser, userId); 16715 } 16716 } 16717 } ); 16718 } catch (Exception e) { 16719 if (DEBUG_BACKUP) { 16720 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16721 } 16722 } 16723 } 16724 16725 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 16726 throws IOException { 16727 serializer.startTag(null, TAG_ALL_GRANTS); 16728 16729 final int N = mSettings.mPackages.size(); 16730 for (int i = 0; i < N; i++) { 16731 final PackageSetting ps = mSettings.mPackages.valueAt(i); 16732 boolean pkgGrantsKnown = false; 16733 16734 PermissionsState packagePerms = ps.getPermissionsState(); 16735 16736 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 16737 final int grantFlags = state.getFlags(); 16738 // only look at grants that are not system/policy fixed 16739 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 16740 final boolean isGranted = state.isGranted(); 16741 // And only back up the user-twiddled state bits 16742 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 16743 final String packageName = mSettings.mPackages.keyAt(i); 16744 if (!pkgGrantsKnown) { 16745 serializer.startTag(null, TAG_GRANT); 16746 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 16747 pkgGrantsKnown = true; 16748 } 16749 16750 final boolean userSet = 16751 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 16752 final boolean userFixed = 16753 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 16754 final boolean revoke = 16755 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 16756 16757 serializer.startTag(null, TAG_PERMISSION); 16758 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 16759 if (isGranted) { 16760 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 16761 } 16762 if (userSet) { 16763 serializer.attribute(null, ATTR_USER_SET, "true"); 16764 } 16765 if (userFixed) { 16766 serializer.attribute(null, ATTR_USER_FIXED, "true"); 16767 } 16768 if (revoke) { 16769 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 16770 } 16771 serializer.endTag(null, TAG_PERMISSION); 16772 } 16773 } 16774 } 16775 16776 if (pkgGrantsKnown) { 16777 serializer.endTag(null, TAG_GRANT); 16778 } 16779 } 16780 16781 serializer.endTag(null, TAG_ALL_GRANTS); 16782 } 16783 16784 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 16785 throws XmlPullParserException, IOException { 16786 String pkgName = null; 16787 int outerDepth = parser.getDepth(); 16788 int type; 16789 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 16790 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 16791 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 16792 continue; 16793 } 16794 16795 final String tagName = parser.getName(); 16796 if (tagName.equals(TAG_GRANT)) { 16797 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 16798 if (DEBUG_BACKUP) { 16799 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 16800 } 16801 } else if (tagName.equals(TAG_PERMISSION)) { 16802 16803 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 16804 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 16805 16806 int newFlagSet = 0; 16807 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 16808 newFlagSet |= FLAG_PERMISSION_USER_SET; 16809 } 16810 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 16811 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 16812 } 16813 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 16814 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 16815 } 16816 if (DEBUG_BACKUP) { 16817 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 16818 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 16819 } 16820 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16821 if (ps != null) { 16822 // Already installed so we apply the grant immediately 16823 if (DEBUG_BACKUP) { 16824 Slog.v(TAG, " + already installed; applying"); 16825 } 16826 PermissionsState perms = ps.getPermissionsState(); 16827 BasePermission bp = mSettings.mPermissions.get(permName); 16828 if (bp != null) { 16829 if (isGranted) { 16830 perms.grantRuntimePermission(bp, userId); 16831 } 16832 if (newFlagSet != 0) { 16833 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 16834 } 16835 } 16836 } else { 16837 // Need to wait for post-restore install to apply the grant 16838 if (DEBUG_BACKUP) { 16839 Slog.v(TAG, " - not yet installed; saving for later"); 16840 } 16841 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 16842 isGranted, newFlagSet, userId); 16843 } 16844 } else { 16845 PackageManagerService.reportSettingsProblem(Log.WARN, 16846 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 16847 XmlUtils.skipCurrentTag(parser); 16848 } 16849 } 16850 16851 scheduleWriteSettingsLocked(); 16852 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 16853 } 16854 16855 @Override 16856 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 16857 int sourceUserId, int targetUserId, int flags) { 16858 mContext.enforceCallingOrSelfPermission( 16859 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 16860 int callingUid = Binder.getCallingUid(); 16861 enforceOwnerRights(ownerPackage, callingUid); 16862 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 16863 if (intentFilter.countActions() == 0) { 16864 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 16865 return; 16866 } 16867 synchronized (mPackages) { 16868 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 16869 ownerPackage, targetUserId, flags); 16870 CrossProfileIntentResolver resolver = 16871 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 16872 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 16873 // We have all those whose filter is equal. Now checking if the rest is equal as well. 16874 if (existing != null) { 16875 int size = existing.size(); 16876 for (int i = 0; i < size; i++) { 16877 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 16878 return; 16879 } 16880 } 16881 } 16882 resolver.addFilter(newFilter); 16883 scheduleWritePackageRestrictionsLocked(sourceUserId); 16884 } 16885 } 16886 16887 @Override 16888 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 16889 mContext.enforceCallingOrSelfPermission( 16890 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 16891 int callingUid = Binder.getCallingUid(); 16892 enforceOwnerRights(ownerPackage, callingUid); 16893 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 16894 synchronized (mPackages) { 16895 CrossProfileIntentResolver resolver = 16896 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 16897 ArraySet<CrossProfileIntentFilter> set = 16898 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 16899 for (CrossProfileIntentFilter filter : set) { 16900 if (filter.getOwnerPackage().equals(ownerPackage)) { 16901 resolver.removeFilter(filter); 16902 } 16903 } 16904 scheduleWritePackageRestrictionsLocked(sourceUserId); 16905 } 16906 } 16907 16908 // Enforcing that callingUid is owning pkg on userId 16909 private void enforceOwnerRights(String pkg, int callingUid) { 16910 // The system owns everything. 16911 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 16912 return; 16913 } 16914 int callingUserId = UserHandle.getUserId(callingUid); 16915 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 16916 if (pi == null) { 16917 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 16918 + callingUserId); 16919 } 16920 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 16921 throw new SecurityException("Calling uid " + callingUid 16922 + " does not own package " + pkg); 16923 } 16924 } 16925 16926 @Override 16927 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 16928 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 16929 } 16930 16931 private Intent getHomeIntent() { 16932 Intent intent = new Intent(Intent.ACTION_MAIN); 16933 intent.addCategory(Intent.CATEGORY_HOME); 16934 return intent; 16935 } 16936 16937 private IntentFilter getHomeFilter() { 16938 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 16939 filter.addCategory(Intent.CATEGORY_HOME); 16940 filter.addCategory(Intent.CATEGORY_DEFAULT); 16941 return filter; 16942 } 16943 16944 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 16945 int userId) { 16946 Intent intent = getHomeIntent(); 16947 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 16948 PackageManager.GET_META_DATA, userId); 16949 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 16950 true, false, false, userId); 16951 16952 allHomeCandidates.clear(); 16953 if (list != null) { 16954 for (ResolveInfo ri : list) { 16955 allHomeCandidates.add(ri); 16956 } 16957 } 16958 return (preferred == null || preferred.activityInfo == null) 16959 ? null 16960 : new ComponentName(preferred.activityInfo.packageName, 16961 preferred.activityInfo.name); 16962 } 16963 16964 @Override 16965 public void setHomeActivity(ComponentName comp, int userId) { 16966 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 16967 getHomeActivitiesAsUser(homeActivities, userId); 16968 16969 boolean found = false; 16970 16971 final int size = homeActivities.size(); 16972 final ComponentName[] set = new ComponentName[size]; 16973 for (int i = 0; i < size; i++) { 16974 final ResolveInfo candidate = homeActivities.get(i); 16975 final ActivityInfo info = candidate.activityInfo; 16976 final ComponentName activityName = new ComponentName(info.packageName, info.name); 16977 set[i] = activityName; 16978 if (!found && activityName.equals(comp)) { 16979 found = true; 16980 } 16981 } 16982 if (!found) { 16983 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 16984 + userId); 16985 } 16986 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 16987 set, comp, userId); 16988 } 16989 16990 private @Nullable String getSetupWizardPackageName() { 16991 final Intent intent = new Intent(Intent.ACTION_MAIN); 16992 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 16993 16994 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 16995 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 16996 | MATCH_DISABLED_COMPONENTS, 16997 UserHandle.myUserId()); 16998 if (matches.size() == 1) { 16999 return matches.get(0).getComponentInfo().packageName; 17000 } else { 17001 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 17002 + ": matches=" + matches); 17003 return null; 17004 } 17005 } 17006 17007 @Override 17008 public void setApplicationEnabledSetting(String appPackageName, 17009 int newState, int flags, int userId, String callingPackage) { 17010 if (!sUserManager.exists(userId)) return; 17011 if (callingPackage == null) { 17012 callingPackage = Integer.toString(Binder.getCallingUid()); 17013 } 17014 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 17015 } 17016 17017 @Override 17018 public void setComponentEnabledSetting(ComponentName componentName, 17019 int newState, int flags, int userId) { 17020 if (!sUserManager.exists(userId)) return; 17021 setEnabledSetting(componentName.getPackageName(), 17022 componentName.getClassName(), newState, flags, userId, null); 17023 } 17024 17025 private void setEnabledSetting(final String packageName, String className, int newState, 17026 final int flags, int userId, String callingPackage) { 17027 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 17028 || newState == COMPONENT_ENABLED_STATE_ENABLED 17029 || newState == COMPONENT_ENABLED_STATE_DISABLED 17030 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17031 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 17032 throw new IllegalArgumentException("Invalid new component state: " 17033 + newState); 17034 } 17035 PackageSetting pkgSetting; 17036 final int uid = Binder.getCallingUid(); 17037 final int permission = mContext.checkCallingOrSelfPermission( 17038 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17039 enforceCrossUserPermission(uid, userId, 17040 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 17041 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17042 boolean sendNow = false; 17043 boolean isApp = (className == null); 17044 String componentName = isApp ? packageName : className; 17045 int packageUid = -1; 17046 ArrayList<String> components; 17047 17048 // writer 17049 synchronized (mPackages) { 17050 pkgSetting = mSettings.mPackages.get(packageName); 17051 if (pkgSetting == null) { 17052 if (className == null) { 17053 throw new IllegalArgumentException("Unknown package: " + packageName); 17054 } 17055 throw new IllegalArgumentException( 17056 "Unknown component: " + packageName + "/" + className); 17057 } 17058 // Allow root and verify that userId is not being specified by a different user 17059 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 17060 throw new SecurityException( 17061 "Permission Denial: attempt to change component state from pid=" 17062 + Binder.getCallingPid() 17063 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 17064 } 17065 if (className == null) { 17066 // We're dealing with an application/package level state change 17067 if (pkgSetting.getEnabled(userId) == newState) { 17068 // Nothing to do 17069 return; 17070 } 17071 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 17072 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 17073 // Don't care about who enables an app. 17074 callingPackage = null; 17075 } 17076 pkgSetting.setEnabled(newState, userId, callingPackage); 17077 // pkgSetting.pkg.mSetEnabled = newState; 17078 } else { 17079 // We're dealing with a component level state change 17080 // First, verify that this is a valid class name. 17081 PackageParser.Package pkg = pkgSetting.pkg; 17082 if (pkg == null || !pkg.hasComponentClassName(className)) { 17083 if (pkg != null && 17084 pkg.applicationInfo.targetSdkVersion >= 17085 Build.VERSION_CODES.JELLY_BEAN) { 17086 throw new IllegalArgumentException("Component class " + className 17087 + " does not exist in " + packageName); 17088 } else { 17089 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 17090 + className + " does not exist in " + packageName); 17091 } 17092 } 17093 switch (newState) { 17094 case COMPONENT_ENABLED_STATE_ENABLED: 17095 if (!pkgSetting.enableComponentLPw(className, userId)) { 17096 return; 17097 } 17098 break; 17099 case COMPONENT_ENABLED_STATE_DISABLED: 17100 if (!pkgSetting.disableComponentLPw(className, userId)) { 17101 return; 17102 } 17103 break; 17104 case COMPONENT_ENABLED_STATE_DEFAULT: 17105 if (!pkgSetting.restoreComponentLPw(className, userId)) { 17106 return; 17107 } 17108 break; 17109 default: 17110 Slog.e(TAG, "Invalid new component state: " + newState); 17111 return; 17112 } 17113 } 17114 scheduleWritePackageRestrictionsLocked(userId); 17115 components = mPendingBroadcasts.get(userId, packageName); 17116 final boolean newPackage = components == null; 17117 if (newPackage) { 17118 components = new ArrayList<String>(); 17119 } 17120 if (!components.contains(componentName)) { 17121 components.add(componentName); 17122 } 17123 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 17124 sendNow = true; 17125 // Purge entry from pending broadcast list if another one exists already 17126 // since we are sending one right away. 17127 mPendingBroadcasts.remove(userId, packageName); 17128 } else { 17129 if (newPackage) { 17130 mPendingBroadcasts.put(userId, packageName, components); 17131 } 17132 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 17133 // Schedule a message 17134 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 17135 } 17136 } 17137 } 17138 17139 long callingId = Binder.clearCallingIdentity(); 17140 try { 17141 if (sendNow) { 17142 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 17143 sendPackageChangedBroadcast(packageName, 17144 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 17145 } 17146 } finally { 17147 Binder.restoreCallingIdentity(callingId); 17148 } 17149 } 17150 17151 @Override 17152 public void flushPackageRestrictionsAsUser(int userId) { 17153 if (!sUserManager.exists(userId)) { 17154 return; 17155 } 17156 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 17157 false /* checkShell */, "flushPackageRestrictions"); 17158 synchronized (mPackages) { 17159 mSettings.writePackageRestrictionsLPr(userId); 17160 mDirtyUsers.remove(userId); 17161 if (mDirtyUsers.isEmpty()) { 17162 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 17163 } 17164 } 17165 } 17166 17167 private void sendPackageChangedBroadcast(String packageName, 17168 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 17169 if (DEBUG_INSTALL) 17170 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 17171 + componentNames); 17172 Bundle extras = new Bundle(4); 17173 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 17174 String nameList[] = new String[componentNames.size()]; 17175 componentNames.toArray(nameList); 17176 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 17177 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 17178 extras.putInt(Intent.EXTRA_UID, packageUid); 17179 // If this is not reporting a change of the overall package, then only send it 17180 // to registered receivers. We don't want to launch a swath of apps for every 17181 // little component state change. 17182 final int flags = !componentNames.contains(packageName) 17183 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 17184 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 17185 new int[] {UserHandle.getUserId(packageUid)}); 17186 } 17187 17188 @Override 17189 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 17190 if (!sUserManager.exists(userId)) return; 17191 final int uid = Binder.getCallingUid(); 17192 final int permission = mContext.checkCallingOrSelfPermission( 17193 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17194 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17195 enforceCrossUserPermission(uid, userId, 17196 true /* requireFullPermission */, true /* checkShell */, "stop package"); 17197 // writer 17198 synchronized (mPackages) { 17199 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 17200 allowedByPermission, uid, userId)) { 17201 scheduleWritePackageRestrictionsLocked(userId); 17202 } 17203 } 17204 } 17205 17206 @Override 17207 public String getInstallerPackageName(String packageName) { 17208 // reader 17209 synchronized (mPackages) { 17210 return mSettings.getInstallerPackageNameLPr(packageName); 17211 } 17212 } 17213 17214 @Override 17215 public int getApplicationEnabledSetting(String packageName, int userId) { 17216 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17217 int uid = Binder.getCallingUid(); 17218 enforceCrossUserPermission(uid, userId, 17219 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 17220 // reader 17221 synchronized (mPackages) { 17222 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 17223 } 17224 } 17225 17226 @Override 17227 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 17228 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17229 int uid = Binder.getCallingUid(); 17230 enforceCrossUserPermission(uid, userId, 17231 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 17232 // reader 17233 synchronized (mPackages) { 17234 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 17235 } 17236 } 17237 17238 @Override 17239 public void enterSafeMode() { 17240 enforceSystemOrRoot("Only the system can request entering safe mode"); 17241 17242 if (!mSystemReady) { 17243 mSafeMode = true; 17244 } 17245 } 17246 17247 @Override 17248 public void systemReady() { 17249 mSystemReady = true; 17250 17251 // Read the compatibilty setting when the system is ready. 17252 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 17253 mContext.getContentResolver(), 17254 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 17255 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 17256 if (DEBUG_SETTINGS) { 17257 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 17258 } 17259 17260 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 17261 17262 synchronized (mPackages) { 17263 // Verify that all of the preferred activity components actually 17264 // exist. It is possible for applications to be updated and at 17265 // that point remove a previously declared activity component that 17266 // had been set as a preferred activity. We try to clean this up 17267 // the next time we encounter that preferred activity, but it is 17268 // possible for the user flow to never be able to return to that 17269 // situation so here we do a sanity check to make sure we haven't 17270 // left any junk around. 17271 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 17272 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17273 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17274 removed.clear(); 17275 for (PreferredActivity pa : pir.filterSet()) { 17276 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 17277 removed.add(pa); 17278 } 17279 } 17280 if (removed.size() > 0) { 17281 for (int r=0; r<removed.size(); r++) { 17282 PreferredActivity pa = removed.get(r); 17283 Slog.w(TAG, "Removing dangling preferred activity: " 17284 + pa.mPref.mComponent); 17285 pir.removeFilter(pa); 17286 } 17287 mSettings.writePackageRestrictionsLPr( 17288 mSettings.mPreferredActivities.keyAt(i)); 17289 } 17290 } 17291 17292 for (int userId : UserManagerService.getInstance().getUserIds()) { 17293 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 17294 grantPermissionsUserIds = ArrayUtils.appendInt( 17295 grantPermissionsUserIds, userId); 17296 } 17297 } 17298 } 17299 sUserManager.systemReady(); 17300 17301 // If we upgraded grant all default permissions before kicking off. 17302 for (int userId : grantPermissionsUserIds) { 17303 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 17304 } 17305 17306 // Kick off any messages waiting for system ready 17307 if (mPostSystemReadyMessages != null) { 17308 for (Message msg : mPostSystemReadyMessages) { 17309 msg.sendToTarget(); 17310 } 17311 mPostSystemReadyMessages = null; 17312 } 17313 17314 // Watch for external volumes that come and go over time 17315 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17316 storage.registerListener(mStorageListener); 17317 17318 mInstallerService.systemReady(); 17319 mPackageDexOptimizer.systemReady(); 17320 17321 MountServiceInternal mountServiceInternal = LocalServices.getService( 17322 MountServiceInternal.class); 17323 mountServiceInternal.addExternalStoragePolicy( 17324 new MountServiceInternal.ExternalStorageMountPolicy() { 17325 @Override 17326 public int getMountMode(int uid, String packageName) { 17327 if (Process.isIsolated(uid)) { 17328 return Zygote.MOUNT_EXTERNAL_NONE; 17329 } 17330 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 17331 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17332 } 17333 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17334 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17335 } 17336 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17337 return Zygote.MOUNT_EXTERNAL_READ; 17338 } 17339 return Zygote.MOUNT_EXTERNAL_WRITE; 17340 } 17341 17342 @Override 17343 public boolean hasExternalStorage(int uid, String packageName) { 17344 return true; 17345 } 17346 }); 17347 } 17348 17349 @Override 17350 public boolean isSafeMode() { 17351 return mSafeMode; 17352 } 17353 17354 @Override 17355 public boolean hasSystemUidErrors() { 17356 return mHasSystemUidErrors; 17357 } 17358 17359 static String arrayToString(int[] array) { 17360 StringBuffer buf = new StringBuffer(128); 17361 buf.append('['); 17362 if (array != null) { 17363 for (int i=0; i<array.length; i++) { 17364 if (i > 0) buf.append(", "); 17365 buf.append(array[i]); 17366 } 17367 } 17368 buf.append(']'); 17369 return buf.toString(); 17370 } 17371 17372 static class DumpState { 17373 public static final int DUMP_LIBS = 1 << 0; 17374 public static final int DUMP_FEATURES = 1 << 1; 17375 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 17376 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 17377 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 17378 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 17379 public static final int DUMP_PERMISSIONS = 1 << 6; 17380 public static final int DUMP_PACKAGES = 1 << 7; 17381 public static final int DUMP_SHARED_USERS = 1 << 8; 17382 public static final int DUMP_MESSAGES = 1 << 9; 17383 public static final int DUMP_PROVIDERS = 1 << 10; 17384 public static final int DUMP_VERIFIERS = 1 << 11; 17385 public static final int DUMP_PREFERRED = 1 << 12; 17386 public static final int DUMP_PREFERRED_XML = 1 << 13; 17387 public static final int DUMP_KEYSETS = 1 << 14; 17388 public static final int DUMP_VERSION = 1 << 15; 17389 public static final int DUMP_INSTALLS = 1 << 16; 17390 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 17391 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 17392 public static final int DUMP_FROZEN = 1 << 19; 17393 17394 public static final int OPTION_SHOW_FILTERS = 1 << 0; 17395 17396 private int mTypes; 17397 17398 private int mOptions; 17399 17400 private boolean mTitlePrinted; 17401 17402 private SharedUserSetting mSharedUser; 17403 17404 public boolean isDumping(int type) { 17405 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 17406 return true; 17407 } 17408 17409 return (mTypes & type) != 0; 17410 } 17411 17412 public void setDump(int type) { 17413 mTypes |= type; 17414 } 17415 17416 public boolean isOptionEnabled(int option) { 17417 return (mOptions & option) != 0; 17418 } 17419 17420 public void setOptionEnabled(int option) { 17421 mOptions |= option; 17422 } 17423 17424 public boolean onTitlePrinted() { 17425 final boolean printed = mTitlePrinted; 17426 mTitlePrinted = true; 17427 return printed; 17428 } 17429 17430 public boolean getTitlePrinted() { 17431 return mTitlePrinted; 17432 } 17433 17434 public void setTitlePrinted(boolean enabled) { 17435 mTitlePrinted = enabled; 17436 } 17437 17438 public SharedUserSetting getSharedUser() { 17439 return mSharedUser; 17440 } 17441 17442 public void setSharedUser(SharedUserSetting user) { 17443 mSharedUser = user; 17444 } 17445 } 17446 17447 @Override 17448 public void onShellCommand(FileDescriptor in, FileDescriptor out, 17449 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 17450 (new PackageManagerShellCommand(this)).exec( 17451 this, in, out, err, args, resultReceiver); 17452 } 17453 17454 @Override 17455 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 17456 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 17457 != PackageManager.PERMISSION_GRANTED) { 17458 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 17459 + Binder.getCallingPid() 17460 + ", uid=" + Binder.getCallingUid() 17461 + " without permission " 17462 + android.Manifest.permission.DUMP); 17463 return; 17464 } 17465 17466 DumpState dumpState = new DumpState(); 17467 boolean fullPreferred = false; 17468 boolean checkin = false; 17469 17470 String packageName = null; 17471 ArraySet<String> permissionNames = null; 17472 17473 int opti = 0; 17474 while (opti < args.length) { 17475 String opt = args[opti]; 17476 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 17477 break; 17478 } 17479 opti++; 17480 17481 if ("-a".equals(opt)) { 17482 // Right now we only know how to print all. 17483 } else if ("-h".equals(opt)) { 17484 pw.println("Package manager dump options:"); 17485 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 17486 pw.println(" --checkin: dump for a checkin"); 17487 pw.println(" -f: print details of intent filters"); 17488 pw.println(" -h: print this help"); 17489 pw.println(" cmd may be one of:"); 17490 pw.println(" l[ibraries]: list known shared libraries"); 17491 pw.println(" f[eatures]: list device features"); 17492 pw.println(" k[eysets]: print known keysets"); 17493 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 17494 pw.println(" perm[issions]: dump permissions"); 17495 pw.println(" permission [name ...]: dump declaration and use of given permission"); 17496 pw.println(" pref[erred]: print preferred package settings"); 17497 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 17498 pw.println(" prov[iders]: dump content providers"); 17499 pw.println(" p[ackages]: dump installed packages"); 17500 pw.println(" s[hared-users]: dump shared user IDs"); 17501 pw.println(" m[essages]: print collected runtime messages"); 17502 pw.println(" v[erifiers]: print package verifier info"); 17503 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 17504 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 17505 pw.println(" version: print database version info"); 17506 pw.println(" write: write current settings now"); 17507 pw.println(" installs: details about install sessions"); 17508 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 17509 pw.println(" <package.name>: info about given package"); 17510 return; 17511 } else if ("--checkin".equals(opt)) { 17512 checkin = true; 17513 } else if ("-f".equals(opt)) { 17514 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 17515 } else { 17516 pw.println("Unknown argument: " + opt + "; use -h for help"); 17517 } 17518 } 17519 17520 // Is the caller requesting to dump a particular piece of data? 17521 if (opti < args.length) { 17522 String cmd = args[opti]; 17523 opti++; 17524 // Is this a package name? 17525 if ("android".equals(cmd) || cmd.contains(".")) { 17526 packageName = cmd; 17527 // When dumping a single package, we always dump all of its 17528 // filter information since the amount of data will be reasonable. 17529 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 17530 } else if ("check-permission".equals(cmd)) { 17531 if (opti >= args.length) { 17532 pw.println("Error: check-permission missing permission argument"); 17533 return; 17534 } 17535 String perm = args[opti]; 17536 opti++; 17537 if (opti >= args.length) { 17538 pw.println("Error: check-permission missing package argument"); 17539 return; 17540 } 17541 String pkg = args[opti]; 17542 opti++; 17543 int user = UserHandle.getUserId(Binder.getCallingUid()); 17544 if (opti < args.length) { 17545 try { 17546 user = Integer.parseInt(args[opti]); 17547 } catch (NumberFormatException e) { 17548 pw.println("Error: check-permission user argument is not a number: " 17549 + args[opti]); 17550 return; 17551 } 17552 } 17553 pw.println(checkPermission(perm, pkg, user)); 17554 return; 17555 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 17556 dumpState.setDump(DumpState.DUMP_LIBS); 17557 } else if ("f".equals(cmd) || "features".equals(cmd)) { 17558 dumpState.setDump(DumpState.DUMP_FEATURES); 17559 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 17560 if (opti >= args.length) { 17561 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 17562 | DumpState.DUMP_SERVICE_RESOLVERS 17563 | DumpState.DUMP_RECEIVER_RESOLVERS 17564 | DumpState.DUMP_CONTENT_RESOLVERS); 17565 } else { 17566 while (opti < args.length) { 17567 String name = args[opti]; 17568 if ("a".equals(name) || "activity".equals(name)) { 17569 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 17570 } else if ("s".equals(name) || "service".equals(name)) { 17571 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 17572 } else if ("r".equals(name) || "receiver".equals(name)) { 17573 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 17574 } else if ("c".equals(name) || "content".equals(name)) { 17575 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 17576 } else { 17577 pw.println("Error: unknown resolver table type: " + name); 17578 return; 17579 } 17580 opti++; 17581 } 17582 } 17583 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 17584 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 17585 } else if ("permission".equals(cmd)) { 17586 if (opti >= args.length) { 17587 pw.println("Error: permission requires permission name"); 17588 return; 17589 } 17590 permissionNames = new ArraySet<>(); 17591 while (opti < args.length) { 17592 permissionNames.add(args[opti]); 17593 opti++; 17594 } 17595 dumpState.setDump(DumpState.DUMP_PERMISSIONS 17596 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 17597 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 17598 dumpState.setDump(DumpState.DUMP_PREFERRED); 17599 } else if ("preferred-xml".equals(cmd)) { 17600 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 17601 if (opti < args.length && "--full".equals(args[opti])) { 17602 fullPreferred = true; 17603 opti++; 17604 } 17605 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 17606 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 17607 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 17608 dumpState.setDump(DumpState.DUMP_PACKAGES); 17609 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 17610 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 17611 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 17612 dumpState.setDump(DumpState.DUMP_PROVIDERS); 17613 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 17614 dumpState.setDump(DumpState.DUMP_MESSAGES); 17615 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 17616 dumpState.setDump(DumpState.DUMP_VERIFIERS); 17617 } else if ("i".equals(cmd) || "ifv".equals(cmd) 17618 || "intent-filter-verifiers".equals(cmd)) { 17619 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 17620 } else if ("version".equals(cmd)) { 17621 dumpState.setDump(DumpState.DUMP_VERSION); 17622 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 17623 dumpState.setDump(DumpState.DUMP_KEYSETS); 17624 } else if ("installs".equals(cmd)) { 17625 dumpState.setDump(DumpState.DUMP_INSTALLS); 17626 } else if ("frozen".equals(cmd)) { 17627 dumpState.setDump(DumpState.DUMP_FROZEN); 17628 } else if ("write".equals(cmd)) { 17629 synchronized (mPackages) { 17630 mSettings.writeLPr(); 17631 pw.println("Settings written."); 17632 return; 17633 } 17634 } 17635 } 17636 17637 if (checkin) { 17638 pw.println("vers,1"); 17639 } 17640 17641 // reader 17642 synchronized (mPackages) { 17643 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 17644 if (!checkin) { 17645 if (dumpState.onTitlePrinted()) 17646 pw.println(); 17647 pw.println("Database versions:"); 17648 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 17649 } 17650 } 17651 17652 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 17653 if (!checkin) { 17654 if (dumpState.onTitlePrinted()) 17655 pw.println(); 17656 pw.println("Verifiers:"); 17657 pw.print(" Required: "); 17658 pw.print(mRequiredVerifierPackage); 17659 pw.print(" (uid="); 17660 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 17661 UserHandle.USER_SYSTEM)); 17662 pw.println(")"); 17663 } else if (mRequiredVerifierPackage != null) { 17664 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 17665 pw.print(","); 17666 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 17667 UserHandle.USER_SYSTEM)); 17668 } 17669 } 17670 17671 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 17672 packageName == null) { 17673 if (mIntentFilterVerifierComponent != null) { 17674 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 17675 if (!checkin) { 17676 if (dumpState.onTitlePrinted()) 17677 pw.println(); 17678 pw.println("Intent Filter Verifier:"); 17679 pw.print(" Using: "); 17680 pw.print(verifierPackageName); 17681 pw.print(" (uid="); 17682 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 17683 UserHandle.USER_SYSTEM)); 17684 pw.println(")"); 17685 } else if (verifierPackageName != null) { 17686 pw.print("ifv,"); pw.print(verifierPackageName); 17687 pw.print(","); 17688 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 17689 UserHandle.USER_SYSTEM)); 17690 } 17691 } else { 17692 pw.println(); 17693 pw.println("No Intent Filter Verifier available!"); 17694 } 17695 } 17696 17697 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 17698 boolean printedHeader = false; 17699 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 17700 while (it.hasNext()) { 17701 String name = it.next(); 17702 SharedLibraryEntry ent = mSharedLibraries.get(name); 17703 if (!checkin) { 17704 if (!printedHeader) { 17705 if (dumpState.onTitlePrinted()) 17706 pw.println(); 17707 pw.println("Libraries:"); 17708 printedHeader = true; 17709 } 17710 pw.print(" "); 17711 } else { 17712 pw.print("lib,"); 17713 } 17714 pw.print(name); 17715 if (!checkin) { 17716 pw.print(" -> "); 17717 } 17718 if (ent.path != null) { 17719 if (!checkin) { 17720 pw.print("(jar) "); 17721 pw.print(ent.path); 17722 } else { 17723 pw.print(",jar,"); 17724 pw.print(ent.path); 17725 } 17726 } else { 17727 if (!checkin) { 17728 pw.print("(apk) "); 17729 pw.print(ent.apk); 17730 } else { 17731 pw.print(",apk,"); 17732 pw.print(ent.apk); 17733 } 17734 } 17735 pw.println(); 17736 } 17737 } 17738 17739 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 17740 if (dumpState.onTitlePrinted()) 17741 pw.println(); 17742 if (!checkin) { 17743 pw.println("Features:"); 17744 } 17745 17746 for (FeatureInfo feat : mAvailableFeatures.values()) { 17747 if (checkin) { 17748 pw.print("feat,"); 17749 pw.print(feat.name); 17750 pw.print(","); 17751 pw.println(feat.version); 17752 } else { 17753 pw.print(" "); 17754 pw.print(feat.name); 17755 if (feat.version > 0) { 17756 pw.print(" version="); 17757 pw.print(feat.version); 17758 } 17759 pw.println(); 17760 } 17761 } 17762 } 17763 17764 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 17765 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 17766 : "Activity Resolver Table:", " ", packageName, 17767 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17768 dumpState.setTitlePrinted(true); 17769 } 17770 } 17771 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 17772 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 17773 : "Receiver Resolver Table:", " ", packageName, 17774 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17775 dumpState.setTitlePrinted(true); 17776 } 17777 } 17778 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 17779 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 17780 : "Service Resolver Table:", " ", packageName, 17781 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17782 dumpState.setTitlePrinted(true); 17783 } 17784 } 17785 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 17786 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 17787 : "Provider Resolver Table:", " ", packageName, 17788 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17789 dumpState.setTitlePrinted(true); 17790 } 17791 } 17792 17793 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 17794 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17795 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17796 int user = mSettings.mPreferredActivities.keyAt(i); 17797 if (pir.dump(pw, 17798 dumpState.getTitlePrinted() 17799 ? "\nPreferred Activities User " + user + ":" 17800 : "Preferred Activities User " + user + ":", " ", 17801 packageName, true, false)) { 17802 dumpState.setTitlePrinted(true); 17803 } 17804 } 17805 } 17806 17807 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 17808 pw.flush(); 17809 FileOutputStream fout = new FileOutputStream(fd); 17810 BufferedOutputStream str = new BufferedOutputStream(fout); 17811 XmlSerializer serializer = new FastXmlSerializer(); 17812 try { 17813 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 17814 serializer.startDocument(null, true); 17815 serializer.setFeature( 17816 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 17817 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 17818 serializer.endDocument(); 17819 serializer.flush(); 17820 } catch (IllegalArgumentException e) { 17821 pw.println("Failed writing: " + e); 17822 } catch (IllegalStateException e) { 17823 pw.println("Failed writing: " + e); 17824 } catch (IOException e) { 17825 pw.println("Failed writing: " + e); 17826 } 17827 } 17828 17829 if (!checkin 17830 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 17831 && packageName == null) { 17832 pw.println(); 17833 int count = mSettings.mPackages.size(); 17834 if (count == 0) { 17835 pw.println("No applications!"); 17836 pw.println(); 17837 } else { 17838 final String prefix = " "; 17839 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 17840 if (allPackageSettings.size() == 0) { 17841 pw.println("No domain preferred apps!"); 17842 pw.println(); 17843 } else { 17844 pw.println("App verification status:"); 17845 pw.println(); 17846 count = 0; 17847 for (PackageSetting ps : allPackageSettings) { 17848 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 17849 if (ivi == null || ivi.getPackageName() == null) continue; 17850 pw.println(prefix + "Package: " + ivi.getPackageName()); 17851 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 17852 pw.println(prefix + "Status: " + ivi.getStatusString()); 17853 pw.println(); 17854 count++; 17855 } 17856 if (count == 0) { 17857 pw.println(prefix + "No app verification established."); 17858 pw.println(); 17859 } 17860 for (int userId : sUserManager.getUserIds()) { 17861 pw.println("App linkages for user " + userId + ":"); 17862 pw.println(); 17863 count = 0; 17864 for (PackageSetting ps : allPackageSettings) { 17865 final long status = ps.getDomainVerificationStatusForUser(userId); 17866 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 17867 continue; 17868 } 17869 pw.println(prefix + "Package: " + ps.name); 17870 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 17871 String statusStr = IntentFilterVerificationInfo. 17872 getStatusStringFromValue(status); 17873 pw.println(prefix + "Status: " + statusStr); 17874 pw.println(); 17875 count++; 17876 } 17877 if (count == 0) { 17878 pw.println(prefix + "No configured app linkages."); 17879 pw.println(); 17880 } 17881 } 17882 } 17883 } 17884 } 17885 17886 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 17887 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 17888 if (packageName == null && permissionNames == null) { 17889 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 17890 if (iperm == 0) { 17891 if (dumpState.onTitlePrinted()) 17892 pw.println(); 17893 pw.println("AppOp Permissions:"); 17894 } 17895 pw.print(" AppOp Permission "); 17896 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 17897 pw.println(":"); 17898 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 17899 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 17900 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 17901 } 17902 } 17903 } 17904 } 17905 17906 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 17907 boolean printedSomething = false; 17908 for (PackageParser.Provider p : mProviders.mProviders.values()) { 17909 if (packageName != null && !packageName.equals(p.info.packageName)) { 17910 continue; 17911 } 17912 if (!printedSomething) { 17913 if (dumpState.onTitlePrinted()) 17914 pw.println(); 17915 pw.println("Registered ContentProviders:"); 17916 printedSomething = true; 17917 } 17918 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 17919 pw.print(" "); pw.println(p.toString()); 17920 } 17921 printedSomething = false; 17922 for (Map.Entry<String, PackageParser.Provider> entry : 17923 mProvidersByAuthority.entrySet()) { 17924 PackageParser.Provider p = entry.getValue(); 17925 if (packageName != null && !packageName.equals(p.info.packageName)) { 17926 continue; 17927 } 17928 if (!printedSomething) { 17929 if (dumpState.onTitlePrinted()) 17930 pw.println(); 17931 pw.println("ContentProvider Authorities:"); 17932 printedSomething = true; 17933 } 17934 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 17935 pw.print(" "); pw.println(p.toString()); 17936 if (p.info != null && p.info.applicationInfo != null) { 17937 final String appInfo = p.info.applicationInfo.toString(); 17938 pw.print(" applicationInfo="); pw.println(appInfo); 17939 } 17940 } 17941 } 17942 17943 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 17944 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 17945 } 17946 17947 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 17948 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 17949 } 17950 17951 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 17952 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 17953 } 17954 17955 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 17956 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 17957 } 17958 17959 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 17960 // XXX should handle packageName != null by dumping only install data that 17961 // the given package is involved with. 17962 if (dumpState.onTitlePrinted()) pw.println(); 17963 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 17964 } 17965 17966 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 17967 // XXX should handle packageName != null by dumping only install data that 17968 // the given package is involved with. 17969 if (dumpState.onTitlePrinted()) pw.println(); 17970 17971 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 17972 ipw.println(); 17973 ipw.println("Frozen packages:"); 17974 ipw.increaseIndent(); 17975 if (mFrozenPackages.size() == 0) { 17976 ipw.println("(none)"); 17977 } else { 17978 for (int i = 0; i < mFrozenPackages.size(); i++) { 17979 ipw.println(mFrozenPackages.valueAt(i)); 17980 } 17981 } 17982 ipw.decreaseIndent(); 17983 } 17984 17985 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 17986 if (dumpState.onTitlePrinted()) pw.println(); 17987 mSettings.dumpReadMessagesLPr(pw, dumpState); 17988 17989 pw.println(); 17990 pw.println("Package warning messages:"); 17991 BufferedReader in = null; 17992 String line = null; 17993 try { 17994 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 17995 while ((line = in.readLine()) != null) { 17996 if (line.contains("ignored: updated version")) continue; 17997 pw.println(line); 17998 } 17999 } catch (IOException ignored) { 18000 } finally { 18001 IoUtils.closeQuietly(in); 18002 } 18003 } 18004 18005 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 18006 BufferedReader in = null; 18007 String line = null; 18008 try { 18009 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18010 while ((line = in.readLine()) != null) { 18011 if (line.contains("ignored: updated version")) continue; 18012 pw.print("msg,"); 18013 pw.println(line); 18014 } 18015 } catch (IOException ignored) { 18016 } finally { 18017 IoUtils.closeQuietly(in); 18018 } 18019 } 18020 } 18021 } 18022 18023 private String dumpDomainString(String packageName) { 18024 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 18025 .getList(); 18026 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 18027 18028 ArraySet<String> result = new ArraySet<>(); 18029 if (iviList.size() > 0) { 18030 for (IntentFilterVerificationInfo ivi : iviList) { 18031 for (String host : ivi.getDomains()) { 18032 result.add(host); 18033 } 18034 } 18035 } 18036 if (filters != null && filters.size() > 0) { 18037 for (IntentFilter filter : filters) { 18038 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 18039 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 18040 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 18041 result.addAll(filter.getHostsList()); 18042 } 18043 } 18044 } 18045 18046 StringBuilder sb = new StringBuilder(result.size() * 16); 18047 for (String domain : result) { 18048 if (sb.length() > 0) sb.append(" "); 18049 sb.append(domain); 18050 } 18051 return sb.toString(); 18052 } 18053 18054 // ------- apps on sdcard specific code ------- 18055 static final boolean DEBUG_SD_INSTALL = false; 18056 18057 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 18058 18059 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 18060 18061 private boolean mMediaMounted = false; 18062 18063 static String getEncryptKey() { 18064 try { 18065 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 18066 SD_ENCRYPTION_KEYSTORE_NAME); 18067 if (sdEncKey == null) { 18068 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 18069 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 18070 if (sdEncKey == null) { 18071 Slog.e(TAG, "Failed to create encryption keys"); 18072 return null; 18073 } 18074 } 18075 return sdEncKey; 18076 } catch (NoSuchAlgorithmException nsae) { 18077 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 18078 return null; 18079 } catch (IOException ioe) { 18080 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 18081 return null; 18082 } 18083 } 18084 18085 /* 18086 * Update media status on PackageManager. 18087 */ 18088 @Override 18089 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 18090 int callingUid = Binder.getCallingUid(); 18091 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 18092 throw new SecurityException("Media status can only be updated by the system"); 18093 } 18094 // reader; this apparently protects mMediaMounted, but should probably 18095 // be a different lock in that case. 18096 synchronized (mPackages) { 18097 Log.i(TAG, "Updating external media status from " 18098 + (mMediaMounted ? "mounted" : "unmounted") + " to " 18099 + (mediaStatus ? "mounted" : "unmounted")); 18100 if (DEBUG_SD_INSTALL) 18101 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 18102 + ", mMediaMounted=" + mMediaMounted); 18103 if (mediaStatus == mMediaMounted) { 18104 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 18105 : 0, -1); 18106 mHandler.sendMessage(msg); 18107 return; 18108 } 18109 mMediaMounted = mediaStatus; 18110 } 18111 // Queue up an async operation since the package installation may take a 18112 // little while. 18113 mHandler.post(new Runnable() { 18114 public void run() { 18115 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 18116 } 18117 }); 18118 } 18119 18120 /** 18121 * Called by MountService when the initial ASECs to scan are available. 18122 * Should block until all the ASEC containers are finished being scanned. 18123 */ 18124 public void scanAvailableAsecs() { 18125 updateExternalMediaStatusInner(true, false, false); 18126 } 18127 18128 /* 18129 * Collect information of applications on external media, map them against 18130 * existing containers and update information based on current mount status. 18131 * Please note that we always have to report status if reportStatus has been 18132 * set to true especially when unloading packages. 18133 */ 18134 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 18135 boolean externalStorage) { 18136 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 18137 int[] uidArr = EmptyArray.INT; 18138 18139 final String[] list = PackageHelper.getSecureContainerList(); 18140 if (ArrayUtils.isEmpty(list)) { 18141 Log.i(TAG, "No secure containers found"); 18142 } else { 18143 // Process list of secure containers and categorize them 18144 // as active or stale based on their package internal state. 18145 18146 // reader 18147 synchronized (mPackages) { 18148 for (String cid : list) { 18149 // Leave stages untouched for now; installer service owns them 18150 if (PackageInstallerService.isStageName(cid)) continue; 18151 18152 if (DEBUG_SD_INSTALL) 18153 Log.i(TAG, "Processing container " + cid); 18154 String pkgName = getAsecPackageName(cid); 18155 if (pkgName == null) { 18156 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 18157 continue; 18158 } 18159 if (DEBUG_SD_INSTALL) 18160 Log.i(TAG, "Looking for pkg : " + pkgName); 18161 18162 final PackageSetting ps = mSettings.mPackages.get(pkgName); 18163 if (ps == null) { 18164 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 18165 continue; 18166 } 18167 18168 /* 18169 * Skip packages that are not external if we're unmounting 18170 * external storage. 18171 */ 18172 if (externalStorage && !isMounted && !isExternal(ps)) { 18173 continue; 18174 } 18175 18176 final AsecInstallArgs args = new AsecInstallArgs(cid, 18177 getAppDexInstructionSets(ps), ps.isForwardLocked()); 18178 // The package status is changed only if the code path 18179 // matches between settings and the container id. 18180 if (ps.codePathString != null 18181 && ps.codePathString.startsWith(args.getCodePath())) { 18182 if (DEBUG_SD_INSTALL) { 18183 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 18184 + " at code path: " + ps.codePathString); 18185 } 18186 18187 // We do have a valid package installed on sdcard 18188 processCids.put(args, ps.codePathString); 18189 final int uid = ps.appId; 18190 if (uid != -1) { 18191 uidArr = ArrayUtils.appendInt(uidArr, uid); 18192 } 18193 } else { 18194 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 18195 + ps.codePathString); 18196 } 18197 } 18198 } 18199 18200 Arrays.sort(uidArr); 18201 } 18202 18203 // Process packages with valid entries. 18204 if (isMounted) { 18205 if (DEBUG_SD_INSTALL) 18206 Log.i(TAG, "Loading packages"); 18207 loadMediaPackages(processCids, uidArr, externalStorage); 18208 startCleaningPackages(); 18209 mInstallerService.onSecureContainersAvailable(); 18210 } else { 18211 if (DEBUG_SD_INSTALL) 18212 Log.i(TAG, "Unloading packages"); 18213 unloadMediaPackages(processCids, uidArr, reportStatus); 18214 } 18215 } 18216 18217 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18218 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 18219 final int size = infos.size(); 18220 final String[] packageNames = new String[size]; 18221 final int[] packageUids = new int[size]; 18222 for (int i = 0; i < size; i++) { 18223 final ApplicationInfo info = infos.get(i); 18224 packageNames[i] = info.packageName; 18225 packageUids[i] = info.uid; 18226 } 18227 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 18228 finishedReceiver); 18229 } 18230 18231 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18232 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18233 sendResourcesChangedBroadcast(mediaStatus, replacing, 18234 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 18235 } 18236 18237 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18238 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18239 int size = pkgList.length; 18240 if (size > 0) { 18241 // Send broadcasts here 18242 Bundle extras = new Bundle(); 18243 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 18244 if (uidArr != null) { 18245 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 18246 } 18247 if (replacing) { 18248 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 18249 } 18250 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 18251 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 18252 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 18253 } 18254 } 18255 18256 /* 18257 * Look at potentially valid container ids from processCids If package 18258 * information doesn't match the one on record or package scanning fails, 18259 * the cid is added to list of removeCids. We currently don't delete stale 18260 * containers. 18261 */ 18262 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 18263 boolean externalStorage) { 18264 ArrayList<String> pkgList = new ArrayList<String>(); 18265 Set<AsecInstallArgs> keys = processCids.keySet(); 18266 18267 for (AsecInstallArgs args : keys) { 18268 String codePath = processCids.get(args); 18269 if (DEBUG_SD_INSTALL) 18270 Log.i(TAG, "Loading container : " + args.cid); 18271 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 18272 try { 18273 // Make sure there are no container errors first. 18274 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 18275 Slog.e(TAG, "Failed to mount cid : " + args.cid 18276 + " when installing from sdcard"); 18277 continue; 18278 } 18279 // Check code path here. 18280 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 18281 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 18282 + " does not match one in settings " + codePath); 18283 continue; 18284 } 18285 // Parse package 18286 int parseFlags = mDefParseFlags; 18287 if (args.isExternalAsec()) { 18288 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 18289 } 18290 if (args.isFwdLocked()) { 18291 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 18292 } 18293 18294 synchronized (mInstallLock) { 18295 PackageParser.Package pkg = null; 18296 try { 18297 // Sadly we don't know the package name yet to freeze it 18298 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 18299 SCAN_IGNORE_FROZEN, 0, null); 18300 } catch (PackageManagerException e) { 18301 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 18302 } 18303 // Scan the package 18304 if (pkg != null) { 18305 /* 18306 * TODO why is the lock being held? doPostInstall is 18307 * called in other places without the lock. This needs 18308 * to be straightened out. 18309 */ 18310 // writer 18311 synchronized (mPackages) { 18312 retCode = PackageManager.INSTALL_SUCCEEDED; 18313 pkgList.add(pkg.packageName); 18314 // Post process args 18315 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 18316 pkg.applicationInfo.uid); 18317 } 18318 } else { 18319 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 18320 } 18321 } 18322 18323 } finally { 18324 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 18325 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 18326 } 18327 } 18328 } 18329 // writer 18330 synchronized (mPackages) { 18331 // If the platform SDK has changed since the last time we booted, 18332 // we need to re-grant app permission to catch any new ones that 18333 // appear. This is really a hack, and means that apps can in some 18334 // cases get permissions that the user didn't initially explicitly 18335 // allow... it would be nice to have some better way to handle 18336 // this situation. 18337 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 18338 : mSettings.getInternalVersion(); 18339 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 18340 : StorageManager.UUID_PRIVATE_INTERNAL; 18341 18342 int updateFlags = UPDATE_PERMISSIONS_ALL; 18343 if (ver.sdkVersion != mSdkVersion) { 18344 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 18345 + mSdkVersion + "; regranting permissions for external"); 18346 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 18347 } 18348 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 18349 18350 // Yay, everything is now upgraded 18351 ver.forceCurrent(); 18352 18353 // can downgrade to reader 18354 // Persist settings 18355 mSettings.writeLPr(); 18356 } 18357 // Send a broadcast to let everyone know we are done processing 18358 if (pkgList.size() > 0) { 18359 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 18360 } 18361 } 18362 18363 /* 18364 * Utility method to unload a list of specified containers 18365 */ 18366 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 18367 // Just unmount all valid containers. 18368 for (AsecInstallArgs arg : cidArgs) { 18369 synchronized (mInstallLock) { 18370 arg.doPostDeleteLI(false); 18371 } 18372 } 18373 } 18374 18375 /* 18376 * Unload packages mounted on external media. This involves deleting package 18377 * data from internal structures, sending broadcasts about disabled packages, 18378 * gc'ing to free up references, unmounting all secure containers 18379 * corresponding to packages on external media, and posting a 18380 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 18381 * that we always have to post this message if status has been requested no 18382 * matter what. 18383 */ 18384 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 18385 final boolean reportStatus) { 18386 if (DEBUG_SD_INSTALL) 18387 Log.i(TAG, "unloading media packages"); 18388 ArrayList<String> pkgList = new ArrayList<String>(); 18389 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 18390 final Set<AsecInstallArgs> keys = processCids.keySet(); 18391 for (AsecInstallArgs args : keys) { 18392 String pkgName = args.getPackageName(); 18393 if (DEBUG_SD_INSTALL) 18394 Log.i(TAG, "Trying to unload pkg : " + pkgName); 18395 // Delete package internally 18396 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 18397 synchronized (mInstallLock) { 18398 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 18399 final boolean res; 18400 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 18401 "unloadMediaPackages")) { 18402 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 18403 null); 18404 } 18405 if (res) { 18406 pkgList.add(pkgName); 18407 } else { 18408 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 18409 failedList.add(args); 18410 } 18411 } 18412 } 18413 18414 // reader 18415 synchronized (mPackages) { 18416 // We didn't update the settings after removing each package; 18417 // write them now for all packages. 18418 mSettings.writeLPr(); 18419 } 18420 18421 // We have to absolutely send UPDATED_MEDIA_STATUS only 18422 // after confirming that all the receivers processed the ordered 18423 // broadcast when packages get disabled, force a gc to clean things up. 18424 // and unload all the containers. 18425 if (pkgList.size() > 0) { 18426 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 18427 new IIntentReceiver.Stub() { 18428 public void performReceive(Intent intent, int resultCode, String data, 18429 Bundle extras, boolean ordered, boolean sticky, 18430 int sendingUser) throws RemoteException { 18431 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 18432 reportStatus ? 1 : 0, 1, keys); 18433 mHandler.sendMessage(msg); 18434 } 18435 }); 18436 } else { 18437 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 18438 keys); 18439 mHandler.sendMessage(msg); 18440 } 18441 } 18442 18443 private void loadPrivatePackages(final VolumeInfo vol) { 18444 mHandler.post(new Runnable() { 18445 @Override 18446 public void run() { 18447 loadPrivatePackagesInner(vol); 18448 } 18449 }); 18450 } 18451 18452 private void loadPrivatePackagesInner(VolumeInfo vol) { 18453 final String volumeUuid = vol.fsUuid; 18454 if (TextUtils.isEmpty(volumeUuid)) { 18455 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 18456 return; 18457 } 18458 18459 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 18460 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 18461 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 18462 18463 final VersionInfo ver; 18464 final List<PackageSetting> packages; 18465 synchronized (mPackages) { 18466 ver = mSettings.findOrCreateVersion(volumeUuid); 18467 packages = mSettings.getVolumePackagesLPr(volumeUuid); 18468 } 18469 18470 for (PackageSetting ps : packages) { 18471 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 18472 synchronized (mInstallLock) { 18473 final PackageParser.Package pkg; 18474 try { 18475 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 18476 loaded.add(pkg.applicationInfo); 18477 18478 } catch (PackageManagerException e) { 18479 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 18480 } 18481 18482 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 18483 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 18484 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 18485 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 18486 } 18487 } 18488 } 18489 18490 // Reconcile app data for all started/unlocked users 18491 final StorageManager sm = mContext.getSystemService(StorageManager.class); 18492 final UserManager um = mContext.getSystemService(UserManager.class); 18493 for (UserInfo user : um.getUsers()) { 18494 final int flags; 18495 if (um.isUserUnlocked(user.id)) { 18496 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18497 } else if (um.isUserRunning(user.id)) { 18498 flags = StorageManager.FLAG_STORAGE_DE; 18499 } else { 18500 continue; 18501 } 18502 18503 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 18504 synchronized (mInstallLock) { 18505 reconcileAppsDataLI(volumeUuid, user.id, flags); 18506 } 18507 } 18508 18509 synchronized (mPackages) { 18510 int updateFlags = UPDATE_PERMISSIONS_ALL; 18511 if (ver.sdkVersion != mSdkVersion) { 18512 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 18513 + mSdkVersion + "; regranting permissions for " + volumeUuid); 18514 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 18515 } 18516 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 18517 18518 // Yay, everything is now upgraded 18519 ver.forceCurrent(); 18520 18521 mSettings.writeLPr(); 18522 } 18523 18524 for (PackageFreezer freezer : freezers) { 18525 freezer.close(); 18526 } 18527 18528 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 18529 sendResourcesChangedBroadcast(true, false, loaded, null); 18530 } 18531 18532 private void unloadPrivatePackages(final VolumeInfo vol) { 18533 mHandler.post(new Runnable() { 18534 @Override 18535 public void run() { 18536 unloadPrivatePackagesInner(vol); 18537 } 18538 }); 18539 } 18540 18541 private void unloadPrivatePackagesInner(VolumeInfo vol) { 18542 final String volumeUuid = vol.fsUuid; 18543 if (TextUtils.isEmpty(volumeUuid)) { 18544 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 18545 return; 18546 } 18547 18548 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 18549 synchronized (mInstallLock) { 18550 synchronized (mPackages) { 18551 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 18552 for (PackageSetting ps : packages) { 18553 if (ps.pkg == null) continue; 18554 18555 final ApplicationInfo info = ps.pkg.applicationInfo; 18556 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 18557 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 18558 18559 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 18560 "unloadPrivatePackagesInner")) { 18561 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 18562 false, null)) { 18563 unloaded.add(info); 18564 } else { 18565 Slog.w(TAG, "Failed to unload " + ps.codePath); 18566 } 18567 } 18568 } 18569 18570 mSettings.writeLPr(); 18571 } 18572 } 18573 18574 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 18575 sendResourcesChangedBroadcast(false, false, unloaded, null); 18576 } 18577 18578 /** 18579 * Examine all users present on given mounted volume, and destroy data 18580 * belonging to users that are no longer valid, or whose user ID has been 18581 * recycled. 18582 */ 18583 private void reconcileUsers(String volumeUuid) { 18584 // TODO: also reconcile DE directories 18585 final File[] files = FileUtils 18586 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)); 18587 for (File file : files) { 18588 if (!file.isDirectory()) continue; 18589 18590 final int userId; 18591 final UserInfo info; 18592 try { 18593 userId = Integer.parseInt(file.getName()); 18594 info = sUserManager.getUserInfo(userId); 18595 } catch (NumberFormatException e) { 18596 Slog.w(TAG, "Invalid user directory " + file); 18597 continue; 18598 } 18599 18600 boolean destroyUser = false; 18601 if (info == null) { 18602 logCriticalInfo(Log.WARN, "Destroying user directory " + file 18603 + " because no matching user was found"); 18604 destroyUser = true; 18605 } else { 18606 try { 18607 UserManagerService.enforceSerialNumber(file, info.serialNumber); 18608 } catch (IOException e) { 18609 logCriticalInfo(Log.WARN, "Destroying user directory " + file 18610 + " because we failed to enforce serial number: " + e); 18611 destroyUser = true; 18612 } 18613 } 18614 18615 if (destroyUser) { 18616 synchronized (mInstallLock) { 18617 try { 18618 mInstaller.removeUserDataDirs(volumeUuid, userId); 18619 } catch (InstallerException e) { 18620 Slog.w(TAG, "Failed to clean up user dirs", e); 18621 } 18622 } 18623 } 18624 } 18625 } 18626 18627 private void assertPackageKnown(String volumeUuid, String packageName) 18628 throws PackageManagerException { 18629 synchronized (mPackages) { 18630 final PackageSetting ps = mSettings.mPackages.get(packageName); 18631 if (ps == null) { 18632 throw new PackageManagerException("Package " + packageName + " is unknown"); 18633 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 18634 throw new PackageManagerException( 18635 "Package " + packageName + " found on unknown volume " + volumeUuid 18636 + "; expected volume " + ps.volumeUuid); 18637 } 18638 } 18639 } 18640 18641 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 18642 throws PackageManagerException { 18643 synchronized (mPackages) { 18644 final PackageSetting ps = mSettings.mPackages.get(packageName); 18645 if (ps == null) { 18646 throw new PackageManagerException("Package " + packageName + " is unknown"); 18647 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 18648 throw new PackageManagerException( 18649 "Package " + packageName + " found on unknown volume " + volumeUuid 18650 + "; expected volume " + ps.volumeUuid); 18651 } else if (!ps.getInstalled(userId)) { 18652 throw new PackageManagerException( 18653 "Package " + packageName + " not installed for user " + userId); 18654 } 18655 } 18656 } 18657 18658 /** 18659 * Examine all apps present on given mounted volume, and destroy apps that 18660 * aren't expected, either due to uninstallation or reinstallation on 18661 * another volume. 18662 */ 18663 private void reconcileApps(String volumeUuid) { 18664 final File[] files = FileUtils 18665 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 18666 for (File file : files) { 18667 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 18668 && !PackageInstallerService.isStageName(file.getName()); 18669 if (!isPackage) { 18670 // Ignore entries which are not packages 18671 continue; 18672 } 18673 18674 try { 18675 final PackageLite pkg = PackageParser.parsePackageLite(file, 18676 PackageParser.PARSE_MUST_BE_APK); 18677 assertPackageKnown(volumeUuid, pkg.packageName); 18678 18679 } catch (PackageParserException | PackageManagerException e) { 18680 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 18681 synchronized (mInstallLock) { 18682 removeCodePathLI(file); 18683 } 18684 } 18685 } 18686 } 18687 18688 /** 18689 * Reconcile all app data for the given user. 18690 * <p> 18691 * Verifies that directories exist and that ownership and labeling is 18692 * correct for all installed apps on all mounted volumes. 18693 */ 18694 void reconcileAppsData(int userId, int flags) { 18695 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18696 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 18697 final String volumeUuid = vol.getFsUuid(); 18698 synchronized (mInstallLock) { 18699 reconcileAppsDataLI(volumeUuid, userId, flags); 18700 } 18701 } 18702 } 18703 18704 /** 18705 * Reconcile all app data on given mounted volume. 18706 * <p> 18707 * Destroys app data that isn't expected, either due to uninstallation or 18708 * reinstallation on another volume. 18709 * <p> 18710 * Verifies that directories exist and that ownership and labeling is 18711 * correct for all installed apps. 18712 */ 18713 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) { 18714 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 18715 + Integer.toHexString(flags)); 18716 18717 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 18718 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 18719 18720 boolean restoreconNeeded = false; 18721 18722 // First look for stale data that doesn't belong, and check if things 18723 // have changed since we did our last restorecon 18724 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18725 if (!isUserKeyUnlocked(userId)) { 18726 throw new RuntimeException( 18727 "Yikes, someone asked us to reconcile CE storage while " + userId 18728 + " was still locked; this would have caused massive data loss!"); 18729 } 18730 18731 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 18732 18733 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 18734 for (File file : files) { 18735 final String packageName = file.getName(); 18736 try { 18737 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 18738 } catch (PackageManagerException e) { 18739 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 18740 try { 18741 mInstaller.destroyAppData(volumeUuid, packageName, userId, 18742 StorageManager.FLAG_STORAGE_CE, 0); 18743 } catch (InstallerException e2) { 18744 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 18745 } 18746 } 18747 } 18748 } 18749 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 18750 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 18751 18752 final File[] files = FileUtils.listFilesOrEmpty(deDir); 18753 for (File file : files) { 18754 final String packageName = file.getName(); 18755 try { 18756 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 18757 } catch (PackageManagerException e) { 18758 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 18759 try { 18760 mInstaller.destroyAppData(volumeUuid, packageName, userId, 18761 StorageManager.FLAG_STORAGE_DE, 0); 18762 } catch (InstallerException e2) { 18763 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 18764 } 18765 } 18766 } 18767 } 18768 18769 // Ensure that data directories are ready to roll for all packages 18770 // installed for this volume and user 18771 final List<PackageSetting> packages; 18772 synchronized (mPackages) { 18773 packages = mSettings.getVolumePackagesLPr(volumeUuid); 18774 } 18775 int preparedCount = 0; 18776 for (PackageSetting ps : packages) { 18777 final String packageName = ps.name; 18778 if (ps.pkg == null) { 18779 Slog.w(TAG, "Odd, missing scanned package " + packageName); 18780 // TODO: might be due to legacy ASEC apps; we should circle back 18781 // and reconcile again once they're scanned 18782 continue; 18783 } 18784 18785 if (ps.getInstalled(userId)) { 18786 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 18787 18788 if (maybeMigrateAppDataLIF(ps.pkg, userId)) { 18789 // We may have just shuffled around app data directories, so 18790 // prepare them one more time 18791 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 18792 } 18793 18794 preparedCount++; 18795 } 18796 } 18797 18798 if (restoreconNeeded) { 18799 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18800 SELinuxMMAC.setRestoreconDone(ceDir); 18801 } 18802 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 18803 SELinuxMMAC.setRestoreconDone(deDir); 18804 } 18805 } 18806 18807 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 18808 + " packages; restoreconNeeded was " + restoreconNeeded); 18809 } 18810 18811 /** 18812 * Prepare app data for the given app just after it was installed or 18813 * upgraded. This method carefully only touches users that it's installed 18814 * for, and it forces a restorecon to handle any seinfo changes. 18815 * <p> 18816 * Verifies that directories exist and that ownership and labeling is 18817 * correct for all installed apps. If there is an ownership mismatch, it 18818 * will try recovering system apps by wiping data; third-party app data is 18819 * left intact. 18820 * <p> 18821 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 18822 */ 18823 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 18824 final PackageSetting ps; 18825 synchronized (mPackages) { 18826 ps = mSettings.mPackages.get(pkg.packageName); 18827 mSettings.writeKernelMappingLPr(ps); 18828 } 18829 18830 final UserManager um = mContext.getSystemService(UserManager.class); 18831 for (UserInfo user : um.getUsers()) { 18832 final int flags; 18833 if (um.isUserUnlocked(user.id)) { 18834 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18835 } else if (um.isUserRunning(user.id)) { 18836 flags = StorageManager.FLAG_STORAGE_DE; 18837 } else { 18838 continue; 18839 } 18840 18841 if (ps.getInstalled(user.id)) { 18842 // Whenever an app changes, force a restorecon of its data 18843 // TODO: when user data is locked, mark that we're still dirty 18844 prepareAppDataLIF(pkg, user.id, flags, true); 18845 } 18846 } 18847 } 18848 18849 /** 18850 * Prepare app data for the given app. 18851 * <p> 18852 * Verifies that directories exist and that ownership and labeling is 18853 * correct for all installed apps. If there is an ownership mismatch, this 18854 * will try recovering system apps by wiping data; third-party app data is 18855 * left intact. 18856 */ 18857 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags, 18858 boolean restoreconNeeded) { 18859 if (pkg == null) { 18860 Slog.wtf(TAG, "Package was null!", new Throwable()); 18861 return; 18862 } 18863 prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded); 18864 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 18865 for (int i = 0; i < childCount; i++) { 18866 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded); 18867 } 18868 } 18869 18870 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags, 18871 boolean restoreconNeeded) { 18872 if (DEBUG_APP_DATA) { 18873 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 18874 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 18875 } 18876 18877 final String volumeUuid = pkg.volumeUuid; 18878 final String packageName = pkg.packageName; 18879 final ApplicationInfo app = pkg.applicationInfo; 18880 final int appId = UserHandle.getAppId(app.uid); 18881 18882 Preconditions.checkNotNull(app.seinfo); 18883 18884 try { 18885 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 18886 appId, app.seinfo, app.targetSdkVersion); 18887 } catch (InstallerException e) { 18888 if (app.isSystemApp()) { 18889 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 18890 + ", but trying to recover: " + e); 18891 destroyAppDataLeafLIF(pkg, userId, flags); 18892 try { 18893 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 18894 appId, app.seinfo, app.targetSdkVersion); 18895 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 18896 } catch (InstallerException e2) { 18897 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 18898 } 18899 } else { 18900 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 18901 } 18902 } 18903 18904 if (restoreconNeeded) { 18905 try { 18906 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, 18907 app.seinfo); 18908 } catch (InstallerException e) { 18909 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 18910 } 18911 } 18912 18913 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18914 try { 18915 // CE storage is unlocked right now, so read out the inode and 18916 // remember for use later when it's locked 18917 // TODO: mark this structure as dirty so we persist it! 18918 final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId, 18919 StorageManager.FLAG_STORAGE_CE); 18920 synchronized (mPackages) { 18921 final PackageSetting ps = mSettings.mPackages.get(packageName); 18922 if (ps != null) { 18923 ps.setCeDataInode(ceDataInode, userId); 18924 } 18925 } 18926 } catch (InstallerException e) { 18927 Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e); 18928 } 18929 } 18930 18931 prepareAppDataContentsLeafLIF(pkg, userId, flags); 18932 } 18933 18934 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 18935 if (pkg == null) { 18936 Slog.wtf(TAG, "Package was null!", new Throwable()); 18937 return; 18938 } 18939 prepareAppDataContentsLeafLIF(pkg, userId, flags); 18940 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 18941 for (int i = 0; i < childCount; i++) { 18942 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 18943 } 18944 } 18945 18946 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 18947 final String volumeUuid = pkg.volumeUuid; 18948 final String packageName = pkg.packageName; 18949 final ApplicationInfo app = pkg.applicationInfo; 18950 18951 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18952 // Create a native library symlink only if we have native libraries 18953 // and if the native libraries are 32 bit libraries. We do not provide 18954 // this symlink for 64 bit libraries. 18955 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 18956 final String nativeLibPath = app.nativeLibraryDir; 18957 try { 18958 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 18959 nativeLibPath, userId); 18960 } catch (InstallerException e) { 18961 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 18962 } 18963 } 18964 } 18965 } 18966 18967 /** 18968 * For system apps on non-FBE devices, this method migrates any existing 18969 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 18970 * requested by the app. 18971 */ 18972 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 18973 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 18974 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 18975 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 18976 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 18977 try { 18978 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 18979 storageTarget); 18980 } catch (InstallerException e) { 18981 logCriticalInfo(Log.WARN, 18982 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 18983 } 18984 return true; 18985 } else { 18986 return false; 18987 } 18988 } 18989 18990 public PackageFreezer freezePackage(String packageName, String killReason) { 18991 return new PackageFreezer(packageName, killReason); 18992 } 18993 18994 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 18995 String killReason) { 18996 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 18997 return new PackageFreezer(); 18998 } else { 18999 return freezePackage(packageName, killReason); 19000 } 19001 } 19002 19003 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 19004 String killReason) { 19005 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 19006 return new PackageFreezer(); 19007 } else { 19008 return freezePackage(packageName, killReason); 19009 } 19010 } 19011 19012 /** 19013 * Class that freezes and kills the given package upon creation, and 19014 * unfreezes it upon closing. This is typically used when doing surgery on 19015 * app code/data to prevent the app from running while you're working. 19016 */ 19017 private class PackageFreezer implements AutoCloseable { 19018 private final String mPackageName; 19019 private final PackageFreezer[] mChildren; 19020 19021 private final boolean mWeFroze; 19022 19023 private final AtomicBoolean mClosed = new AtomicBoolean(); 19024 private final CloseGuard mCloseGuard = CloseGuard.get(); 19025 19026 /** 19027 * Create and return a stub freezer that doesn't actually do anything, 19028 * typically used when someone requested 19029 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 19030 * {@link PackageManager#DELETE_DONT_KILL_APP}. 19031 */ 19032 public PackageFreezer() { 19033 mPackageName = null; 19034 mChildren = null; 19035 mWeFroze = false; 19036 mCloseGuard.open("close"); 19037 } 19038 19039 public PackageFreezer(String packageName, String killReason) { 19040 synchronized (mPackages) { 19041 mPackageName = packageName; 19042 mWeFroze = mFrozenPackages.add(mPackageName); 19043 19044 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 19045 if (ps != null) { 19046 killApplication(ps.name, ps.appId, killReason); 19047 } 19048 19049 final PackageParser.Package p = mPackages.get(packageName); 19050 if (p != null && p.childPackages != null) { 19051 final int N = p.childPackages.size(); 19052 mChildren = new PackageFreezer[N]; 19053 for (int i = 0; i < N; i++) { 19054 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 19055 killReason); 19056 } 19057 } else { 19058 mChildren = null; 19059 } 19060 } 19061 mCloseGuard.open("close"); 19062 } 19063 19064 @Override 19065 protected void finalize() throws Throwable { 19066 try { 19067 mCloseGuard.warnIfOpen(); 19068 close(); 19069 } finally { 19070 super.finalize(); 19071 } 19072 } 19073 19074 @Override 19075 public void close() { 19076 mCloseGuard.close(); 19077 if (mClosed.compareAndSet(false, true)) { 19078 synchronized (mPackages) { 19079 if (mWeFroze) { 19080 mFrozenPackages.remove(mPackageName); 19081 } 19082 19083 if (mChildren != null) { 19084 for (PackageFreezer freezer : mChildren) { 19085 freezer.close(); 19086 } 19087 } 19088 } 19089 } 19090 } 19091 } 19092 19093 /** 19094 * Verify that given package is currently frozen. 19095 */ 19096 private void checkPackageFrozen(String packageName) { 19097 synchronized (mPackages) { 19098 if (!mFrozenPackages.contains(packageName)) { 19099 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 19100 } 19101 } 19102 } 19103 19104 @Override 19105 public int movePackage(final String packageName, final String volumeUuid) { 19106 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19107 19108 final int moveId = mNextMoveId.getAndIncrement(); 19109 mHandler.post(new Runnable() { 19110 @Override 19111 public void run() { 19112 try { 19113 movePackageInternal(packageName, volumeUuid, moveId); 19114 } catch (PackageManagerException e) { 19115 Slog.w(TAG, "Failed to move " + packageName, e); 19116 mMoveCallbacks.notifyStatusChanged(moveId, 19117 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19118 } 19119 } 19120 }); 19121 return moveId; 19122 } 19123 19124 private void movePackageInternal(final String packageName, final String volumeUuid, 19125 final int moveId) throws PackageManagerException { 19126 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 19127 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19128 final PackageManager pm = mContext.getPackageManager(); 19129 19130 final boolean currentAsec; 19131 final String currentVolumeUuid; 19132 final File codeFile; 19133 final String installerPackageName; 19134 final String packageAbiOverride; 19135 final int appId; 19136 final String seinfo; 19137 final String label; 19138 final int targetSdkVersion; 19139 final PackageFreezer freezer; 19140 19141 // reader 19142 synchronized (mPackages) { 19143 final PackageParser.Package pkg = mPackages.get(packageName); 19144 final PackageSetting ps = mSettings.mPackages.get(packageName); 19145 if (pkg == null || ps == null) { 19146 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 19147 } 19148 19149 if (pkg.applicationInfo.isSystemApp()) { 19150 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 19151 "Cannot move system application"); 19152 } 19153 19154 if (pkg.applicationInfo.isExternalAsec()) { 19155 currentAsec = true; 19156 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 19157 } else if (pkg.applicationInfo.isForwardLocked()) { 19158 currentAsec = true; 19159 currentVolumeUuid = "forward_locked"; 19160 } else { 19161 currentAsec = false; 19162 currentVolumeUuid = ps.volumeUuid; 19163 19164 final File probe = new File(pkg.codePath); 19165 final File probeOat = new File(probe, "oat"); 19166 if (!probe.isDirectory() || !probeOat.isDirectory()) { 19167 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19168 "Move only supported for modern cluster style installs"); 19169 } 19170 } 19171 19172 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 19173 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19174 "Package already moved to " + volumeUuid); 19175 } 19176 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 19177 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 19178 "Device admin cannot be moved"); 19179 } 19180 19181 if (mFrozenPackages.contains(packageName)) { 19182 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 19183 "Failed to move already frozen package"); 19184 } 19185 19186 codeFile = new File(pkg.codePath); 19187 installerPackageName = ps.installerPackageName; 19188 packageAbiOverride = ps.cpuAbiOverrideString; 19189 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 19190 seinfo = pkg.applicationInfo.seinfo; 19191 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 19192 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 19193 freezer = new PackageFreezer(packageName, "movePackageInternal"); 19194 } 19195 19196 final Bundle extras = new Bundle(); 19197 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 19198 extras.putString(Intent.EXTRA_TITLE, label); 19199 mMoveCallbacks.notifyCreated(moveId, extras); 19200 19201 int installFlags; 19202 final boolean moveCompleteApp; 19203 final File measurePath; 19204 19205 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 19206 installFlags = INSTALL_INTERNAL; 19207 moveCompleteApp = !currentAsec; 19208 measurePath = Environment.getDataAppDirectory(volumeUuid); 19209 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 19210 installFlags = INSTALL_EXTERNAL; 19211 moveCompleteApp = false; 19212 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 19213 } else { 19214 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 19215 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 19216 || !volume.isMountedWritable()) { 19217 freezer.close(); 19218 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19219 "Move location not mounted private volume"); 19220 } 19221 19222 Preconditions.checkState(!currentAsec); 19223 19224 installFlags = INSTALL_INTERNAL; 19225 moveCompleteApp = true; 19226 measurePath = Environment.getDataAppDirectory(volumeUuid); 19227 } 19228 19229 final PackageStats stats = new PackageStats(null, -1); 19230 synchronized (mInstaller) { 19231 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 19232 freezer.close(); 19233 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19234 "Failed to measure package size"); 19235 } 19236 } 19237 19238 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 19239 + stats.dataSize); 19240 19241 final long startFreeBytes = measurePath.getFreeSpace(); 19242 final long sizeBytes; 19243 if (moveCompleteApp) { 19244 sizeBytes = stats.codeSize + stats.dataSize; 19245 } else { 19246 sizeBytes = stats.codeSize; 19247 } 19248 19249 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 19250 freezer.close(); 19251 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19252 "Not enough free space to move"); 19253 } 19254 19255 mMoveCallbacks.notifyStatusChanged(moveId, 10); 19256 19257 final CountDownLatch installedLatch = new CountDownLatch(1); 19258 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 19259 @Override 19260 public void onUserActionRequired(Intent intent) throws RemoteException { 19261 throw new IllegalStateException(); 19262 } 19263 19264 @Override 19265 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 19266 Bundle extras) throws RemoteException { 19267 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 19268 + PackageManager.installStatusToString(returnCode, msg)); 19269 19270 installedLatch.countDown(); 19271 freezer.close(); 19272 19273 final int status = PackageManager.installStatusToPublicStatus(returnCode); 19274 switch (status) { 19275 case PackageInstaller.STATUS_SUCCESS: 19276 mMoveCallbacks.notifyStatusChanged(moveId, 19277 PackageManager.MOVE_SUCCEEDED); 19278 break; 19279 case PackageInstaller.STATUS_FAILURE_STORAGE: 19280 mMoveCallbacks.notifyStatusChanged(moveId, 19281 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 19282 break; 19283 default: 19284 mMoveCallbacks.notifyStatusChanged(moveId, 19285 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19286 break; 19287 } 19288 } 19289 }; 19290 19291 final MoveInfo move; 19292 if (moveCompleteApp) { 19293 // Kick off a thread to report progress estimates 19294 new Thread() { 19295 @Override 19296 public void run() { 19297 while (true) { 19298 try { 19299 if (installedLatch.await(1, TimeUnit.SECONDS)) { 19300 break; 19301 } 19302 } catch (InterruptedException ignored) { 19303 } 19304 19305 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 19306 final int progress = 10 + (int) MathUtils.constrain( 19307 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 19308 mMoveCallbacks.notifyStatusChanged(moveId, progress); 19309 } 19310 } 19311 }.start(); 19312 19313 final String dataAppName = codeFile.getName(); 19314 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 19315 dataAppName, appId, seinfo, targetSdkVersion); 19316 } else { 19317 move = null; 19318 } 19319 19320 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 19321 19322 final Message msg = mHandler.obtainMessage(INIT_COPY); 19323 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 19324 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 19325 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 19326 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/); 19327 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 19328 msg.obj = params; 19329 19330 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 19331 System.identityHashCode(msg.obj)); 19332 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 19333 System.identityHashCode(msg.obj)); 19334 19335 mHandler.sendMessage(msg); 19336 } 19337 19338 @Override 19339 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 19340 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19341 19342 final int realMoveId = mNextMoveId.getAndIncrement(); 19343 final Bundle extras = new Bundle(); 19344 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 19345 mMoveCallbacks.notifyCreated(realMoveId, extras); 19346 19347 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 19348 @Override 19349 public void onCreated(int moveId, Bundle extras) { 19350 // Ignored 19351 } 19352 19353 @Override 19354 public void onStatusChanged(int moveId, int status, long estMillis) { 19355 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 19356 } 19357 }; 19358 19359 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19360 storage.setPrimaryStorageUuid(volumeUuid, callback); 19361 return realMoveId; 19362 } 19363 19364 @Override 19365 public int getMoveStatus(int moveId) { 19366 mContext.enforceCallingOrSelfPermission( 19367 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19368 return mMoveCallbacks.mLastStatus.get(moveId); 19369 } 19370 19371 @Override 19372 public void registerMoveCallback(IPackageMoveObserver callback) { 19373 mContext.enforceCallingOrSelfPermission( 19374 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19375 mMoveCallbacks.register(callback); 19376 } 19377 19378 @Override 19379 public void unregisterMoveCallback(IPackageMoveObserver callback) { 19380 mContext.enforceCallingOrSelfPermission( 19381 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19382 mMoveCallbacks.unregister(callback); 19383 } 19384 19385 @Override 19386 public boolean setInstallLocation(int loc) { 19387 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 19388 null); 19389 if (getInstallLocation() == loc) { 19390 return true; 19391 } 19392 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 19393 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 19394 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 19395 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 19396 return true; 19397 } 19398 return false; 19399 } 19400 19401 @Override 19402 public int getInstallLocation() { 19403 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 19404 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 19405 PackageHelper.APP_INSTALL_AUTO); 19406 } 19407 19408 /** Called by UserManagerService */ 19409 void cleanUpUser(UserManagerService userManager, int userHandle) { 19410 synchronized (mPackages) { 19411 mDirtyUsers.remove(userHandle); 19412 mUserNeedsBadging.delete(userHandle); 19413 mSettings.removeUserLPw(userHandle); 19414 mPendingBroadcasts.remove(userHandle); 19415 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 19416 } 19417 synchronized (mInstallLock) { 19418 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19419 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19420 final String volumeUuid = vol.getFsUuid(); 19421 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 19422 try { 19423 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 19424 } catch (InstallerException e) { 19425 Slog.w(TAG, "Failed to remove user data", e); 19426 } 19427 } 19428 synchronized (mPackages) { 19429 removeUnusedPackagesLILPw(userManager, userHandle); 19430 } 19431 } 19432 } 19433 19434 /** 19435 * We're removing userHandle and would like to remove any downloaded packages 19436 * that are no longer in use by any other user. 19437 * @param userHandle the user being removed 19438 */ 19439 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 19440 final boolean DEBUG_CLEAN_APKS = false; 19441 int [] users = userManager.getUserIds(); 19442 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 19443 while (psit.hasNext()) { 19444 PackageSetting ps = psit.next(); 19445 if (ps.pkg == null) { 19446 continue; 19447 } 19448 final String packageName = ps.pkg.packageName; 19449 // Skip over if system app 19450 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 19451 continue; 19452 } 19453 if (DEBUG_CLEAN_APKS) { 19454 Slog.i(TAG, "Checking package " + packageName); 19455 } 19456 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 19457 if (keep) { 19458 if (DEBUG_CLEAN_APKS) { 19459 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 19460 } 19461 } else { 19462 for (int i = 0; i < users.length; i++) { 19463 if (users[i] != userHandle && ps.getInstalled(users[i])) { 19464 keep = true; 19465 if (DEBUG_CLEAN_APKS) { 19466 Slog.i(TAG, " Keeping package " + packageName + " for user " 19467 + users[i]); 19468 } 19469 break; 19470 } 19471 } 19472 } 19473 if (!keep) { 19474 if (DEBUG_CLEAN_APKS) { 19475 Slog.i(TAG, " Removing package " + packageName); 19476 } 19477 mHandler.post(new Runnable() { 19478 public void run() { 19479 deletePackageX(packageName, userHandle, 0); 19480 } //end run 19481 }); 19482 } 19483 } 19484 } 19485 19486 /** Called by UserManagerService */ 19487 void createNewUser(int userHandle) { 19488 synchronized (mInstallLock) { 19489 try { 19490 mInstaller.createUserConfig(userHandle); 19491 } catch (InstallerException e) { 19492 Slog.w(TAG, "Failed to create user config", e); 19493 } 19494 mSettings.createNewUserLI(this, mInstaller, userHandle); 19495 } 19496 synchronized (mPackages) { 19497 applyFactoryDefaultBrowserLPw(userHandle); 19498 primeDomainVerificationsLPw(userHandle); 19499 } 19500 } 19501 19502 void newUserCreated(final int userHandle) { 19503 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 19504 // If permission review for legacy apps is required, we represent 19505 // dagerous permissions for such apps as always granted runtime 19506 // permissions to keep per user flag state whether review is needed. 19507 // Hence, if a new user is added we have to propagate dangerous 19508 // permission grants for these legacy apps. 19509 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 19510 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 19511 | UPDATE_PERMISSIONS_REPLACE_ALL); 19512 } 19513 } 19514 19515 @Override 19516 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 19517 mContext.enforceCallingOrSelfPermission( 19518 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 19519 "Only package verification agents can read the verifier device identity"); 19520 19521 synchronized (mPackages) { 19522 return mSettings.getVerifierDeviceIdentityLPw(); 19523 } 19524 } 19525 19526 @Override 19527 public void setPermissionEnforced(String permission, boolean enforced) { 19528 // TODO: Now that we no longer change GID for storage, this should to away. 19529 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 19530 "setPermissionEnforced"); 19531 if (READ_EXTERNAL_STORAGE.equals(permission)) { 19532 synchronized (mPackages) { 19533 if (mSettings.mReadExternalStorageEnforced == null 19534 || mSettings.mReadExternalStorageEnforced != enforced) { 19535 mSettings.mReadExternalStorageEnforced = enforced; 19536 mSettings.writeLPr(); 19537 } 19538 } 19539 // kill any non-foreground processes so we restart them and 19540 // grant/revoke the GID. 19541 final IActivityManager am = ActivityManagerNative.getDefault(); 19542 if (am != null) { 19543 final long token = Binder.clearCallingIdentity(); 19544 try { 19545 am.killProcessesBelowForeground("setPermissionEnforcement"); 19546 } catch (RemoteException e) { 19547 } finally { 19548 Binder.restoreCallingIdentity(token); 19549 } 19550 } 19551 } else { 19552 throw new IllegalArgumentException("No selective enforcement for " + permission); 19553 } 19554 } 19555 19556 @Override 19557 @Deprecated 19558 public boolean isPermissionEnforced(String permission) { 19559 return true; 19560 } 19561 19562 @Override 19563 public boolean isStorageLow() { 19564 final long token = Binder.clearCallingIdentity(); 19565 try { 19566 final DeviceStorageMonitorInternal 19567 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 19568 if (dsm != null) { 19569 return dsm.isMemoryLow(); 19570 } else { 19571 return false; 19572 } 19573 } finally { 19574 Binder.restoreCallingIdentity(token); 19575 } 19576 } 19577 19578 @Override 19579 public IPackageInstaller getPackageInstaller() { 19580 return mInstallerService; 19581 } 19582 19583 private boolean userNeedsBadging(int userId) { 19584 int index = mUserNeedsBadging.indexOfKey(userId); 19585 if (index < 0) { 19586 final UserInfo userInfo; 19587 final long token = Binder.clearCallingIdentity(); 19588 try { 19589 userInfo = sUserManager.getUserInfo(userId); 19590 } finally { 19591 Binder.restoreCallingIdentity(token); 19592 } 19593 final boolean b; 19594 if (userInfo != null && userInfo.isManagedProfile()) { 19595 b = true; 19596 } else { 19597 b = false; 19598 } 19599 mUserNeedsBadging.put(userId, b); 19600 return b; 19601 } 19602 return mUserNeedsBadging.valueAt(index); 19603 } 19604 19605 @Override 19606 public KeySet getKeySetByAlias(String packageName, String alias) { 19607 if (packageName == null || alias == null) { 19608 return null; 19609 } 19610 synchronized(mPackages) { 19611 final PackageParser.Package pkg = mPackages.get(packageName); 19612 if (pkg == null) { 19613 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19614 throw new IllegalArgumentException("Unknown package: " + packageName); 19615 } 19616 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19617 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 19618 } 19619 } 19620 19621 @Override 19622 public KeySet getSigningKeySet(String packageName) { 19623 if (packageName == null) { 19624 return null; 19625 } 19626 synchronized(mPackages) { 19627 final PackageParser.Package pkg = mPackages.get(packageName); 19628 if (pkg == null) { 19629 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19630 throw new IllegalArgumentException("Unknown package: " + packageName); 19631 } 19632 if (pkg.applicationInfo.uid != Binder.getCallingUid() 19633 && Process.SYSTEM_UID != Binder.getCallingUid()) { 19634 throw new SecurityException("May not access signing KeySet of other apps."); 19635 } 19636 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19637 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 19638 } 19639 } 19640 19641 @Override 19642 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 19643 if (packageName == null || ks == null) { 19644 return false; 19645 } 19646 synchronized(mPackages) { 19647 final PackageParser.Package pkg = mPackages.get(packageName); 19648 if (pkg == null) { 19649 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19650 throw new IllegalArgumentException("Unknown package: " + packageName); 19651 } 19652 IBinder ksh = ks.getToken(); 19653 if (ksh instanceof KeySetHandle) { 19654 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19655 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 19656 } 19657 return false; 19658 } 19659 } 19660 19661 @Override 19662 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 19663 if (packageName == null || ks == null) { 19664 return false; 19665 } 19666 synchronized(mPackages) { 19667 final PackageParser.Package pkg = mPackages.get(packageName); 19668 if (pkg == null) { 19669 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19670 throw new IllegalArgumentException("Unknown package: " + packageName); 19671 } 19672 IBinder ksh = ks.getToken(); 19673 if (ksh instanceof KeySetHandle) { 19674 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19675 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 19676 } 19677 return false; 19678 } 19679 } 19680 19681 private void deletePackageIfUnusedLPr(final String packageName) { 19682 PackageSetting ps = mSettings.mPackages.get(packageName); 19683 if (ps == null) { 19684 return; 19685 } 19686 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 19687 // TODO Implement atomic delete if package is unused 19688 // It is currently possible that the package will be deleted even if it is installed 19689 // after this method returns. 19690 mHandler.post(new Runnable() { 19691 public void run() { 19692 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 19693 } 19694 }); 19695 } 19696 } 19697 19698 /** 19699 * Check and throw if the given before/after packages would be considered a 19700 * downgrade. 19701 */ 19702 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 19703 throws PackageManagerException { 19704 if (after.versionCode < before.mVersionCode) { 19705 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 19706 "Update version code " + after.versionCode + " is older than current " 19707 + before.mVersionCode); 19708 } else if (after.versionCode == before.mVersionCode) { 19709 if (after.baseRevisionCode < before.baseRevisionCode) { 19710 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 19711 "Update base revision code " + after.baseRevisionCode 19712 + " is older than current " + before.baseRevisionCode); 19713 } 19714 19715 if (!ArrayUtils.isEmpty(after.splitNames)) { 19716 for (int i = 0; i < after.splitNames.length; i++) { 19717 final String splitName = after.splitNames[i]; 19718 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 19719 if (j != -1) { 19720 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 19721 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 19722 "Update split " + splitName + " revision code " 19723 + after.splitRevisionCodes[i] + " is older than current " 19724 + before.splitRevisionCodes[j]); 19725 } 19726 } 19727 } 19728 } 19729 } 19730 } 19731 19732 private static class MoveCallbacks extends Handler { 19733 private static final int MSG_CREATED = 1; 19734 private static final int MSG_STATUS_CHANGED = 2; 19735 19736 private final RemoteCallbackList<IPackageMoveObserver> 19737 mCallbacks = new RemoteCallbackList<>(); 19738 19739 private final SparseIntArray mLastStatus = new SparseIntArray(); 19740 19741 public MoveCallbacks(Looper looper) { 19742 super(looper); 19743 } 19744 19745 public void register(IPackageMoveObserver callback) { 19746 mCallbacks.register(callback); 19747 } 19748 19749 public void unregister(IPackageMoveObserver callback) { 19750 mCallbacks.unregister(callback); 19751 } 19752 19753 @Override 19754 public void handleMessage(Message msg) { 19755 final SomeArgs args = (SomeArgs) msg.obj; 19756 final int n = mCallbacks.beginBroadcast(); 19757 for (int i = 0; i < n; i++) { 19758 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 19759 try { 19760 invokeCallback(callback, msg.what, args); 19761 } catch (RemoteException ignored) { 19762 } 19763 } 19764 mCallbacks.finishBroadcast(); 19765 args.recycle(); 19766 } 19767 19768 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 19769 throws RemoteException { 19770 switch (what) { 19771 case MSG_CREATED: { 19772 callback.onCreated(args.argi1, (Bundle) args.arg2); 19773 break; 19774 } 19775 case MSG_STATUS_CHANGED: { 19776 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 19777 break; 19778 } 19779 } 19780 } 19781 19782 private void notifyCreated(int moveId, Bundle extras) { 19783 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 19784 19785 final SomeArgs args = SomeArgs.obtain(); 19786 args.argi1 = moveId; 19787 args.arg2 = extras; 19788 obtainMessage(MSG_CREATED, args).sendToTarget(); 19789 } 19790 19791 private void notifyStatusChanged(int moveId, int status) { 19792 notifyStatusChanged(moveId, status, -1); 19793 } 19794 19795 private void notifyStatusChanged(int moveId, int status, long estMillis) { 19796 Slog.v(TAG, "Move " + moveId + " status " + status); 19797 19798 final SomeArgs args = SomeArgs.obtain(); 19799 args.argi1 = moveId; 19800 args.argi2 = status; 19801 args.arg3 = estMillis; 19802 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 19803 19804 synchronized (mLastStatus) { 19805 mLastStatus.put(moveId, status); 19806 } 19807 } 19808 } 19809 19810 private final static class OnPermissionChangeListeners extends Handler { 19811 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 19812 19813 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 19814 new RemoteCallbackList<>(); 19815 19816 public OnPermissionChangeListeners(Looper looper) { 19817 super(looper); 19818 } 19819 19820 @Override 19821 public void handleMessage(Message msg) { 19822 switch (msg.what) { 19823 case MSG_ON_PERMISSIONS_CHANGED: { 19824 final int uid = msg.arg1; 19825 handleOnPermissionsChanged(uid); 19826 } break; 19827 } 19828 } 19829 19830 public void addListenerLocked(IOnPermissionsChangeListener listener) { 19831 mPermissionListeners.register(listener); 19832 19833 } 19834 19835 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 19836 mPermissionListeners.unregister(listener); 19837 } 19838 19839 public void onPermissionsChanged(int uid) { 19840 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 19841 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 19842 } 19843 } 19844 19845 private void handleOnPermissionsChanged(int uid) { 19846 final int count = mPermissionListeners.beginBroadcast(); 19847 try { 19848 for (int i = 0; i < count; i++) { 19849 IOnPermissionsChangeListener callback = mPermissionListeners 19850 .getBroadcastItem(i); 19851 try { 19852 callback.onPermissionsChanged(uid); 19853 } catch (RemoteException e) { 19854 Log.e(TAG, "Permission listener is dead", e); 19855 } 19856 } 19857 } finally { 19858 mPermissionListeners.finishBroadcast(); 19859 } 19860 } 19861 } 19862 19863 private class PackageManagerInternalImpl extends PackageManagerInternal { 19864 @Override 19865 public void setLocationPackagesProvider(PackagesProvider provider) { 19866 synchronized (mPackages) { 19867 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 19868 } 19869 } 19870 19871 @Override 19872 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 19873 synchronized (mPackages) { 19874 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 19875 } 19876 } 19877 19878 @Override 19879 public void setSmsAppPackagesProvider(PackagesProvider provider) { 19880 synchronized (mPackages) { 19881 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 19882 } 19883 } 19884 19885 @Override 19886 public void setDialerAppPackagesProvider(PackagesProvider provider) { 19887 synchronized (mPackages) { 19888 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 19889 } 19890 } 19891 19892 @Override 19893 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 19894 synchronized (mPackages) { 19895 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 19896 } 19897 } 19898 19899 @Override 19900 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 19901 synchronized (mPackages) { 19902 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 19903 } 19904 } 19905 19906 @Override 19907 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 19908 synchronized (mPackages) { 19909 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 19910 packageName, userId); 19911 } 19912 } 19913 19914 @Override 19915 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 19916 synchronized (mPackages) { 19917 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 19918 packageName, userId); 19919 } 19920 } 19921 19922 @Override 19923 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 19924 synchronized (mPackages) { 19925 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 19926 packageName, userId); 19927 } 19928 } 19929 19930 @Override 19931 public void setKeepUninstalledPackages(final List<String> packageList) { 19932 Preconditions.checkNotNull(packageList); 19933 List<String> removedFromList = null; 19934 synchronized (mPackages) { 19935 if (mKeepUninstalledPackages != null) { 19936 final int packagesCount = mKeepUninstalledPackages.size(); 19937 for (int i = 0; i < packagesCount; i++) { 19938 String oldPackage = mKeepUninstalledPackages.get(i); 19939 if (packageList != null && packageList.contains(oldPackage)) { 19940 continue; 19941 } 19942 if (removedFromList == null) { 19943 removedFromList = new ArrayList<>(); 19944 } 19945 removedFromList.add(oldPackage); 19946 } 19947 } 19948 mKeepUninstalledPackages = new ArrayList<>(packageList); 19949 if (removedFromList != null) { 19950 final int removedCount = removedFromList.size(); 19951 for (int i = 0; i < removedCount; i++) { 19952 deletePackageIfUnusedLPr(removedFromList.get(i)); 19953 } 19954 } 19955 } 19956 } 19957 19958 @Override 19959 public boolean isPermissionsReviewRequired(String packageName, int userId) { 19960 synchronized (mPackages) { 19961 // If we do not support permission review, done. 19962 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 19963 return false; 19964 } 19965 19966 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 19967 if (packageSetting == null) { 19968 return false; 19969 } 19970 19971 // Permission review applies only to apps not supporting the new permission model. 19972 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 19973 return false; 19974 } 19975 19976 // Legacy apps have the permission and get user consent on launch. 19977 PermissionsState permissionsState = packageSetting.getPermissionsState(); 19978 return permissionsState.isPermissionReviewRequired(userId); 19979 } 19980 } 19981 19982 @Override 19983 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 19984 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 19985 } 19986 19987 @Override 19988 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 19989 int userId) { 19990 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 19991 } 19992 } 19993 19994 @Override 19995 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 19996 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 19997 synchronized (mPackages) { 19998 final long identity = Binder.clearCallingIdentity(); 19999 try { 20000 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 20001 packageNames, userId); 20002 } finally { 20003 Binder.restoreCallingIdentity(identity); 20004 } 20005 } 20006 } 20007 20008 private static void enforceSystemOrPhoneCaller(String tag) { 20009 int callingUid = Binder.getCallingUid(); 20010 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 20011 throw new SecurityException( 20012 "Cannot call " + tag + " from UID " + callingUid); 20013 } 20014 } 20015 20016 boolean isHistoricalPackageUsageAvailable() { 20017 return mPackageUsage.isHistoricalPackageUsageAvailable(); 20018 } 20019 20020 /** 20021 * Return a <b>copy</b> of the collection of packages known to the package manager. 20022 * @return A copy of the values of mPackages. 20023 */ 20024 Collection<PackageParser.Package> getPackages() { 20025 synchronized (mPackages) { 20026 return new ArrayList<>(mPackages.values()); 20027 } 20028 } 20029 20030 /** 20031 * Logs process start information (including base APK hash) to the security log. 20032 * @hide 20033 */ 20034 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 20035 String apkFile, int pid) { 20036 if (!SecurityLog.isLoggingEnabled()) { 20037 return; 20038 } 20039 Bundle data = new Bundle(); 20040 data.putLong("startTimestamp", System.currentTimeMillis()); 20041 data.putString("processName", processName); 20042 data.putInt("uid", uid); 20043 data.putString("seinfo", seinfo); 20044 data.putString("apkFile", apkFile); 20045 data.putInt("pid", pid); 20046 Message msg = mProcessLoggingHandler.obtainMessage( 20047 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 20048 msg.setData(data); 20049 mProcessLoggingHandler.sendMessage(msg); 20050 } 20051} 20052