PackageManagerService.java revision c30808b413deff60fafa047d9cc15c275feb3c63
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; 21import static android.Manifest.permission.WRITE_MEDIA_STORAGE; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 27import static android.content.pm.PackageManager.DELETE_KEEP_DATA; 28import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 29import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED; 30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 31import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 32import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 34import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET; 35import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 36import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 37import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 38import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 40import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 41import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 42import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 43import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 44import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 45import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 46import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 47import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 48import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 49import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 50import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 51import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 52import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 53import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 54import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 55import static android.content.pm.PackageManager.INSTALL_INTERNAL; 56import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK; 59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 62import static android.content.pm.PackageManager.MATCH_ALL; 63import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 64import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE; 65import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE; 66import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS; 67import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY; 68import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY; 69import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 70import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN; 71import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 72import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 73import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 74import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 75import static android.content.pm.PackageManager.PERMISSION_DENIED; 76import static android.content.pm.PackageManager.PERMISSION_GRANTED; 77import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED; 78import static android.content.pm.PackageParser.isApkFile; 79import static android.os.Process.PACKAGE_INFO_GID; 80import static android.os.Process.SYSTEM_UID; 81import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 82import static android.system.OsConstants.O_CREAT; 83import static android.system.OsConstants.O_RDWR; 84 85import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 86import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 87import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 88import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 89import static com.android.internal.util.ArrayUtils.appendInt; 90import static com.android.server.pm.Installer.DEXOPT_PUBLIC; 91import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 92import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 93import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 94import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 95import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 96import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason; 97import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter; 98import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 99import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 100import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 101 102import android.Manifest; 103import android.annotation.NonNull; 104import android.annotation.Nullable; 105import android.app.ActivityManager; 106import android.app.ActivityManagerNative; 107import android.app.IActivityManager; 108import android.app.admin.DevicePolicyManagerInternal; 109import android.app.admin.IDevicePolicyManager; 110import android.app.admin.SecurityLog; 111import android.app.backup.IBackupManager; 112import android.content.BroadcastReceiver; 113import android.content.ComponentName; 114import android.content.Context; 115import android.content.IIntentReceiver; 116import android.content.Intent; 117import android.content.IntentFilter; 118import android.content.IntentSender; 119import android.content.IntentSender.SendIntentException; 120import android.content.ServiceConnection; 121import android.content.pm.ActivityInfo; 122import android.content.pm.ApplicationInfo; 123import android.content.pm.AppsQueryHelper; 124import android.content.pm.ComponentInfo; 125import android.content.pm.EphemeralApplicationInfo; 126import android.content.pm.EphemeralResolveInfo; 127import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo; 128import android.content.pm.FeatureInfo; 129import android.content.pm.IOnPermissionsChangeListener; 130import android.content.pm.IPackageDataObserver; 131import android.content.pm.IPackageDeleteObserver; 132import android.content.pm.IPackageDeleteObserver2; 133import android.content.pm.IPackageInstallObserver2; 134import android.content.pm.IPackageInstaller; 135import android.content.pm.IPackageManager; 136import android.content.pm.IPackageMoveObserver; 137import android.content.pm.IPackageStatsObserver; 138import android.content.pm.InstrumentationInfo; 139import android.content.pm.IntentFilterVerificationInfo; 140import android.content.pm.KeySet; 141import android.content.pm.PackageCleanItem; 142import android.content.pm.PackageInfo; 143import android.content.pm.PackageInfoLite; 144import android.content.pm.PackageInstaller; 145import android.content.pm.PackageManager; 146import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 147import android.content.pm.PackageManagerInternal; 148import android.content.pm.PackageParser; 149import android.content.pm.PackageParser.ActivityIntentInfo; 150import android.content.pm.PackageParser.PackageLite; 151import android.content.pm.PackageParser.PackageParserException; 152import android.content.pm.PackageStats; 153import android.content.pm.PackageUserState; 154import android.content.pm.ParceledListSlice; 155import android.content.pm.PermissionGroupInfo; 156import android.content.pm.PermissionInfo; 157import android.content.pm.ProviderInfo; 158import android.content.pm.ResolveInfo; 159import android.content.pm.ServiceInfo; 160import android.content.pm.Signature; 161import android.content.pm.UserInfo; 162import android.content.pm.VerifierDeviceIdentity; 163import android.content.pm.VerifierInfo; 164import android.content.res.Resources; 165import android.graphics.Bitmap; 166import android.hardware.display.DisplayManager; 167import android.net.Uri; 168import android.os.Binder; 169import android.os.Build; 170import android.os.Bundle; 171import android.os.Debug; 172import android.os.Environment; 173import android.os.Environment.UserEnvironment; 174import android.os.FileUtils; 175import android.os.Handler; 176import android.os.IBinder; 177import android.os.Looper; 178import android.os.Message; 179import android.os.Parcel; 180import android.os.ParcelFileDescriptor; 181import android.os.Process; 182import android.os.RemoteCallbackList; 183import android.os.RemoteException; 184import android.os.ResultReceiver; 185import android.os.SELinux; 186import android.os.ServiceManager; 187import android.os.SystemClock; 188import android.os.SystemProperties; 189import android.os.Trace; 190import android.os.UserHandle; 191import android.os.UserManager; 192import android.os.UserManagerInternal; 193import android.os.storage.IMountService; 194import android.os.storage.MountServiceInternal; 195import android.os.storage.StorageEventListener; 196import android.os.storage.StorageManager; 197import android.os.storage.VolumeInfo; 198import android.os.storage.VolumeRecord; 199import android.security.KeyStore; 200import android.security.SystemKeyStore; 201import android.system.ErrnoException; 202import android.system.Os; 203import android.text.TextUtils; 204import android.text.format.DateUtils; 205import android.util.ArrayMap; 206import android.util.ArraySet; 207import android.util.AtomicFile; 208import android.util.DisplayMetrics; 209import android.util.EventLog; 210import android.util.ExceptionUtils; 211import android.util.Log; 212import android.util.LogPrinter; 213import android.util.MathUtils; 214import android.util.PrintStreamPrinter; 215import android.util.Slog; 216import android.util.SparseArray; 217import android.util.SparseBooleanArray; 218import android.util.SparseIntArray; 219import android.util.Xml; 220import android.util.jar.StrictJarFile; 221import android.view.Display; 222 223import com.android.internal.R; 224import com.android.internal.annotations.GuardedBy; 225import com.android.internal.app.IMediaContainerService; 226import com.android.internal.app.ResolverActivity; 227import com.android.internal.content.NativeLibraryHelper; 228import com.android.internal.content.PackageHelper; 229import com.android.internal.logging.MetricsLogger; 230import com.android.internal.os.IParcelFileDescriptorFactory; 231import com.android.internal.os.InstallerConnection.InstallerException; 232import com.android.internal.os.SomeArgs; 233import com.android.internal.os.Zygote; 234import com.android.internal.telephony.CarrierAppUtils; 235import com.android.internal.util.ArrayUtils; 236import com.android.internal.util.FastPrintWriter; 237import com.android.internal.util.FastXmlSerializer; 238import com.android.internal.util.IndentingPrintWriter; 239import com.android.internal.util.Preconditions; 240import com.android.internal.util.XmlUtils; 241import com.android.server.EventLogTags; 242import com.android.server.FgThread; 243import com.android.server.IntentResolver; 244import com.android.server.LocalServices; 245import com.android.server.ServiceThread; 246import com.android.server.SystemConfig; 247import com.android.server.Watchdog; 248import com.android.server.net.NetworkPolicyManagerInternal; 249import com.android.server.pm.PermissionsState.PermissionState; 250import com.android.server.pm.Settings.DatabaseVersion; 251import com.android.server.pm.Settings.VersionInfo; 252import com.android.server.storage.DeviceStorageMonitorInternal; 253 254import dalvik.system.CloseGuard; 255import dalvik.system.DexFile; 256import dalvik.system.VMRuntime; 257 258import libcore.io.IoUtils; 259import libcore.util.EmptyArray; 260 261import org.xmlpull.v1.XmlPullParser; 262import org.xmlpull.v1.XmlPullParserException; 263import org.xmlpull.v1.XmlSerializer; 264 265import java.io.BufferedInputStream; 266import java.io.BufferedOutputStream; 267import java.io.BufferedReader; 268import java.io.ByteArrayInputStream; 269import java.io.ByteArrayOutputStream; 270import java.io.File; 271import java.io.FileDescriptor; 272import java.io.FileInputStream; 273import java.io.FileNotFoundException; 274import java.io.FileOutputStream; 275import java.io.FileReader; 276import java.io.FilenameFilter; 277import java.io.IOException; 278import java.io.InputStream; 279import java.io.PrintWriter; 280import java.nio.charset.StandardCharsets; 281import java.security.DigestInputStream; 282import java.security.MessageDigest; 283import java.security.NoSuchAlgorithmException; 284import java.security.PublicKey; 285import java.security.cert.Certificate; 286import java.security.cert.CertificateEncodingException; 287import java.security.cert.CertificateException; 288import java.text.SimpleDateFormat; 289import java.util.ArrayList; 290import java.util.Arrays; 291import java.util.Collection; 292import java.util.Collections; 293import java.util.Comparator; 294import java.util.Date; 295import java.util.HashSet; 296import java.util.Iterator; 297import java.util.List; 298import java.util.Map; 299import java.util.Objects; 300import java.util.Set; 301import java.util.concurrent.CountDownLatch; 302import java.util.concurrent.TimeUnit; 303import java.util.concurrent.atomic.AtomicBoolean; 304import java.util.concurrent.atomic.AtomicInteger; 305import java.util.concurrent.atomic.AtomicLong; 306 307/** 308 * Keep track of all those APKs everywhere. 309 * <p> 310 * Internally there are two important locks: 311 * <ul> 312 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 313 * and other related state. It is a fine-grained lock that should only be held 314 * momentarily, as it's one of the most contended locks in the system. 315 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 316 * operations typically involve heavy lifting of application data on disk. Since 317 * {@code installd} is single-threaded, and it's operations can often be slow, 318 * this lock should never be acquired while already holding {@link #mPackages}. 319 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 320 * holding {@link #mInstallLock}. 321 * </ul> 322 * Many internal methods rely on the caller to hold the appropriate locks, and 323 * this contract is expressed through method name suffixes: 324 * <ul> 325 * <li>fooLI(): the caller must hold {@link #mInstallLock} 326 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 327 * being modified must be frozen 328 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 329 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 330 * </ul> 331 * <p> 332 * Because this class is very central to the platform's security; please run all 333 * CTS and unit tests whenever making modifications: 334 * 335 * <pre> 336 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 337 * $ cts-tradefed run commandAndExit cts -m AppSecurityTests 338 * </pre> 339 */ 340public class PackageManagerService extends IPackageManager.Stub { 341 static final String TAG = "PackageManager"; 342 static final boolean DEBUG_SETTINGS = false; 343 static final boolean DEBUG_PREFERRED = false; 344 static final boolean DEBUG_UPGRADE = false; 345 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 346 private static final boolean DEBUG_BACKUP = false; 347 private static final boolean DEBUG_INSTALL = false; 348 private static final boolean DEBUG_REMOVE = false; 349 private static final boolean DEBUG_BROADCASTS = false; 350 private static final boolean DEBUG_SHOW_INFO = false; 351 private static final boolean DEBUG_PACKAGE_INFO = false; 352 private static final boolean DEBUG_INTENT_MATCHING = false; 353 private static final boolean DEBUG_PACKAGE_SCANNING = false; 354 private static final boolean DEBUG_VERIFY = false; 355 private static final boolean DEBUG_FILTERS = false; 356 357 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 358 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 359 // user, but by default initialize to this. 360 static final boolean DEBUG_DEXOPT = false; 361 362 private static final boolean DEBUG_ABI_SELECTION = false; 363 private static final boolean DEBUG_EPHEMERAL = false; 364 private static final boolean DEBUG_TRIAGED_MISSING = false; 365 private static final boolean DEBUG_APP_DATA = false; 366 367 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 368 369 private static final boolean DISABLE_EPHEMERAL_APPS = true; 370 371 private static final int RADIO_UID = Process.PHONE_UID; 372 private static final int LOG_UID = Process.LOG_UID; 373 private static final int NFC_UID = Process.NFC_UID; 374 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 375 private static final int SHELL_UID = Process.SHELL_UID; 376 377 // Cap the size of permission trees that 3rd party apps can define 378 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 379 380 // Suffix used during package installation when copying/moving 381 // package apks to install directory. 382 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 383 384 static final int SCAN_NO_DEX = 1<<1; 385 static final int SCAN_FORCE_DEX = 1<<2; 386 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 387 static final int SCAN_NEW_INSTALL = 1<<4; 388 static final int SCAN_NO_PATHS = 1<<5; 389 static final int SCAN_UPDATE_TIME = 1<<6; 390 static final int SCAN_DEFER_DEX = 1<<7; 391 static final int SCAN_BOOTING = 1<<8; 392 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 393 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 394 static final int SCAN_REPLACING = 1<<11; 395 static final int SCAN_REQUIRE_KNOWN = 1<<12; 396 static final int SCAN_MOVE = 1<<13; 397 static final int SCAN_INITIAL = 1<<14; 398 static final int SCAN_CHECK_ONLY = 1<<15; 399 static final int SCAN_DONT_KILL_APP = 1<<17; 400 static final int SCAN_IGNORE_FROZEN = 1<<18; 401 402 static final int REMOVE_CHATTY = 1<<16; 403 404 private static final int[] EMPTY_INT_ARRAY = new int[0]; 405 406 /** 407 * Timeout (in milliseconds) after which the watchdog should declare that 408 * our handler thread is wedged. The usual default for such things is one 409 * minute but we sometimes do very lengthy I/O operations on this thread, 410 * such as installing multi-gigabyte applications, so ours needs to be longer. 411 */ 412 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 413 414 /** 415 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 416 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 417 * settings entry if available, otherwise we use the hardcoded default. If it's been 418 * more than this long since the last fstrim, we force one during the boot sequence. 419 * 420 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 421 * one gets run at the next available charging+idle time. This final mandatory 422 * no-fstrim check kicks in only of the other scheduling criteria is never met. 423 */ 424 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 425 426 /** 427 * Whether verification is enabled by default. 428 */ 429 private static final boolean DEFAULT_VERIFY_ENABLE = true; 430 431 /** 432 * The default maximum time to wait for the verification agent to return in 433 * milliseconds. 434 */ 435 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 436 437 /** 438 * The default response for package verification timeout. 439 * 440 * This can be either PackageManager.VERIFICATION_ALLOW or 441 * PackageManager.VERIFICATION_REJECT. 442 */ 443 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 444 445 static final String PLATFORM_PACKAGE_NAME = "android"; 446 447 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 448 449 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 450 DEFAULT_CONTAINER_PACKAGE, 451 "com.android.defcontainer.DefaultContainerService"); 452 453 private static final String KILL_APP_REASON_GIDS_CHANGED = 454 "permission grant or revoke changed gids"; 455 456 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 457 "permissions revoked"; 458 459 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 460 461 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 462 463 /** Permission grant: not grant the permission. */ 464 private static final int GRANT_DENIED = 1; 465 466 /** Permission grant: grant the permission as an install permission. */ 467 private static final int GRANT_INSTALL = 2; 468 469 /** Permission grant: grant the permission as a runtime one. */ 470 private static final int GRANT_RUNTIME = 3; 471 472 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 473 private static final int GRANT_UPGRADE = 4; 474 475 /** Canonical intent used to identify what counts as a "web browser" app */ 476 private static final Intent sBrowserIntent; 477 static { 478 sBrowserIntent = new Intent(); 479 sBrowserIntent.setAction(Intent.ACTION_VIEW); 480 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 481 sBrowserIntent.setData(Uri.parse("http:")); 482 } 483 484 /** 485 * The set of all protected actions [i.e. those actions for which a high priority 486 * intent filter is disallowed]. 487 */ 488 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 489 static { 490 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 491 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 492 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 493 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 494 } 495 496 // Compilation reasons. 497 public static final int REASON_FIRST_BOOT = 0; 498 public static final int REASON_BOOT = 1; 499 public static final int REASON_INSTALL = 2; 500 public static final int REASON_BACKGROUND_DEXOPT = 3; 501 public static final int REASON_AB_OTA = 4; 502 public static final int REASON_NON_SYSTEM_LIBRARY = 5; 503 public static final int REASON_SHARED_APK = 6; 504 public static final int REASON_FORCED_DEXOPT = 7; 505 506 public static final int REASON_LAST = REASON_FORCED_DEXOPT; 507 508 /** Special library name that skips shared libraries check during compilation. */ 509 private static final String SKIP_SHARED_LIBRARY_CHECK = "&"; 510 511 final ServiceThread mHandlerThread; 512 513 final PackageHandler mHandler; 514 515 private final ProcessLoggingHandler mProcessLoggingHandler; 516 517 /** 518 * Messages for {@link #mHandler} that need to wait for system ready before 519 * being dispatched. 520 */ 521 private ArrayList<Message> mPostSystemReadyMessages; 522 523 final int mSdkVersion = Build.VERSION.SDK_INT; 524 525 final Context mContext; 526 final boolean mFactoryTest; 527 final boolean mOnlyCore; 528 final DisplayMetrics mMetrics; 529 final int mDefParseFlags; 530 final String[] mSeparateProcesses; 531 final boolean mIsUpgrade; 532 final boolean mIsPreNUpgrade; 533 534 /** The location for ASEC container files on internal storage. */ 535 final String mAsecInternalPath; 536 537 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 538 // LOCK HELD. Can be called with mInstallLock held. 539 @GuardedBy("mInstallLock") 540 final Installer mInstaller; 541 542 /** Directory where installed third-party apps stored */ 543 final File mAppInstallDir; 544 final File mEphemeralInstallDir; 545 546 /** 547 * Directory to which applications installed internally have their 548 * 32 bit native libraries copied. 549 */ 550 private File mAppLib32InstallDir; 551 552 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 553 // apps. 554 final File mDrmAppPrivateInstallDir; 555 556 // ---------------------------------------------------------------- 557 558 // Lock for state used when installing and doing other long running 559 // operations. Methods that must be called with this lock held have 560 // the suffix "LI". 561 final Object mInstallLock = new Object(); 562 563 // ---------------------------------------------------------------- 564 565 // Keys are String (package name), values are Package. This also serves 566 // as the lock for the global state. Methods that must be called with 567 // this lock held have the prefix "LP". 568 @GuardedBy("mPackages") 569 final ArrayMap<String, PackageParser.Package> mPackages = 570 new ArrayMap<String, PackageParser.Package>(); 571 572 final ArrayMap<String, Set<String>> mKnownCodebase = 573 new ArrayMap<String, Set<String>>(); 574 575 // Tracks available target package names -> overlay package paths. 576 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 577 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 578 579 /** 580 * Tracks new system packages [received in an OTA] that we expect to 581 * find updated user-installed versions. Keys are package name, values 582 * are package location. 583 */ 584 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 585 /** 586 * Tracks high priority intent filters for protected actions. During boot, certain 587 * filter actions are protected and should never be allowed to have a high priority 588 * intent filter for them. However, there is one, and only one exception -- the 589 * setup wizard. It must be able to define a high priority intent filter for these 590 * actions to ensure there are no escapes from the wizard. We need to delay processing 591 * of these during boot as we need to look at all of the system packages in order 592 * to know which component is the setup wizard. 593 */ 594 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 595 /** 596 * Whether or not processing protected filters should be deferred. 597 */ 598 private boolean mDeferProtectedFilters = true; 599 600 /** 601 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 602 */ 603 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 604 /** 605 * Whether or not system app permissions should be promoted from install to runtime. 606 */ 607 boolean mPromoteSystemApps; 608 609 @GuardedBy("mPackages") 610 final Settings mSettings; 611 612 /** 613 * Set of package names that are currently "frozen", which means active 614 * surgery is being done on the code/data for that package. The platform 615 * will refuse to launch frozen packages to avoid race conditions. 616 * 617 * @see PackageFreezer 618 */ 619 @GuardedBy("mPackages") 620 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 621 622 boolean mRestoredSettings; 623 624 // System configuration read by SystemConfig. 625 final int[] mGlobalGids; 626 final SparseArray<ArraySet<String>> mSystemPermissions; 627 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 628 629 // If mac_permissions.xml was found for seinfo labeling. 630 boolean mFoundPolicyFile; 631 632 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 633 634 public static final class SharedLibraryEntry { 635 public final String path; 636 public final String apk; 637 638 SharedLibraryEntry(String _path, String _apk) { 639 path = _path; 640 apk = _apk; 641 } 642 } 643 644 // Currently known shared libraries. 645 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 646 new ArrayMap<String, SharedLibraryEntry>(); 647 648 // All available activities, for your resolving pleasure. 649 final ActivityIntentResolver mActivities = 650 new ActivityIntentResolver(); 651 652 // All available receivers, for your resolving pleasure. 653 final ActivityIntentResolver mReceivers = 654 new ActivityIntentResolver(); 655 656 // All available services, for your resolving pleasure. 657 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 658 659 // All available providers, for your resolving pleasure. 660 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 661 662 // Mapping from provider base names (first directory in content URI codePath) 663 // to the provider information. 664 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 665 new ArrayMap<String, PackageParser.Provider>(); 666 667 // Mapping from instrumentation class names to info about them. 668 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 669 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 670 671 // Mapping from permission names to info about them. 672 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 673 new ArrayMap<String, PackageParser.PermissionGroup>(); 674 675 // Packages whose data we have transfered into another package, thus 676 // should no longer exist. 677 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 678 679 // Broadcast actions that are only available to the system. 680 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 681 682 /** List of packages waiting for verification. */ 683 final SparseArray<PackageVerificationState> mPendingVerification 684 = new SparseArray<PackageVerificationState>(); 685 686 /** Set of packages associated with each app op permission. */ 687 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 688 689 final PackageInstallerService mInstallerService; 690 691 private final PackageDexOptimizer mPackageDexOptimizer; 692 693 private AtomicInteger mNextMoveId = new AtomicInteger(); 694 private final MoveCallbacks mMoveCallbacks; 695 696 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 697 698 // Cache of users who need badging. 699 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 700 701 /** Token for keys in mPendingVerification. */ 702 private int mPendingVerificationToken = 0; 703 704 volatile boolean mSystemReady; 705 volatile boolean mSafeMode; 706 volatile boolean mHasSystemUidErrors; 707 708 ApplicationInfo mAndroidApplication; 709 final ActivityInfo mResolveActivity = new ActivityInfo(); 710 final ResolveInfo mResolveInfo = new ResolveInfo(); 711 ComponentName mResolveComponentName; 712 PackageParser.Package mPlatformPackage; 713 ComponentName mCustomResolverComponentName; 714 715 boolean mResolverReplaced = false; 716 717 private final @Nullable ComponentName mIntentFilterVerifierComponent; 718 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 719 720 private int mIntentFilterVerificationToken = 0; 721 722 /** Component that knows whether or not an ephemeral application exists */ 723 final ComponentName mEphemeralResolverComponent; 724 /** The service connection to the ephemeral resolver */ 725 final EphemeralResolverConnection mEphemeralResolverConnection; 726 727 /** Component used to install ephemeral applications */ 728 final ComponentName mEphemeralInstallerComponent; 729 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 730 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 731 732 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 733 = new SparseArray<IntentFilterVerificationState>(); 734 735 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 736 new DefaultPermissionGrantPolicy(this); 737 738 // List of packages names to keep cached, even if they are uninstalled for all users 739 private List<String> mKeepUninstalledPackages; 740 741 private UserManagerInternal mUserManagerInternal; 742 743 private static class IFVerificationParams { 744 PackageParser.Package pkg; 745 boolean replacing; 746 int userId; 747 int verifierUid; 748 749 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 750 int _userId, int _verifierUid) { 751 pkg = _pkg; 752 replacing = _replacing; 753 userId = _userId; 754 replacing = _replacing; 755 verifierUid = _verifierUid; 756 } 757 } 758 759 private interface IntentFilterVerifier<T extends IntentFilter> { 760 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 761 T filter, String packageName); 762 void startVerifications(int userId); 763 void receiveVerificationResponse(int verificationId); 764 } 765 766 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 767 private Context mContext; 768 private ComponentName mIntentFilterVerifierComponent; 769 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 770 771 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 772 mContext = context; 773 mIntentFilterVerifierComponent = verifierComponent; 774 } 775 776 private String getDefaultScheme() { 777 return IntentFilter.SCHEME_HTTPS; 778 } 779 780 @Override 781 public void startVerifications(int userId) { 782 // Launch verifications requests 783 int count = mCurrentIntentFilterVerifications.size(); 784 for (int n=0; n<count; n++) { 785 int verificationId = mCurrentIntentFilterVerifications.get(n); 786 final IntentFilterVerificationState ivs = 787 mIntentFilterVerificationStates.get(verificationId); 788 789 String packageName = ivs.getPackageName(); 790 791 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 792 final int filterCount = filters.size(); 793 ArraySet<String> domainsSet = new ArraySet<>(); 794 for (int m=0; m<filterCount; m++) { 795 PackageParser.ActivityIntentInfo filter = filters.get(m); 796 domainsSet.addAll(filter.getHostsList()); 797 } 798 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 799 synchronized (mPackages) { 800 if (mSettings.createIntentFilterVerificationIfNeededLPw( 801 packageName, domainsList) != null) { 802 scheduleWriteSettingsLocked(); 803 } 804 } 805 sendVerificationRequest(userId, verificationId, ivs); 806 } 807 mCurrentIntentFilterVerifications.clear(); 808 } 809 810 private void sendVerificationRequest(int userId, int verificationId, 811 IntentFilterVerificationState ivs) { 812 813 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 814 verificationIntent.putExtra( 815 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 816 verificationId); 817 verificationIntent.putExtra( 818 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 819 getDefaultScheme()); 820 verificationIntent.putExtra( 821 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 822 ivs.getHostsString()); 823 verificationIntent.putExtra( 824 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 825 ivs.getPackageName()); 826 verificationIntent.setComponent(mIntentFilterVerifierComponent); 827 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 828 829 UserHandle user = new UserHandle(userId); 830 mContext.sendBroadcastAsUser(verificationIntent, user); 831 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 832 "Sending IntentFilter verification broadcast"); 833 } 834 835 public void receiveVerificationResponse(int verificationId) { 836 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 837 838 final boolean verified = ivs.isVerified(); 839 840 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 841 final int count = filters.size(); 842 if (DEBUG_DOMAIN_VERIFICATION) { 843 Slog.i(TAG, "Received verification response " + verificationId 844 + " for " + count + " filters, verified=" + verified); 845 } 846 for (int n=0; n<count; n++) { 847 PackageParser.ActivityIntentInfo filter = filters.get(n); 848 filter.setVerified(verified); 849 850 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 851 + " verified with result:" + verified + " and hosts:" 852 + ivs.getHostsString()); 853 } 854 855 mIntentFilterVerificationStates.remove(verificationId); 856 857 final String packageName = ivs.getPackageName(); 858 IntentFilterVerificationInfo ivi = null; 859 860 synchronized (mPackages) { 861 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 862 } 863 if (ivi == null) { 864 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 865 + verificationId + " packageName:" + packageName); 866 return; 867 } 868 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 869 "Updating IntentFilterVerificationInfo for package " + packageName 870 +" verificationId:" + verificationId); 871 872 synchronized (mPackages) { 873 if (verified) { 874 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 875 } else { 876 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 877 } 878 scheduleWriteSettingsLocked(); 879 880 final int userId = ivs.getUserId(); 881 if (userId != UserHandle.USER_ALL) { 882 final int userStatus = 883 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 884 885 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 886 boolean needUpdate = false; 887 888 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 889 // already been set by the User thru the Disambiguation dialog 890 switch (userStatus) { 891 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 892 if (verified) { 893 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 894 } else { 895 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 896 } 897 needUpdate = true; 898 break; 899 900 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 901 if (verified) { 902 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 903 needUpdate = true; 904 } 905 break; 906 907 default: 908 // Nothing to do 909 } 910 911 if (needUpdate) { 912 mSettings.updateIntentFilterVerificationStatusLPw( 913 packageName, updatedStatus, userId); 914 scheduleWritePackageRestrictionsLocked(userId); 915 } 916 } 917 } 918 } 919 920 @Override 921 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 922 ActivityIntentInfo filter, String packageName) { 923 if (!hasValidDomains(filter)) { 924 return false; 925 } 926 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 927 if (ivs == null) { 928 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 929 packageName); 930 } 931 if (DEBUG_DOMAIN_VERIFICATION) { 932 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 933 } 934 ivs.addFilter(filter); 935 return true; 936 } 937 938 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 939 int userId, int verificationId, String packageName) { 940 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 941 verifierUid, userId, packageName); 942 ivs.setPendingState(); 943 synchronized (mPackages) { 944 mIntentFilterVerificationStates.append(verificationId, ivs); 945 mCurrentIntentFilterVerifications.add(verificationId); 946 } 947 return ivs; 948 } 949 } 950 951 private static boolean hasValidDomains(ActivityIntentInfo filter) { 952 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 953 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 954 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 955 } 956 957 // Set of pending broadcasts for aggregating enable/disable of components. 958 static class PendingPackageBroadcasts { 959 // for each user id, a map of <package name -> components within that package> 960 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 961 962 public PendingPackageBroadcasts() { 963 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 964 } 965 966 public ArrayList<String> get(int userId, String packageName) { 967 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 968 return packages.get(packageName); 969 } 970 971 public void put(int userId, String packageName, ArrayList<String> components) { 972 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 973 packages.put(packageName, components); 974 } 975 976 public void remove(int userId, String packageName) { 977 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 978 if (packages != null) { 979 packages.remove(packageName); 980 } 981 } 982 983 public void remove(int userId) { 984 mUidMap.remove(userId); 985 } 986 987 public int userIdCount() { 988 return mUidMap.size(); 989 } 990 991 public int userIdAt(int n) { 992 return mUidMap.keyAt(n); 993 } 994 995 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 996 return mUidMap.get(userId); 997 } 998 999 public int size() { 1000 // total number of pending broadcast entries across all userIds 1001 int num = 0; 1002 for (int i = 0; i< mUidMap.size(); i++) { 1003 num += mUidMap.valueAt(i).size(); 1004 } 1005 return num; 1006 } 1007 1008 public void clear() { 1009 mUidMap.clear(); 1010 } 1011 1012 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1013 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1014 if (map == null) { 1015 map = new ArrayMap<String, ArrayList<String>>(); 1016 mUidMap.put(userId, map); 1017 } 1018 return map; 1019 } 1020 } 1021 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1022 1023 // Service Connection to remote media container service to copy 1024 // package uri's from external media onto secure containers 1025 // or internal storage. 1026 private IMediaContainerService mContainerService = null; 1027 1028 static final int SEND_PENDING_BROADCAST = 1; 1029 static final int MCS_BOUND = 3; 1030 static final int END_COPY = 4; 1031 static final int INIT_COPY = 5; 1032 static final int MCS_UNBIND = 6; 1033 static final int START_CLEANING_PACKAGE = 7; 1034 static final int FIND_INSTALL_LOC = 8; 1035 static final int POST_INSTALL = 9; 1036 static final int MCS_RECONNECT = 10; 1037 static final int MCS_GIVE_UP = 11; 1038 static final int UPDATED_MEDIA_STATUS = 12; 1039 static final int WRITE_SETTINGS = 13; 1040 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1041 static final int PACKAGE_VERIFIED = 15; 1042 static final int CHECK_PENDING_VERIFICATION = 16; 1043 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1044 static final int INTENT_FILTER_VERIFIED = 18; 1045 static final int WRITE_PACKAGE_LIST = 19; 1046 1047 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1048 1049 // Delay time in millisecs 1050 static final int BROADCAST_DELAY = 10 * 1000; 1051 1052 static UserManagerService sUserManager; 1053 1054 // Stores a list of users whose package restrictions file needs to be updated 1055 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1056 1057 final private DefaultContainerConnection mDefContainerConn = 1058 new DefaultContainerConnection(); 1059 class DefaultContainerConnection implements ServiceConnection { 1060 public void onServiceConnected(ComponentName name, IBinder service) { 1061 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1062 IMediaContainerService imcs = 1063 IMediaContainerService.Stub.asInterface(service); 1064 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1065 } 1066 1067 public void onServiceDisconnected(ComponentName name) { 1068 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1069 } 1070 } 1071 1072 // Recordkeeping of restore-after-install operations that are currently in flight 1073 // between the Package Manager and the Backup Manager 1074 static class PostInstallData { 1075 public InstallArgs args; 1076 public PackageInstalledInfo res; 1077 1078 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1079 args = _a; 1080 res = _r; 1081 } 1082 } 1083 1084 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1085 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1086 1087 // XML tags for backup/restore of various bits of state 1088 private static final String TAG_PREFERRED_BACKUP = "pa"; 1089 private static final String TAG_DEFAULT_APPS = "da"; 1090 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1091 1092 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1093 private static final String TAG_ALL_GRANTS = "rt-grants"; 1094 private static final String TAG_GRANT = "grant"; 1095 private static final String ATTR_PACKAGE_NAME = "pkg"; 1096 1097 private static final String TAG_PERMISSION = "perm"; 1098 private static final String ATTR_PERMISSION_NAME = "name"; 1099 private static final String ATTR_IS_GRANTED = "g"; 1100 private static final String ATTR_USER_SET = "set"; 1101 private static final String ATTR_USER_FIXED = "fixed"; 1102 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1103 1104 // System/policy permission grants are not backed up 1105 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1106 FLAG_PERMISSION_POLICY_FIXED 1107 | FLAG_PERMISSION_SYSTEM_FIXED 1108 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1109 1110 // And we back up these user-adjusted states 1111 private static final int USER_RUNTIME_GRANT_MASK = 1112 FLAG_PERMISSION_USER_SET 1113 | FLAG_PERMISSION_USER_FIXED 1114 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1115 1116 final @Nullable String mRequiredVerifierPackage; 1117 final @NonNull String mRequiredInstallerPackage; 1118 final @Nullable String mSetupWizardPackage; 1119 final @NonNull String mServicesSystemSharedLibraryPackageName; 1120 final @NonNull String mSharedSystemSharedLibraryPackageName; 1121 1122 private final PackageUsage mPackageUsage = new PackageUsage(); 1123 1124 private class PackageUsage { 1125 private static final int WRITE_INTERVAL 1126 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 1127 1128 private final Object mFileLock = new Object(); 1129 private final AtomicLong mLastWritten = new AtomicLong(0); 1130 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 1131 1132 private boolean mIsHistoricalPackageUsageAvailable = true; 1133 1134 boolean isHistoricalPackageUsageAvailable() { 1135 return mIsHistoricalPackageUsageAvailable; 1136 } 1137 1138 void write(boolean force) { 1139 if (force) { 1140 writeInternal(); 1141 return; 1142 } 1143 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 1144 && !DEBUG_DEXOPT) { 1145 return; 1146 } 1147 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 1148 new Thread("PackageUsage_DiskWriter") { 1149 @Override 1150 public void run() { 1151 try { 1152 writeInternal(); 1153 } finally { 1154 mBackgroundWriteRunning.set(false); 1155 } 1156 } 1157 }.start(); 1158 } 1159 } 1160 1161 private void writeInternal() { 1162 synchronized (mPackages) { 1163 synchronized (mFileLock) { 1164 AtomicFile file = getFile(); 1165 FileOutputStream f = null; 1166 try { 1167 f = file.startWrite(); 1168 BufferedOutputStream out = new BufferedOutputStream(f); 1169 FileUtils.setPermissions(file.getBaseFile().getPath(), 1170 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1171 StringBuilder sb = new StringBuilder(); 1172 1173 sb.append(USAGE_FILE_MAGIC_VERSION_1); 1174 sb.append('\n'); 1175 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1176 1177 for (PackageParser.Package pkg : mPackages.values()) { 1178 if (pkg.getLatestPackageUseTimeInMills() == 0L) { 1179 continue; 1180 } 1181 sb.setLength(0); 1182 sb.append(pkg.packageName); 1183 for (long usageTimeInMillis : pkg.mLastPackageUsageTimeInMills) { 1184 sb.append(' '); 1185 sb.append(usageTimeInMillis); 1186 } 1187 sb.append('\n'); 1188 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1189 } 1190 out.flush(); 1191 file.finishWrite(f); 1192 } catch (IOException e) { 1193 if (f != null) { 1194 file.failWrite(f); 1195 } 1196 Log.e(TAG, "Failed to write package usage times", e); 1197 } 1198 } 1199 } 1200 mLastWritten.set(SystemClock.elapsedRealtime()); 1201 } 1202 1203 void readLP() { 1204 synchronized (mFileLock) { 1205 AtomicFile file = getFile(); 1206 BufferedInputStream in = null; 1207 try { 1208 in = new BufferedInputStream(file.openRead()); 1209 StringBuffer sb = new StringBuffer(); 1210 1211 String firstLine = readLine(in, sb); 1212 if (firstLine.equals(USAGE_FILE_MAGIC_VERSION_1)) { 1213 readVersion1LP(in, sb); 1214 } else { 1215 readVersion0LP(in, sb, firstLine); 1216 } 1217 } catch (FileNotFoundException expected) { 1218 mIsHistoricalPackageUsageAvailable = false; 1219 } catch (IOException e) { 1220 Log.w(TAG, "Failed to read package usage times", e); 1221 } finally { 1222 IoUtils.closeQuietly(in); 1223 } 1224 } 1225 mLastWritten.set(SystemClock.elapsedRealtime()); 1226 } 1227 1228 private void readVersion0LP(InputStream in, StringBuffer sb, String firstLine) 1229 throws IOException { 1230 // Initial version of the file had no version number and stored one 1231 // package-timestamp pair per line. 1232 // Note that the first line has already been read from the InputStream. 1233 for (String line = firstLine; line != null; line = readLine(in, sb)) { 1234 String[] tokens = line.split(" "); 1235 if (tokens.length != 2) { 1236 throw new IOException("Failed to parse " + line + 1237 " as package-timestamp pair."); 1238 } 1239 1240 String packageName = tokens[0]; 1241 PackageParser.Package pkg = mPackages.get(packageName); 1242 if (pkg == null) { 1243 continue; 1244 } 1245 1246 long timestamp = parseAsLong(tokens[1]); 1247 for (int reason = 0; 1248 reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT; 1249 reason++) { 1250 pkg.mLastPackageUsageTimeInMills[reason] = timestamp; 1251 } 1252 } 1253 } 1254 1255 private void readVersion1LP(InputStream in, StringBuffer sb) throws IOException { 1256 // Version 1 of the file started with the corresponding version 1257 // number and then stored a package name and eight timestamps per line. 1258 String line; 1259 while ((line = readLine(in, sb)) != null) { 1260 String[] tokens = line.split(" "); 1261 if (tokens.length != PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT + 1) { 1262 throw new IOException("Failed to parse " + line + " as a timestamp array."); 1263 } 1264 1265 String packageName = tokens[0]; 1266 PackageParser.Package pkg = mPackages.get(packageName); 1267 if (pkg == null) { 1268 continue; 1269 } 1270 1271 for (int reason = 0; 1272 reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT; 1273 reason++) { 1274 pkg.mLastPackageUsageTimeInMills[reason] = parseAsLong(tokens[reason + 1]); 1275 } 1276 } 1277 } 1278 1279 private long parseAsLong(String token) throws IOException { 1280 try { 1281 return Long.parseLong(token); 1282 } catch (NumberFormatException e) { 1283 throw new IOException("Failed to parse " + token + " as a long.", e); 1284 } 1285 } 1286 1287 private String readLine(InputStream in, StringBuffer sb) throws IOException { 1288 return readToken(in, sb, '\n'); 1289 } 1290 1291 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1292 throws IOException { 1293 sb.setLength(0); 1294 while (true) { 1295 int ch = in.read(); 1296 if (ch == -1) { 1297 if (sb.length() == 0) { 1298 return null; 1299 } 1300 throw new IOException("Unexpected EOF"); 1301 } 1302 if (ch == endOfToken) { 1303 return sb.toString(); 1304 } 1305 sb.append((char)ch); 1306 } 1307 } 1308 1309 private AtomicFile getFile() { 1310 File dataDir = Environment.getDataDirectory(); 1311 File systemDir = new File(dataDir, "system"); 1312 File fname = new File(systemDir, "package-usage.list"); 1313 return new AtomicFile(fname); 1314 } 1315 1316 private static final String USAGE_FILE_MAGIC = "PACKAGE_USAGE__VERSION_"; 1317 private static final String USAGE_FILE_MAGIC_VERSION_1 = USAGE_FILE_MAGIC + "1"; 1318 } 1319 1320 class PackageHandler extends Handler { 1321 private boolean mBound = false; 1322 final ArrayList<HandlerParams> mPendingInstalls = 1323 new ArrayList<HandlerParams>(); 1324 1325 private boolean connectToService() { 1326 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1327 " DefaultContainerService"); 1328 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1329 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1330 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1331 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1332 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1333 mBound = true; 1334 return true; 1335 } 1336 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1337 return false; 1338 } 1339 1340 private void disconnectService() { 1341 mContainerService = null; 1342 mBound = false; 1343 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1344 mContext.unbindService(mDefContainerConn); 1345 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1346 } 1347 1348 PackageHandler(Looper looper) { 1349 super(looper); 1350 } 1351 1352 public void handleMessage(Message msg) { 1353 try { 1354 doHandleMessage(msg); 1355 } finally { 1356 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1357 } 1358 } 1359 1360 void doHandleMessage(Message msg) { 1361 switch (msg.what) { 1362 case INIT_COPY: { 1363 HandlerParams params = (HandlerParams) msg.obj; 1364 int idx = mPendingInstalls.size(); 1365 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1366 // If a bind was already initiated we dont really 1367 // need to do anything. The pending install 1368 // will be processed later on. 1369 if (!mBound) { 1370 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1371 System.identityHashCode(mHandler)); 1372 // If this is the only one pending we might 1373 // have to bind to the service again. 1374 if (!connectToService()) { 1375 Slog.e(TAG, "Failed to bind to media container service"); 1376 params.serviceError(); 1377 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1378 System.identityHashCode(mHandler)); 1379 if (params.traceMethod != null) { 1380 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1381 params.traceCookie); 1382 } 1383 return; 1384 } else { 1385 // Once we bind to the service, the first 1386 // pending request will be processed. 1387 mPendingInstalls.add(idx, params); 1388 } 1389 } else { 1390 mPendingInstalls.add(idx, params); 1391 // Already bound to the service. Just make 1392 // sure we trigger off processing the first request. 1393 if (idx == 0) { 1394 mHandler.sendEmptyMessage(MCS_BOUND); 1395 } 1396 } 1397 break; 1398 } 1399 case MCS_BOUND: { 1400 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1401 if (msg.obj != null) { 1402 mContainerService = (IMediaContainerService) msg.obj; 1403 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1404 System.identityHashCode(mHandler)); 1405 } 1406 if (mContainerService == null) { 1407 if (!mBound) { 1408 // Something seriously wrong since we are not bound and we are not 1409 // waiting for connection. Bail out. 1410 Slog.e(TAG, "Cannot bind to media container service"); 1411 for (HandlerParams params : mPendingInstalls) { 1412 // Indicate service bind error 1413 params.serviceError(); 1414 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1415 System.identityHashCode(params)); 1416 if (params.traceMethod != null) { 1417 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1418 params.traceMethod, params.traceCookie); 1419 } 1420 return; 1421 } 1422 mPendingInstalls.clear(); 1423 } else { 1424 Slog.w(TAG, "Waiting to connect to media container service"); 1425 } 1426 } else if (mPendingInstalls.size() > 0) { 1427 HandlerParams params = mPendingInstalls.get(0); 1428 if (params != null) { 1429 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1430 System.identityHashCode(params)); 1431 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1432 if (params.startCopy()) { 1433 // We are done... look for more work or to 1434 // go idle. 1435 if (DEBUG_SD_INSTALL) Log.i(TAG, 1436 "Checking for more work or unbind..."); 1437 // Delete pending install 1438 if (mPendingInstalls.size() > 0) { 1439 mPendingInstalls.remove(0); 1440 } 1441 if (mPendingInstalls.size() == 0) { 1442 if (mBound) { 1443 if (DEBUG_SD_INSTALL) Log.i(TAG, 1444 "Posting delayed MCS_UNBIND"); 1445 removeMessages(MCS_UNBIND); 1446 Message ubmsg = obtainMessage(MCS_UNBIND); 1447 // Unbind after a little delay, to avoid 1448 // continual thrashing. 1449 sendMessageDelayed(ubmsg, 10000); 1450 } 1451 } else { 1452 // There are more pending requests in queue. 1453 // Just post MCS_BOUND message to trigger processing 1454 // of next pending install. 1455 if (DEBUG_SD_INSTALL) Log.i(TAG, 1456 "Posting MCS_BOUND for next work"); 1457 mHandler.sendEmptyMessage(MCS_BOUND); 1458 } 1459 } 1460 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1461 } 1462 } else { 1463 // Should never happen ideally. 1464 Slog.w(TAG, "Empty queue"); 1465 } 1466 break; 1467 } 1468 case MCS_RECONNECT: { 1469 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1470 if (mPendingInstalls.size() > 0) { 1471 if (mBound) { 1472 disconnectService(); 1473 } 1474 if (!connectToService()) { 1475 Slog.e(TAG, "Failed to bind to media container service"); 1476 for (HandlerParams params : mPendingInstalls) { 1477 // Indicate service bind error 1478 params.serviceError(); 1479 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1480 System.identityHashCode(params)); 1481 } 1482 mPendingInstalls.clear(); 1483 } 1484 } 1485 break; 1486 } 1487 case MCS_UNBIND: { 1488 // If there is no actual work left, then time to unbind. 1489 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1490 1491 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1492 if (mBound) { 1493 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1494 1495 disconnectService(); 1496 } 1497 } else if (mPendingInstalls.size() > 0) { 1498 // There are more pending requests in queue. 1499 // Just post MCS_BOUND message to trigger processing 1500 // of next pending install. 1501 mHandler.sendEmptyMessage(MCS_BOUND); 1502 } 1503 1504 break; 1505 } 1506 case MCS_GIVE_UP: { 1507 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1508 HandlerParams params = mPendingInstalls.remove(0); 1509 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1510 System.identityHashCode(params)); 1511 break; 1512 } 1513 case SEND_PENDING_BROADCAST: { 1514 String packages[]; 1515 ArrayList<String> components[]; 1516 int size = 0; 1517 int uids[]; 1518 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1519 synchronized (mPackages) { 1520 if (mPendingBroadcasts == null) { 1521 return; 1522 } 1523 size = mPendingBroadcasts.size(); 1524 if (size <= 0) { 1525 // Nothing to be done. Just return 1526 return; 1527 } 1528 packages = new String[size]; 1529 components = new ArrayList[size]; 1530 uids = new int[size]; 1531 int i = 0; // filling out the above arrays 1532 1533 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1534 int packageUserId = mPendingBroadcasts.userIdAt(n); 1535 Iterator<Map.Entry<String, ArrayList<String>>> it 1536 = mPendingBroadcasts.packagesForUserId(packageUserId) 1537 .entrySet().iterator(); 1538 while (it.hasNext() && i < size) { 1539 Map.Entry<String, ArrayList<String>> ent = it.next(); 1540 packages[i] = ent.getKey(); 1541 components[i] = ent.getValue(); 1542 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1543 uids[i] = (ps != null) 1544 ? UserHandle.getUid(packageUserId, ps.appId) 1545 : -1; 1546 i++; 1547 } 1548 } 1549 size = i; 1550 mPendingBroadcasts.clear(); 1551 } 1552 // Send broadcasts 1553 for (int i = 0; i < size; i++) { 1554 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1555 } 1556 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1557 break; 1558 } 1559 case START_CLEANING_PACKAGE: { 1560 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1561 final String packageName = (String)msg.obj; 1562 final int userId = msg.arg1; 1563 final boolean andCode = msg.arg2 != 0; 1564 synchronized (mPackages) { 1565 if (userId == UserHandle.USER_ALL) { 1566 int[] users = sUserManager.getUserIds(); 1567 for (int user : users) { 1568 mSettings.addPackageToCleanLPw( 1569 new PackageCleanItem(user, packageName, andCode)); 1570 } 1571 } else { 1572 mSettings.addPackageToCleanLPw( 1573 new PackageCleanItem(userId, packageName, andCode)); 1574 } 1575 } 1576 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1577 startCleaningPackages(); 1578 } break; 1579 case POST_INSTALL: { 1580 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1581 1582 PostInstallData data = mRunningInstalls.get(msg.arg1); 1583 final boolean didRestore = (msg.arg2 != 0); 1584 mRunningInstalls.delete(msg.arg1); 1585 1586 if (data != null) { 1587 InstallArgs args = data.args; 1588 PackageInstalledInfo parentRes = data.res; 1589 1590 final boolean grantPermissions = (args.installFlags 1591 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1592 final boolean killApp = (args.installFlags 1593 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1594 final String[] grantedPermissions = args.installGrantPermissions; 1595 1596 // Handle the parent package 1597 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1598 grantedPermissions, didRestore, args.installerPackageName, 1599 args.observer); 1600 1601 // Handle the child packages 1602 final int childCount = (parentRes.addedChildPackages != null) 1603 ? parentRes.addedChildPackages.size() : 0; 1604 for (int i = 0; i < childCount; i++) { 1605 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1606 handlePackagePostInstall(childRes, grantPermissions, killApp, 1607 grantedPermissions, false, args.installerPackageName, 1608 args.observer); 1609 } 1610 1611 // Log tracing if needed 1612 if (args.traceMethod != null) { 1613 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1614 args.traceCookie); 1615 } 1616 } else { 1617 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1618 } 1619 1620 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1621 } break; 1622 case UPDATED_MEDIA_STATUS: { 1623 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1624 boolean reportStatus = msg.arg1 == 1; 1625 boolean doGc = msg.arg2 == 1; 1626 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1627 if (doGc) { 1628 // Force a gc to clear up stale containers. 1629 Runtime.getRuntime().gc(); 1630 } 1631 if (msg.obj != null) { 1632 @SuppressWarnings("unchecked") 1633 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1634 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1635 // Unload containers 1636 unloadAllContainers(args); 1637 } 1638 if (reportStatus) { 1639 try { 1640 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1641 PackageHelper.getMountService().finishMediaUpdate(); 1642 } catch (RemoteException e) { 1643 Log.e(TAG, "MountService not running?"); 1644 } 1645 } 1646 } break; 1647 case WRITE_SETTINGS: { 1648 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1649 synchronized (mPackages) { 1650 removeMessages(WRITE_SETTINGS); 1651 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1652 mSettings.writeLPr(); 1653 mDirtyUsers.clear(); 1654 } 1655 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1656 } break; 1657 case WRITE_PACKAGE_RESTRICTIONS: { 1658 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1659 synchronized (mPackages) { 1660 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1661 for (int userId : mDirtyUsers) { 1662 mSettings.writePackageRestrictionsLPr(userId); 1663 } 1664 mDirtyUsers.clear(); 1665 } 1666 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1667 } break; 1668 case WRITE_PACKAGE_LIST: { 1669 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1670 synchronized (mPackages) { 1671 removeMessages(WRITE_PACKAGE_LIST); 1672 mSettings.writePackageListLPr(msg.arg1); 1673 } 1674 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1675 } break; 1676 case CHECK_PENDING_VERIFICATION: { 1677 final int verificationId = msg.arg1; 1678 final PackageVerificationState state = mPendingVerification.get(verificationId); 1679 1680 if ((state != null) && !state.timeoutExtended()) { 1681 final InstallArgs args = state.getInstallArgs(); 1682 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1683 1684 Slog.i(TAG, "Verification timed out for " + originUri); 1685 mPendingVerification.remove(verificationId); 1686 1687 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1688 1689 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1690 Slog.i(TAG, "Continuing with installation of " + originUri); 1691 state.setVerifierResponse(Binder.getCallingUid(), 1692 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1693 broadcastPackageVerified(verificationId, originUri, 1694 PackageManager.VERIFICATION_ALLOW, 1695 state.getInstallArgs().getUser()); 1696 try { 1697 ret = args.copyApk(mContainerService, true); 1698 } catch (RemoteException e) { 1699 Slog.e(TAG, "Could not contact the ContainerService"); 1700 } 1701 } else { 1702 broadcastPackageVerified(verificationId, originUri, 1703 PackageManager.VERIFICATION_REJECT, 1704 state.getInstallArgs().getUser()); 1705 } 1706 1707 Trace.asyncTraceEnd( 1708 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1709 1710 processPendingInstall(args, ret); 1711 mHandler.sendEmptyMessage(MCS_UNBIND); 1712 } 1713 break; 1714 } 1715 case PACKAGE_VERIFIED: { 1716 final int verificationId = msg.arg1; 1717 1718 final PackageVerificationState state = mPendingVerification.get(verificationId); 1719 if (state == null) { 1720 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1721 break; 1722 } 1723 1724 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1725 1726 state.setVerifierResponse(response.callerUid, response.code); 1727 1728 if (state.isVerificationComplete()) { 1729 mPendingVerification.remove(verificationId); 1730 1731 final InstallArgs args = state.getInstallArgs(); 1732 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1733 1734 int ret; 1735 if (state.isInstallAllowed()) { 1736 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1737 broadcastPackageVerified(verificationId, originUri, 1738 response.code, state.getInstallArgs().getUser()); 1739 try { 1740 ret = args.copyApk(mContainerService, true); 1741 } catch (RemoteException e) { 1742 Slog.e(TAG, "Could not contact the ContainerService"); 1743 } 1744 } else { 1745 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1746 } 1747 1748 Trace.asyncTraceEnd( 1749 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1750 1751 processPendingInstall(args, ret); 1752 mHandler.sendEmptyMessage(MCS_UNBIND); 1753 } 1754 1755 break; 1756 } 1757 case START_INTENT_FILTER_VERIFICATIONS: { 1758 IFVerificationParams params = (IFVerificationParams) msg.obj; 1759 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1760 params.replacing, params.pkg); 1761 break; 1762 } 1763 case INTENT_FILTER_VERIFIED: { 1764 final int verificationId = msg.arg1; 1765 1766 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1767 verificationId); 1768 if (state == null) { 1769 Slog.w(TAG, "Invalid IntentFilter verification token " 1770 + verificationId + " received"); 1771 break; 1772 } 1773 1774 final int userId = state.getUserId(); 1775 1776 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1777 "Processing IntentFilter verification with token:" 1778 + verificationId + " and userId:" + userId); 1779 1780 final IntentFilterVerificationResponse response = 1781 (IntentFilterVerificationResponse) msg.obj; 1782 1783 state.setVerifierResponse(response.callerUid, response.code); 1784 1785 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1786 "IntentFilter verification with token:" + verificationId 1787 + " and userId:" + userId 1788 + " is settings verifier response with response code:" 1789 + response.code); 1790 1791 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1792 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1793 + response.getFailedDomainsString()); 1794 } 1795 1796 if (state.isVerificationComplete()) { 1797 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1798 } else { 1799 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1800 "IntentFilter verification with token:" + verificationId 1801 + " was not said to be complete"); 1802 } 1803 1804 break; 1805 } 1806 } 1807 } 1808 } 1809 1810 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1811 boolean killApp, String[] grantedPermissions, 1812 boolean launchedForRestore, String installerPackage, 1813 IPackageInstallObserver2 installObserver) { 1814 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1815 // Send the removed broadcasts 1816 if (res.removedInfo != null) { 1817 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1818 } 1819 1820 // Now that we successfully installed the package, grant runtime 1821 // permissions if requested before broadcasting the install. 1822 if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion 1823 >= Build.VERSION_CODES.M) { 1824 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1825 } 1826 1827 final boolean update = res.removedInfo != null 1828 && res.removedInfo.removedPackage != null; 1829 1830 // If this is the first time we have child packages for a disabled privileged 1831 // app that had no children, we grant requested runtime permissions to the new 1832 // children if the parent on the system image had them already granted. 1833 if (res.pkg.parentPackage != null) { 1834 synchronized (mPackages) { 1835 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1836 } 1837 } 1838 1839 synchronized (mPackages) { 1840 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1841 } 1842 1843 final String packageName = res.pkg.applicationInfo.packageName; 1844 Bundle extras = new Bundle(1); 1845 extras.putInt(Intent.EXTRA_UID, res.uid); 1846 1847 // Determine the set of users who are adding this package for 1848 // the first time vs. those who are seeing an update. 1849 int[] firstUsers = EMPTY_INT_ARRAY; 1850 int[] updateUsers = EMPTY_INT_ARRAY; 1851 if (res.origUsers == null || res.origUsers.length == 0) { 1852 firstUsers = res.newUsers; 1853 } else { 1854 for (int newUser : res.newUsers) { 1855 boolean isNew = true; 1856 for (int origUser : res.origUsers) { 1857 if (origUser == newUser) { 1858 isNew = false; 1859 break; 1860 } 1861 } 1862 if (isNew) { 1863 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1864 } else { 1865 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1866 } 1867 } 1868 } 1869 1870 // Send installed broadcasts if the install/update is not ephemeral 1871 if (!isEphemeral(res.pkg)) { 1872 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1873 1874 // Send added for users that see the package for the first time 1875 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1876 extras, 0 /*flags*/, null /*targetPackage*/, 1877 null /*finishedReceiver*/, firstUsers); 1878 1879 // Send added for users that don't see the package for the first time 1880 if (update) { 1881 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1882 } 1883 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1884 extras, 0 /*flags*/, null /*targetPackage*/, 1885 null /*finishedReceiver*/, updateUsers); 1886 1887 // Send replaced for users that don't see the package for the first time 1888 if (update) { 1889 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1890 packageName, extras, 0 /*flags*/, 1891 null /*targetPackage*/, null /*finishedReceiver*/, 1892 updateUsers); 1893 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1894 null /*package*/, null /*extras*/, 0 /*flags*/, 1895 packageName /*targetPackage*/, 1896 null /*finishedReceiver*/, updateUsers); 1897 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 1898 // First-install and we did a restore, so we're responsible for the 1899 // first-launch broadcast. 1900 if (DEBUG_BACKUP) { 1901 Slog.i(TAG, "Post-restore of " + packageName 1902 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers)); 1903 } 1904 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers); 1905 } 1906 1907 // Send broadcast package appeared if forward locked/external for all users 1908 // treat asec-hosted packages like removable media on upgrade 1909 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1910 if (DEBUG_INSTALL) { 1911 Slog.i(TAG, "upgrading pkg " + res.pkg 1912 + " is ASEC-hosted -> AVAILABLE"); 1913 } 1914 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1915 ArrayList<String> pkgList = new ArrayList<>(1); 1916 pkgList.add(packageName); 1917 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1918 } 1919 } 1920 1921 // Work that needs to happen on first install within each user 1922 if (firstUsers != null && firstUsers.length > 0) { 1923 synchronized (mPackages) { 1924 for (int userId : firstUsers) { 1925 // If this app is a browser and it's newly-installed for some 1926 // users, clear any default-browser state in those users. The 1927 // app's nature doesn't depend on the user, so we can just check 1928 // its browser nature in any user and generalize. 1929 if (packageIsBrowser(packageName, userId)) { 1930 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1931 } 1932 1933 // We may also need to apply pending (restored) runtime 1934 // permission grants within these users. 1935 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1936 } 1937 } 1938 } 1939 1940 // Log current value of "unknown sources" setting 1941 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1942 getUnknownSourcesSettings()); 1943 1944 // Force a gc to clear up things 1945 Runtime.getRuntime().gc(); 1946 1947 // Remove the replaced package's older resources safely now 1948 // We delete after a gc for applications on sdcard. 1949 if (res.removedInfo != null && res.removedInfo.args != null) { 1950 synchronized (mInstallLock) { 1951 res.removedInfo.args.doPostDeleteLI(true); 1952 } 1953 } 1954 } 1955 1956 // If someone is watching installs - notify them 1957 if (installObserver != null) { 1958 try { 1959 Bundle extras = extrasForInstallResult(res); 1960 installObserver.onPackageInstalled(res.name, res.returnCode, 1961 res.returnMsg, extras); 1962 } catch (RemoteException e) { 1963 Slog.i(TAG, "Observer no longer exists."); 1964 } 1965 } 1966 } 1967 1968 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1969 PackageParser.Package pkg) { 1970 if (pkg.parentPackage == null) { 1971 return; 1972 } 1973 if (pkg.requestedPermissions == null) { 1974 return; 1975 } 1976 final PackageSetting disabledSysParentPs = mSettings 1977 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1978 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1979 || !disabledSysParentPs.isPrivileged() 1980 || (disabledSysParentPs.childPackageNames != null 1981 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1982 return; 1983 } 1984 final int[] allUserIds = sUserManager.getUserIds(); 1985 final int permCount = pkg.requestedPermissions.size(); 1986 for (int i = 0; i < permCount; i++) { 1987 String permission = pkg.requestedPermissions.get(i); 1988 BasePermission bp = mSettings.mPermissions.get(permission); 1989 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1990 continue; 1991 } 1992 for (int userId : allUserIds) { 1993 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1994 permission, userId)) { 1995 grantRuntimePermission(pkg.packageName, permission, userId); 1996 } 1997 } 1998 } 1999 } 2000 2001 private StorageEventListener mStorageListener = new StorageEventListener() { 2002 @Override 2003 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 2004 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 2005 if (vol.state == VolumeInfo.STATE_MOUNTED) { 2006 final String volumeUuid = vol.getFsUuid(); 2007 2008 // Clean up any users or apps that were removed or recreated 2009 // while this volume was missing 2010 reconcileUsers(volumeUuid); 2011 reconcileApps(volumeUuid); 2012 2013 // Clean up any install sessions that expired or were 2014 // cancelled while this volume was missing 2015 mInstallerService.onPrivateVolumeMounted(volumeUuid); 2016 2017 loadPrivatePackages(vol); 2018 2019 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2020 unloadPrivatePackages(vol); 2021 } 2022 } 2023 2024 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 2025 if (vol.state == VolumeInfo.STATE_MOUNTED) { 2026 updateExternalMediaStatus(true, false); 2027 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2028 updateExternalMediaStatus(false, false); 2029 } 2030 } 2031 } 2032 2033 @Override 2034 public void onVolumeForgotten(String fsUuid) { 2035 if (TextUtils.isEmpty(fsUuid)) { 2036 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 2037 return; 2038 } 2039 2040 // Remove any apps installed on the forgotten volume 2041 synchronized (mPackages) { 2042 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 2043 for (PackageSetting ps : packages) { 2044 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 2045 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 2046 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 2047 } 2048 2049 mSettings.onVolumeForgotten(fsUuid); 2050 mSettings.writeLPr(); 2051 } 2052 } 2053 }; 2054 2055 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 2056 String[] grantedPermissions) { 2057 for (int userId : userIds) { 2058 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 2059 } 2060 2061 // We could have touched GID membership, so flush out packages.list 2062 synchronized (mPackages) { 2063 mSettings.writePackageListLPr(); 2064 } 2065 } 2066 2067 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 2068 String[] grantedPermissions) { 2069 SettingBase sb = (SettingBase) pkg.mExtras; 2070 if (sb == null) { 2071 return; 2072 } 2073 2074 PermissionsState permissionsState = sb.getPermissionsState(); 2075 2076 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 2077 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 2078 2079 for (String permission : pkg.requestedPermissions) { 2080 final BasePermission bp; 2081 synchronized (mPackages) { 2082 bp = mSettings.mPermissions.get(permission); 2083 } 2084 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 2085 && (grantedPermissions == null 2086 || ArrayUtils.contains(grantedPermissions, permission))) { 2087 final int flags = permissionsState.getPermissionFlags(permission, userId); 2088 // Installer cannot change immutable permissions. 2089 if ((flags & immutableFlags) == 0) { 2090 grantRuntimePermission(pkg.packageName, permission, userId); 2091 } 2092 } 2093 } 2094 } 2095 2096 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2097 Bundle extras = null; 2098 switch (res.returnCode) { 2099 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2100 extras = new Bundle(); 2101 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2102 res.origPermission); 2103 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2104 res.origPackage); 2105 break; 2106 } 2107 case PackageManager.INSTALL_SUCCEEDED: { 2108 extras = new Bundle(); 2109 extras.putBoolean(Intent.EXTRA_REPLACING, 2110 res.removedInfo != null && res.removedInfo.removedPackage != null); 2111 break; 2112 } 2113 } 2114 return extras; 2115 } 2116 2117 void scheduleWriteSettingsLocked() { 2118 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2119 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2120 } 2121 } 2122 2123 void scheduleWritePackageListLocked(int userId) { 2124 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 2125 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST); 2126 msg.arg1 = userId; 2127 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY); 2128 } 2129 } 2130 2131 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2132 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2133 scheduleWritePackageRestrictionsLocked(userId); 2134 } 2135 2136 void scheduleWritePackageRestrictionsLocked(int userId) { 2137 final int[] userIds = (userId == UserHandle.USER_ALL) 2138 ? sUserManager.getUserIds() : new int[]{userId}; 2139 for (int nextUserId : userIds) { 2140 if (!sUserManager.exists(nextUserId)) return; 2141 mDirtyUsers.add(nextUserId); 2142 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2143 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2144 } 2145 } 2146 } 2147 2148 public static PackageManagerService main(Context context, Installer installer, 2149 boolean factoryTest, boolean onlyCore) { 2150 // Self-check for initial settings. 2151 PackageManagerServiceCompilerMapping.checkProperties(); 2152 2153 PackageManagerService m = new PackageManagerService(context, installer, 2154 factoryTest, onlyCore); 2155 m.enableSystemUserPackages(); 2156 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 2157 // disabled after already being started. 2158 CarrierAppUtils.disableCarrierAppsUntilPrivileged(context.getOpPackageName(), m, 2159 UserHandle.USER_SYSTEM); 2160 ServiceManager.addService("package", m); 2161 return m; 2162 } 2163 2164 private void enableSystemUserPackages() { 2165 if (!UserManager.isSplitSystemUser()) { 2166 return; 2167 } 2168 // For system user, enable apps based on the following conditions: 2169 // - app is whitelisted or belong to one of these groups: 2170 // -- system app which has no launcher icons 2171 // -- system app which has INTERACT_ACROSS_USERS permission 2172 // -- system IME app 2173 // - app is not in the blacklist 2174 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2175 Set<String> enableApps = new ArraySet<>(); 2176 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2177 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2178 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2179 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2180 enableApps.addAll(wlApps); 2181 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2182 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2183 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2184 enableApps.removeAll(blApps); 2185 Log.i(TAG, "Applications installed for system user: " + enableApps); 2186 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2187 UserHandle.SYSTEM); 2188 final int allAppsSize = allAps.size(); 2189 synchronized (mPackages) { 2190 for (int i = 0; i < allAppsSize; i++) { 2191 String pName = allAps.get(i); 2192 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2193 // Should not happen, but we shouldn't be failing if it does 2194 if (pkgSetting == null) { 2195 continue; 2196 } 2197 boolean install = enableApps.contains(pName); 2198 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2199 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2200 + " for system user"); 2201 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2202 } 2203 } 2204 } 2205 } 2206 2207 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2208 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2209 Context.DISPLAY_SERVICE); 2210 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2211 } 2212 2213 public PackageManagerService(Context context, Installer installer, 2214 boolean factoryTest, boolean onlyCore) { 2215 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2216 SystemClock.uptimeMillis()); 2217 2218 if (mSdkVersion <= 0) { 2219 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2220 } 2221 2222 mContext = context; 2223 mFactoryTest = factoryTest; 2224 mOnlyCore = onlyCore; 2225 mMetrics = new DisplayMetrics(); 2226 mSettings = new Settings(mPackages); 2227 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2228 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2229 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2230 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2231 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2232 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2233 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2234 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2235 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2236 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2237 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2238 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2239 2240 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2241 if (separateProcesses != null && separateProcesses.length() > 0) { 2242 if ("*".equals(separateProcesses)) { 2243 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2244 mSeparateProcesses = null; 2245 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2246 } else { 2247 mDefParseFlags = 0; 2248 mSeparateProcesses = separateProcesses.split(","); 2249 Slog.w(TAG, "Running with debug.separate_processes: " 2250 + separateProcesses); 2251 } 2252 } else { 2253 mDefParseFlags = 0; 2254 mSeparateProcesses = null; 2255 } 2256 2257 mInstaller = installer; 2258 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2259 "*dexopt*"); 2260 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2261 2262 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2263 FgThread.get().getLooper()); 2264 2265 getDefaultDisplayMetrics(context, mMetrics); 2266 2267 SystemConfig systemConfig = SystemConfig.getInstance(); 2268 mGlobalGids = systemConfig.getGlobalGids(); 2269 mSystemPermissions = systemConfig.getSystemPermissions(); 2270 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2271 2272 synchronized (mInstallLock) { 2273 // writer 2274 synchronized (mPackages) { 2275 mHandlerThread = new ServiceThread(TAG, 2276 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2277 mHandlerThread.start(); 2278 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2279 mProcessLoggingHandler = new ProcessLoggingHandler(); 2280 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2281 2282 File dataDir = Environment.getDataDirectory(); 2283 mAppInstallDir = new File(dataDir, "app"); 2284 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2285 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2286 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2287 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2288 2289 sUserManager = new UserManagerService(context, this, mPackages); 2290 2291 // Propagate permission configuration in to package manager. 2292 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2293 = systemConfig.getPermissions(); 2294 for (int i=0; i<permConfig.size(); i++) { 2295 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2296 BasePermission bp = mSettings.mPermissions.get(perm.name); 2297 if (bp == null) { 2298 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2299 mSettings.mPermissions.put(perm.name, bp); 2300 } 2301 if (perm.gids != null) { 2302 bp.setGids(perm.gids, perm.perUser); 2303 } 2304 } 2305 2306 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2307 for (int i=0; i<libConfig.size(); i++) { 2308 mSharedLibraries.put(libConfig.keyAt(i), 2309 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2310 } 2311 2312 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2313 2314 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 2315 2316 String customResolverActivity = Resources.getSystem().getString( 2317 R.string.config_customResolverActivity); 2318 if (TextUtils.isEmpty(customResolverActivity)) { 2319 customResolverActivity = null; 2320 } else { 2321 mCustomResolverComponentName = ComponentName.unflattenFromString( 2322 customResolverActivity); 2323 } 2324 2325 long startTime = SystemClock.uptimeMillis(); 2326 2327 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2328 startTime); 2329 2330 // Set flag to monitor and not change apk file paths when 2331 // scanning install directories. 2332 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2333 2334 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2335 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2336 2337 if (bootClassPath == null) { 2338 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2339 } 2340 2341 if (systemServerClassPath == null) { 2342 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2343 } 2344 2345 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2346 final String[] dexCodeInstructionSets = 2347 getDexCodeInstructionSets( 2348 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2349 2350 /** 2351 * Ensure all external libraries have had dexopt run on them. 2352 */ 2353 if (mSharedLibraries.size() > 0) { 2354 // NOTE: For now, we're compiling these system "shared libraries" 2355 // (and framework jars) into all available architectures. It's possible 2356 // to compile them only when we come across an app that uses them (there's 2357 // already logic for that in scanPackageLI) but that adds some complexity. 2358 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2359 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2360 final String lib = libEntry.path; 2361 if (lib == null) { 2362 continue; 2363 } 2364 2365 try { 2366 // Shared libraries do not have profiles so we perform a full 2367 // AOT compilation (if needed). 2368 int dexoptNeeded = DexFile.getDexOptNeeded( 2369 lib, dexCodeInstructionSet, 2370 getCompilerFilterForReason(REASON_SHARED_APK), 2371 false /* newProfile */); 2372 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2373 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2374 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/, 2375 getCompilerFilterForReason(REASON_SHARED_APK), 2376 StorageManager.UUID_PRIVATE_INTERNAL, 2377 SKIP_SHARED_LIBRARY_CHECK); 2378 } 2379 } catch (FileNotFoundException e) { 2380 Slog.w(TAG, "Library not found: " + lib); 2381 } catch (IOException | InstallerException e) { 2382 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2383 + e.getMessage()); 2384 } 2385 } 2386 } 2387 } 2388 2389 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2390 2391 final VersionInfo ver = mSettings.getInternalVersion(); 2392 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2393 2394 // when upgrading from pre-M, promote system app permissions from install to runtime 2395 mPromoteSystemApps = 2396 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2397 2398 // save off the names of pre-existing system packages prior to scanning; we don't 2399 // want to automatically grant runtime permissions for new system apps 2400 if (mPromoteSystemApps) { 2401 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2402 while (pkgSettingIter.hasNext()) { 2403 PackageSetting ps = pkgSettingIter.next(); 2404 if (isSystemApp(ps)) { 2405 mExistingSystemPackages.add(ps.name); 2406 } 2407 } 2408 } 2409 2410 // When upgrading from pre-N, we need to handle package extraction like first boot, 2411 // as there is no profiling data available. 2412 mIsPreNUpgrade = !mSettings.isNWorkDone(); 2413 mSettings.setNWorkDone(); 2414 2415 // Collect vendor overlay packages. 2416 // (Do this before scanning any apps.) 2417 // For security and version matching reason, only consider 2418 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2419 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2420 scanDirTracedLI(vendorOverlayDir, mDefParseFlags 2421 | PackageParser.PARSE_IS_SYSTEM 2422 | PackageParser.PARSE_IS_SYSTEM_DIR 2423 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2424 2425 // Find base frameworks (resource packages without code). 2426 scanDirTracedLI(frameworkDir, mDefParseFlags 2427 | PackageParser.PARSE_IS_SYSTEM 2428 | PackageParser.PARSE_IS_SYSTEM_DIR 2429 | PackageParser.PARSE_IS_PRIVILEGED, 2430 scanFlags | SCAN_NO_DEX, 0); 2431 2432 // Collected privileged system packages. 2433 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2434 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2435 | PackageParser.PARSE_IS_SYSTEM 2436 | PackageParser.PARSE_IS_SYSTEM_DIR 2437 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2438 2439 // Collect ordinary system packages. 2440 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2441 scanDirTracedLI(systemAppDir, mDefParseFlags 2442 | PackageParser.PARSE_IS_SYSTEM 2443 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2444 2445 // Collect all vendor packages. 2446 File vendorAppDir = new File("/vendor/app"); 2447 try { 2448 vendorAppDir = vendorAppDir.getCanonicalFile(); 2449 } catch (IOException e) { 2450 // failed to look up canonical path, continue with original one 2451 } 2452 scanDirTracedLI(vendorAppDir, mDefParseFlags 2453 | PackageParser.PARSE_IS_SYSTEM 2454 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2455 2456 // Collect all OEM packages. 2457 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2458 scanDirTracedLI(oemAppDir, mDefParseFlags 2459 | PackageParser.PARSE_IS_SYSTEM 2460 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2461 2462 // Prune any system packages that no longer exist. 2463 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2464 if (!mOnlyCore) { 2465 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2466 while (psit.hasNext()) { 2467 PackageSetting ps = psit.next(); 2468 2469 /* 2470 * If this is not a system app, it can't be a 2471 * disable system app. 2472 */ 2473 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2474 continue; 2475 } 2476 2477 /* 2478 * If the package is scanned, it's not erased. 2479 */ 2480 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2481 if (scannedPkg != null) { 2482 /* 2483 * If the system app is both scanned and in the 2484 * disabled packages list, then it must have been 2485 * added via OTA. Remove it from the currently 2486 * scanned package so the previously user-installed 2487 * application can be scanned. 2488 */ 2489 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2490 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2491 + ps.name + "; removing system app. Last known codePath=" 2492 + ps.codePathString + ", installStatus=" + ps.installStatus 2493 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2494 + scannedPkg.mVersionCode); 2495 removePackageLI(scannedPkg, true); 2496 mExpectingBetter.put(ps.name, ps.codePath); 2497 } 2498 2499 continue; 2500 } 2501 2502 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2503 psit.remove(); 2504 logCriticalInfo(Log.WARN, "System package " + ps.name 2505 + " no longer exists; it's data will be wiped"); 2506 // Actual deletion of code and data will be handled by later 2507 // reconciliation step 2508 } else { 2509 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2510 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2511 possiblyDeletedUpdatedSystemApps.add(ps.name); 2512 } 2513 } 2514 } 2515 } 2516 2517 //look for any incomplete package installations 2518 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2519 for (int i = 0; i < deletePkgsList.size(); i++) { 2520 // Actual deletion of code and data will be handled by later 2521 // reconciliation step 2522 final String packageName = deletePkgsList.get(i).name; 2523 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2524 synchronized (mPackages) { 2525 mSettings.removePackageLPw(packageName); 2526 } 2527 } 2528 2529 //delete tmp files 2530 deleteTempPackageFiles(); 2531 2532 // Remove any shared userIDs that have no associated packages 2533 mSettings.pruneSharedUsersLPw(); 2534 2535 if (!mOnlyCore) { 2536 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2537 SystemClock.uptimeMillis()); 2538 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2539 2540 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2541 | PackageParser.PARSE_FORWARD_LOCK, 2542 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2543 2544 scanDirLI(mEphemeralInstallDir, mDefParseFlags 2545 | PackageParser.PARSE_IS_EPHEMERAL, 2546 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2547 2548 /** 2549 * Remove disable package settings for any updated system 2550 * apps that were removed via an OTA. If they're not a 2551 * previously-updated app, remove them completely. 2552 * Otherwise, just revoke their system-level permissions. 2553 */ 2554 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2555 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2556 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2557 2558 String msg; 2559 if (deletedPkg == null) { 2560 msg = "Updated system package " + deletedAppName 2561 + " no longer exists; it's data will be wiped"; 2562 // Actual deletion of code and data will be handled by later 2563 // reconciliation step 2564 } else { 2565 msg = "Updated system app + " + deletedAppName 2566 + " no longer present; removing system privileges for " 2567 + deletedAppName; 2568 2569 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2570 2571 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2572 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2573 } 2574 logCriticalInfo(Log.WARN, msg); 2575 } 2576 2577 /** 2578 * Make sure all system apps that we expected to appear on 2579 * the userdata partition actually showed up. If they never 2580 * appeared, crawl back and revive the system version. 2581 */ 2582 for (int i = 0; i < mExpectingBetter.size(); i++) { 2583 final String packageName = mExpectingBetter.keyAt(i); 2584 if (!mPackages.containsKey(packageName)) { 2585 final File scanFile = mExpectingBetter.valueAt(i); 2586 2587 logCriticalInfo(Log.WARN, "Expected better " + packageName 2588 + " but never showed up; reverting to system"); 2589 2590 int reparseFlags = mDefParseFlags; 2591 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2592 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2593 | PackageParser.PARSE_IS_SYSTEM_DIR 2594 | PackageParser.PARSE_IS_PRIVILEGED; 2595 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2596 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2597 | PackageParser.PARSE_IS_SYSTEM_DIR; 2598 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2599 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2600 | PackageParser.PARSE_IS_SYSTEM_DIR; 2601 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2602 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2603 | PackageParser.PARSE_IS_SYSTEM_DIR; 2604 } else { 2605 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2606 continue; 2607 } 2608 2609 mSettings.enableSystemPackageLPw(packageName); 2610 2611 try { 2612 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2613 } catch (PackageManagerException e) { 2614 Slog.e(TAG, "Failed to parse original system package: " 2615 + e.getMessage()); 2616 } 2617 } 2618 } 2619 } 2620 mExpectingBetter.clear(); 2621 2622 // Resolve protected action filters. Only the setup wizard is allowed to 2623 // have a high priority filter for these actions. 2624 mSetupWizardPackage = getSetupWizardPackageName(); 2625 if (mProtectedFilters.size() > 0) { 2626 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2627 Slog.i(TAG, "No setup wizard;" 2628 + " All protected intents capped to priority 0"); 2629 } 2630 for (ActivityIntentInfo filter : mProtectedFilters) { 2631 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2632 if (DEBUG_FILTERS) { 2633 Slog.i(TAG, "Found setup wizard;" 2634 + " allow priority " + filter.getPriority() + ";" 2635 + " package: " + filter.activity.info.packageName 2636 + " activity: " + filter.activity.className 2637 + " priority: " + filter.getPriority()); 2638 } 2639 // skip setup wizard; allow it to keep the high priority filter 2640 continue; 2641 } 2642 Slog.w(TAG, "Protected action; cap priority to 0;" 2643 + " package: " + filter.activity.info.packageName 2644 + " activity: " + filter.activity.className 2645 + " origPrio: " + filter.getPriority()); 2646 filter.setPriority(0); 2647 } 2648 } 2649 mDeferProtectedFilters = false; 2650 mProtectedFilters.clear(); 2651 2652 // Now that we know all of the shared libraries, update all clients to have 2653 // the correct library paths. 2654 updateAllSharedLibrariesLPw(); 2655 2656 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2657 // NOTE: We ignore potential failures here during a system scan (like 2658 // the rest of the commands above) because there's precious little we 2659 // can do about it. A settings error is reported, though. 2660 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2661 false /* boot complete */); 2662 } 2663 2664 // Now that we know all the packages we are keeping, 2665 // read and update their last usage times. 2666 mPackageUsage.readLP(); 2667 2668 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2669 SystemClock.uptimeMillis()); 2670 Slog.i(TAG, "Time to scan packages: " 2671 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2672 + " seconds"); 2673 2674 // If the platform SDK has changed since the last time we booted, 2675 // we need to re-grant app permission to catch any new ones that 2676 // appear. This is really a hack, and means that apps can in some 2677 // cases get permissions that the user didn't initially explicitly 2678 // allow... it would be nice to have some better way to handle 2679 // this situation. 2680 int updateFlags = UPDATE_PERMISSIONS_ALL; 2681 if (ver.sdkVersion != mSdkVersion) { 2682 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2683 + mSdkVersion + "; regranting permissions for internal storage"); 2684 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2685 } 2686 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2687 ver.sdkVersion = mSdkVersion; 2688 2689 // If this is the first boot or an update from pre-M, and it is a normal 2690 // boot, then we need to initialize the default preferred apps across 2691 // all defined users. 2692 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2693 for (UserInfo user : sUserManager.getUsers(true)) { 2694 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2695 applyFactoryDefaultBrowserLPw(user.id); 2696 primeDomainVerificationsLPw(user.id); 2697 } 2698 } 2699 2700 // Prepare storage for system user really early during boot, 2701 // since core system apps like SettingsProvider and SystemUI 2702 // can't wait for user to start 2703 final int storageFlags; 2704 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2705 storageFlags = StorageManager.FLAG_STORAGE_DE; 2706 } else { 2707 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2708 } 2709 reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2710 storageFlags); 2711 2712 // If this is first boot after an OTA, and a normal boot, then 2713 // we need to clear code cache directories. 2714 if (mIsUpgrade && !onlyCore) { 2715 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2716 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2717 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2718 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2719 // No apps are running this early, so no need to freeze 2720 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2721 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2722 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2723 } 2724 clearAppProfilesLIF(ps.pkg); 2725 } 2726 ver.fingerprint = Build.FINGERPRINT; 2727 } 2728 2729 checkDefaultBrowser(); 2730 2731 // clear only after permissions and other defaults have been updated 2732 mExistingSystemPackages.clear(); 2733 mPromoteSystemApps = false; 2734 2735 // All the changes are done during package scanning. 2736 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2737 2738 // can downgrade to reader 2739 mSettings.writeLPr(); 2740 2741 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2742 SystemClock.uptimeMillis()); 2743 2744 if (!mOnlyCore) { 2745 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2746 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2747 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2748 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2749 mIntentFilterVerifierComponent); 2750 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2751 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 2752 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2753 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED); 2754 } else { 2755 mRequiredVerifierPackage = null; 2756 mRequiredInstallerPackage = null; 2757 mIntentFilterVerifierComponent = null; 2758 mIntentFilterVerifier = null; 2759 mServicesSystemSharedLibraryPackageName = null; 2760 mSharedSystemSharedLibraryPackageName = null; 2761 } 2762 2763 mInstallerService = new PackageInstallerService(context, this); 2764 2765 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2766 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2767 // both the installer and resolver must be present to enable ephemeral 2768 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2769 if (DEBUG_EPHEMERAL) { 2770 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2771 + " installer:" + ephemeralInstallerComponent); 2772 } 2773 mEphemeralResolverComponent = ephemeralResolverComponent; 2774 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2775 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2776 mEphemeralResolverConnection = 2777 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2778 } else { 2779 if (DEBUG_EPHEMERAL) { 2780 final String missingComponent = 2781 (ephemeralResolverComponent == null) 2782 ? (ephemeralInstallerComponent == null) 2783 ? "resolver and installer" 2784 : "resolver" 2785 : "installer"; 2786 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2787 } 2788 mEphemeralResolverComponent = null; 2789 mEphemeralInstallerComponent = null; 2790 mEphemeralResolverConnection = null; 2791 } 2792 2793 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2794 } // synchronized (mPackages) 2795 } // synchronized (mInstallLock) 2796 2797 // Now after opening every single application zip, make sure they 2798 // are all flushed. Not really needed, but keeps things nice and 2799 // tidy. 2800 Runtime.getRuntime().gc(); 2801 2802 // The initial scanning above does many calls into installd while 2803 // holding the mPackages lock, but we're mostly interested in yelling 2804 // once we have a booted system. 2805 mInstaller.setWarnIfHeld(mPackages); 2806 2807 // Expose private service for system components to use. 2808 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2809 } 2810 2811 @Override 2812 public boolean isFirstBoot() { 2813 return !mRestoredSettings; 2814 } 2815 2816 @Override 2817 public boolean isOnlyCoreApps() { 2818 return mOnlyCore; 2819 } 2820 2821 @Override 2822 public boolean isUpgrade() { 2823 return mIsUpgrade; 2824 } 2825 2826 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2827 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2828 2829 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2830 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2831 UserHandle.USER_SYSTEM); 2832 if (matches.size() == 1) { 2833 return matches.get(0).getComponentInfo().packageName; 2834 } else { 2835 Log.e(TAG, "There should probably be exactly one verifier; found " + matches); 2836 return null; 2837 } 2838 } 2839 2840 private @NonNull String getRequiredSharedLibraryLPr(String libraryName) { 2841 synchronized (mPackages) { 2842 SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName); 2843 if (libraryEntry == null) { 2844 throw new IllegalStateException("Missing required shared library:" + libraryName); 2845 } 2846 return libraryEntry.apk; 2847 } 2848 } 2849 2850 private @NonNull String getRequiredInstallerLPr() { 2851 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2852 intent.addCategory(Intent.CATEGORY_DEFAULT); 2853 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2854 2855 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2856 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2857 UserHandle.USER_SYSTEM); 2858 if (matches.size() == 1) { 2859 ResolveInfo resolveInfo = matches.get(0); 2860 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 2861 throw new RuntimeException("The installer must be a privileged app"); 2862 } 2863 return matches.get(0).getComponentInfo().packageName; 2864 } else { 2865 throw new RuntimeException("There must be exactly one installer; found " + matches); 2866 } 2867 } 2868 2869 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2870 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2871 2872 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2873 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2874 UserHandle.USER_SYSTEM); 2875 ResolveInfo best = null; 2876 final int N = matches.size(); 2877 for (int i = 0; i < N; i++) { 2878 final ResolveInfo cur = matches.get(i); 2879 final String packageName = cur.getComponentInfo().packageName; 2880 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2881 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2882 continue; 2883 } 2884 2885 if (best == null || cur.priority > best.priority) { 2886 best = cur; 2887 } 2888 } 2889 2890 if (best != null) { 2891 return best.getComponentInfo().getComponentName(); 2892 } else { 2893 throw new RuntimeException("There must be at least one intent filter verifier"); 2894 } 2895 } 2896 2897 private @Nullable ComponentName getEphemeralResolverLPr() { 2898 final String[] packageArray = 2899 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2900 if (packageArray.length == 0) { 2901 if (DEBUG_EPHEMERAL) { 2902 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2903 } 2904 return null; 2905 } 2906 2907 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2908 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 2909 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2910 UserHandle.USER_SYSTEM); 2911 2912 final int N = resolvers.size(); 2913 if (N == 0) { 2914 if (DEBUG_EPHEMERAL) { 2915 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2916 } 2917 return null; 2918 } 2919 2920 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2921 for (int i = 0; i < N; i++) { 2922 final ResolveInfo info = resolvers.get(i); 2923 2924 if (info.serviceInfo == null) { 2925 continue; 2926 } 2927 2928 final String packageName = info.serviceInfo.packageName; 2929 if (!possiblePackages.contains(packageName)) { 2930 if (DEBUG_EPHEMERAL) { 2931 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2932 + " pkg: " + packageName + ", info:" + info); 2933 } 2934 continue; 2935 } 2936 2937 if (DEBUG_EPHEMERAL) { 2938 Slog.v(TAG, "Ephemeral resolver found;" 2939 + " pkg: " + packageName + ", info:" + info); 2940 } 2941 return new ComponentName(packageName, info.serviceInfo.name); 2942 } 2943 if (DEBUG_EPHEMERAL) { 2944 Slog.v(TAG, "Ephemeral resolver NOT found"); 2945 } 2946 return null; 2947 } 2948 2949 private @Nullable ComponentName getEphemeralInstallerLPr() { 2950 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2951 intent.addCategory(Intent.CATEGORY_DEFAULT); 2952 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2953 2954 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2955 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2956 UserHandle.USER_SYSTEM); 2957 if (matches.size() == 0) { 2958 return null; 2959 } else if (matches.size() == 1) { 2960 return matches.get(0).getComponentInfo().getComponentName(); 2961 } else { 2962 throw new RuntimeException( 2963 "There must be at most one ephemeral installer; found " + matches); 2964 } 2965 } 2966 2967 private void primeDomainVerificationsLPw(int userId) { 2968 if (DEBUG_DOMAIN_VERIFICATION) { 2969 Slog.d(TAG, "Priming domain verifications in user " + userId); 2970 } 2971 2972 SystemConfig systemConfig = SystemConfig.getInstance(); 2973 ArraySet<String> packages = systemConfig.getLinkedApps(); 2974 ArraySet<String> domains = new ArraySet<String>(); 2975 2976 for (String packageName : packages) { 2977 PackageParser.Package pkg = mPackages.get(packageName); 2978 if (pkg != null) { 2979 if (!pkg.isSystemApp()) { 2980 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2981 continue; 2982 } 2983 2984 domains.clear(); 2985 for (PackageParser.Activity a : pkg.activities) { 2986 for (ActivityIntentInfo filter : a.intents) { 2987 if (hasValidDomains(filter)) { 2988 domains.addAll(filter.getHostsList()); 2989 } 2990 } 2991 } 2992 2993 if (domains.size() > 0) { 2994 if (DEBUG_DOMAIN_VERIFICATION) { 2995 Slog.v(TAG, " + " + packageName); 2996 } 2997 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2998 // state w.r.t. the formal app-linkage "no verification attempted" state; 2999 // and then 'always' in the per-user state actually used for intent resolution. 3000 final IntentFilterVerificationInfo ivi; 3001 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 3002 new ArrayList<String>(domains)); 3003 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 3004 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 3005 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 3006 } else { 3007 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 3008 + "' does not handle web links"); 3009 } 3010 } else { 3011 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 3012 } 3013 } 3014 3015 scheduleWritePackageRestrictionsLocked(userId); 3016 scheduleWriteSettingsLocked(); 3017 } 3018 3019 private void applyFactoryDefaultBrowserLPw(int userId) { 3020 // The default browser app's package name is stored in a string resource, 3021 // with a product-specific overlay used for vendor customization. 3022 String browserPkg = mContext.getResources().getString( 3023 com.android.internal.R.string.default_browser); 3024 if (!TextUtils.isEmpty(browserPkg)) { 3025 // non-empty string => required to be a known package 3026 PackageSetting ps = mSettings.mPackages.get(browserPkg); 3027 if (ps == null) { 3028 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3029 browserPkg = null; 3030 } else { 3031 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3032 } 3033 } 3034 3035 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3036 // default. If there's more than one, just leave everything alone. 3037 if (browserPkg == null) { 3038 calculateDefaultBrowserLPw(userId); 3039 } 3040 } 3041 3042 private void calculateDefaultBrowserLPw(int userId) { 3043 List<String> allBrowsers = resolveAllBrowserApps(userId); 3044 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3045 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3046 } 3047 3048 private List<String> resolveAllBrowserApps(int userId) { 3049 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3050 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3051 PackageManager.MATCH_ALL, userId); 3052 3053 final int count = list.size(); 3054 List<String> result = new ArrayList<String>(count); 3055 for (int i=0; i<count; i++) { 3056 ResolveInfo info = list.get(i); 3057 if (info.activityInfo == null 3058 || !info.handleAllWebDataURI 3059 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3060 || result.contains(info.activityInfo.packageName)) { 3061 continue; 3062 } 3063 result.add(info.activityInfo.packageName); 3064 } 3065 3066 return result; 3067 } 3068 3069 private boolean packageIsBrowser(String packageName, int userId) { 3070 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3071 PackageManager.MATCH_ALL, userId); 3072 final int N = list.size(); 3073 for (int i = 0; i < N; i++) { 3074 ResolveInfo info = list.get(i); 3075 if (packageName.equals(info.activityInfo.packageName)) { 3076 return true; 3077 } 3078 } 3079 return false; 3080 } 3081 3082 private void checkDefaultBrowser() { 3083 final int myUserId = UserHandle.myUserId(); 3084 final String packageName = getDefaultBrowserPackageName(myUserId); 3085 if (packageName != null) { 3086 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3087 if (info == null) { 3088 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3089 synchronized (mPackages) { 3090 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3091 } 3092 } 3093 } 3094 } 3095 3096 @Override 3097 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3098 throws RemoteException { 3099 try { 3100 return super.onTransact(code, data, reply, flags); 3101 } catch (RuntimeException e) { 3102 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3103 Slog.wtf(TAG, "Package Manager Crash", e); 3104 } 3105 throw e; 3106 } 3107 } 3108 3109 static int[] appendInts(int[] cur, int[] add) { 3110 if (add == null) return cur; 3111 if (cur == null) return add; 3112 final int N = add.length; 3113 for (int i=0; i<N; i++) { 3114 cur = appendInt(cur, add[i]); 3115 } 3116 return cur; 3117 } 3118 3119 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3120 if (!sUserManager.exists(userId)) return null; 3121 if (ps == null) { 3122 return null; 3123 } 3124 final PackageParser.Package p = ps.pkg; 3125 if (p == null) { 3126 return null; 3127 } 3128 3129 final PermissionsState permissionsState = ps.getPermissionsState(); 3130 3131 final int[] gids = permissionsState.computeGids(userId); 3132 final Set<String> permissions = permissionsState.getPermissions(userId); 3133 final PackageUserState state = ps.readUserState(userId); 3134 3135 return PackageParser.generatePackageInfo(p, gids, flags, 3136 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3137 } 3138 3139 @Override 3140 public void checkPackageStartable(String packageName, int userId) { 3141 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3142 3143 synchronized (mPackages) { 3144 final PackageSetting ps = mSettings.mPackages.get(packageName); 3145 if (ps == null) { 3146 throw new SecurityException("Package " + packageName + " was not found!"); 3147 } 3148 3149 if (!ps.getInstalled(userId)) { 3150 throw new SecurityException( 3151 "Package " + packageName + " was not installed for user " + userId + "!"); 3152 } 3153 3154 if (mSafeMode && !ps.isSystem()) { 3155 throw new SecurityException("Package " + packageName + " not a system app!"); 3156 } 3157 3158 if (mFrozenPackages.contains(packageName)) { 3159 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3160 } 3161 3162 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3163 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3164 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3165 } 3166 } 3167 } 3168 3169 @Override 3170 public boolean isPackageAvailable(String packageName, int userId) { 3171 if (!sUserManager.exists(userId)) return false; 3172 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3173 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3174 synchronized (mPackages) { 3175 PackageParser.Package p = mPackages.get(packageName); 3176 if (p != null) { 3177 final PackageSetting ps = (PackageSetting) p.mExtras; 3178 if (ps != null) { 3179 final PackageUserState state = ps.readUserState(userId); 3180 if (state != null) { 3181 return PackageParser.isAvailable(state); 3182 } 3183 } 3184 } 3185 } 3186 return false; 3187 } 3188 3189 @Override 3190 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3191 if (!sUserManager.exists(userId)) return null; 3192 flags = updateFlagsForPackage(flags, userId, packageName); 3193 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3194 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3195 // reader 3196 synchronized (mPackages) { 3197 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3198 PackageParser.Package p = null; 3199 if (matchFactoryOnly) { 3200 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3201 if (ps != null) { 3202 return generatePackageInfo(ps, flags, userId); 3203 } 3204 } 3205 if (p == null) { 3206 p = mPackages.get(packageName); 3207 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3208 return null; 3209 } 3210 } 3211 if (DEBUG_PACKAGE_INFO) 3212 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3213 if (p != null) { 3214 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3215 } 3216 if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3217 final PackageSetting ps = mSettings.mPackages.get(packageName); 3218 return generatePackageInfo(ps, flags, userId); 3219 } 3220 } 3221 return null; 3222 } 3223 3224 @Override 3225 public String[] currentToCanonicalPackageNames(String[] names) { 3226 String[] out = new String[names.length]; 3227 // reader 3228 synchronized (mPackages) { 3229 for (int i=names.length-1; i>=0; i--) { 3230 PackageSetting ps = mSettings.mPackages.get(names[i]); 3231 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3232 } 3233 } 3234 return out; 3235 } 3236 3237 @Override 3238 public String[] canonicalToCurrentPackageNames(String[] names) { 3239 String[] out = new String[names.length]; 3240 // reader 3241 synchronized (mPackages) { 3242 for (int i=names.length-1; i>=0; i--) { 3243 String cur = mSettings.mRenamedPackages.get(names[i]); 3244 out[i] = cur != null ? cur : names[i]; 3245 } 3246 } 3247 return out; 3248 } 3249 3250 @Override 3251 public int getPackageUid(String packageName, int flags, int userId) { 3252 if (!sUserManager.exists(userId)) return -1; 3253 flags = updateFlagsForPackage(flags, userId, packageName); 3254 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3255 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3256 3257 // reader 3258 synchronized (mPackages) { 3259 final PackageParser.Package p = mPackages.get(packageName); 3260 if (p != null && p.isMatch(flags)) { 3261 return UserHandle.getUid(userId, p.applicationInfo.uid); 3262 } 3263 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3264 final PackageSetting ps = mSettings.mPackages.get(packageName); 3265 if (ps != null && ps.isMatch(flags)) { 3266 return UserHandle.getUid(userId, ps.appId); 3267 } 3268 } 3269 } 3270 3271 return -1; 3272 } 3273 3274 @Override 3275 public int[] getPackageGids(String packageName, int flags, int userId) { 3276 if (!sUserManager.exists(userId)) return null; 3277 flags = updateFlagsForPackage(flags, userId, packageName); 3278 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3279 false /* requireFullPermission */, false /* checkShell */, 3280 "getPackageGids"); 3281 3282 // reader 3283 synchronized (mPackages) { 3284 final PackageParser.Package p = mPackages.get(packageName); 3285 if (p != null && p.isMatch(flags)) { 3286 PackageSetting ps = (PackageSetting) p.mExtras; 3287 return ps.getPermissionsState().computeGids(userId); 3288 } 3289 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3290 final PackageSetting ps = mSettings.mPackages.get(packageName); 3291 if (ps != null && ps.isMatch(flags)) { 3292 return ps.getPermissionsState().computeGids(userId); 3293 } 3294 } 3295 } 3296 3297 return null; 3298 } 3299 3300 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3301 if (bp.perm != null) { 3302 return PackageParser.generatePermissionInfo(bp.perm, flags); 3303 } 3304 PermissionInfo pi = new PermissionInfo(); 3305 pi.name = bp.name; 3306 pi.packageName = bp.sourcePackage; 3307 pi.nonLocalizedLabel = bp.name; 3308 pi.protectionLevel = bp.protectionLevel; 3309 return pi; 3310 } 3311 3312 @Override 3313 public PermissionInfo getPermissionInfo(String name, int flags) { 3314 // reader 3315 synchronized (mPackages) { 3316 final BasePermission p = mSettings.mPermissions.get(name); 3317 if (p != null) { 3318 return generatePermissionInfo(p, flags); 3319 } 3320 return null; 3321 } 3322 } 3323 3324 @Override 3325 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3326 int flags) { 3327 // reader 3328 synchronized (mPackages) { 3329 if (group != null && !mPermissionGroups.containsKey(group)) { 3330 // This is thrown as NameNotFoundException 3331 return null; 3332 } 3333 3334 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3335 for (BasePermission p : mSettings.mPermissions.values()) { 3336 if (group == null) { 3337 if (p.perm == null || p.perm.info.group == null) { 3338 out.add(generatePermissionInfo(p, flags)); 3339 } 3340 } else { 3341 if (p.perm != null && group.equals(p.perm.info.group)) { 3342 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3343 } 3344 } 3345 } 3346 return new ParceledListSlice<>(out); 3347 } 3348 } 3349 3350 @Override 3351 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3352 // reader 3353 synchronized (mPackages) { 3354 return PackageParser.generatePermissionGroupInfo( 3355 mPermissionGroups.get(name), flags); 3356 } 3357 } 3358 3359 @Override 3360 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3361 // reader 3362 synchronized (mPackages) { 3363 final int N = mPermissionGroups.size(); 3364 ArrayList<PermissionGroupInfo> out 3365 = new ArrayList<PermissionGroupInfo>(N); 3366 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3367 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3368 } 3369 return new ParceledListSlice<>(out); 3370 } 3371 } 3372 3373 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3374 int userId) { 3375 if (!sUserManager.exists(userId)) return null; 3376 PackageSetting ps = mSettings.mPackages.get(packageName); 3377 if (ps != null) { 3378 if (ps.pkg == null) { 3379 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3380 if (pInfo != null) { 3381 return pInfo.applicationInfo; 3382 } 3383 return null; 3384 } 3385 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3386 ps.readUserState(userId), userId); 3387 } 3388 return null; 3389 } 3390 3391 @Override 3392 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3393 if (!sUserManager.exists(userId)) return null; 3394 flags = updateFlagsForApplication(flags, userId, packageName); 3395 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3396 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3397 // writer 3398 synchronized (mPackages) { 3399 PackageParser.Package p = mPackages.get(packageName); 3400 if (DEBUG_PACKAGE_INFO) Log.v( 3401 TAG, "getApplicationInfo " + packageName 3402 + ": " + p); 3403 if (p != null) { 3404 PackageSetting ps = mSettings.mPackages.get(packageName); 3405 if (ps == null) return null; 3406 // Note: isEnabledLP() does not apply here - always return info 3407 return PackageParser.generateApplicationInfo( 3408 p, flags, ps.readUserState(userId), userId); 3409 } 3410 if ("android".equals(packageName)||"system".equals(packageName)) { 3411 return mAndroidApplication; 3412 } 3413 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3414 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3415 } 3416 } 3417 return null; 3418 } 3419 3420 @Override 3421 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3422 final IPackageDataObserver observer) { 3423 mContext.enforceCallingOrSelfPermission( 3424 android.Manifest.permission.CLEAR_APP_CACHE, null); 3425 // Queue up an async operation since clearing cache may take a little while. 3426 mHandler.post(new Runnable() { 3427 public void run() { 3428 mHandler.removeCallbacks(this); 3429 boolean success = true; 3430 synchronized (mInstallLock) { 3431 try { 3432 mInstaller.freeCache(volumeUuid, freeStorageSize); 3433 } catch (InstallerException e) { 3434 Slog.w(TAG, "Couldn't clear application caches: " + e); 3435 success = false; 3436 } 3437 } 3438 if (observer != null) { 3439 try { 3440 observer.onRemoveCompleted(null, success); 3441 } catch (RemoteException e) { 3442 Slog.w(TAG, "RemoveException when invoking call back"); 3443 } 3444 } 3445 } 3446 }); 3447 } 3448 3449 @Override 3450 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3451 final IntentSender pi) { 3452 mContext.enforceCallingOrSelfPermission( 3453 android.Manifest.permission.CLEAR_APP_CACHE, null); 3454 // Queue up an async operation since clearing cache may take a little while. 3455 mHandler.post(new Runnable() { 3456 public void run() { 3457 mHandler.removeCallbacks(this); 3458 boolean success = true; 3459 synchronized (mInstallLock) { 3460 try { 3461 mInstaller.freeCache(volumeUuid, freeStorageSize); 3462 } catch (InstallerException e) { 3463 Slog.w(TAG, "Couldn't clear application caches: " + e); 3464 success = false; 3465 } 3466 } 3467 if(pi != null) { 3468 try { 3469 // Callback via pending intent 3470 int code = success ? 1 : 0; 3471 pi.sendIntent(null, code, null, 3472 null, null); 3473 } catch (SendIntentException e1) { 3474 Slog.i(TAG, "Failed to send pending intent"); 3475 } 3476 } 3477 } 3478 }); 3479 } 3480 3481 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3482 synchronized (mInstallLock) { 3483 try { 3484 mInstaller.freeCache(volumeUuid, freeStorageSize); 3485 } catch (InstallerException e) { 3486 throw new IOException("Failed to free enough space", e); 3487 } 3488 } 3489 } 3490 3491 /** 3492 * Update given flags based on encryption status of current user. 3493 */ 3494 private int updateFlags(int flags, int userId) { 3495 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3496 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3497 // Caller expressed an explicit opinion about what encryption 3498 // aware/unaware components they want to see, so fall through and 3499 // give them what they want 3500 } else { 3501 // Caller expressed no opinion, so match based on user state 3502 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 3503 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3504 } else { 3505 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3506 } 3507 } 3508 return flags; 3509 } 3510 3511 private UserManagerInternal getUserManagerInternal() { 3512 if (mUserManagerInternal == null) { 3513 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 3514 } 3515 return mUserManagerInternal; 3516 } 3517 3518 /** 3519 * Update given flags when being used to request {@link PackageInfo}. 3520 */ 3521 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3522 boolean triaged = true; 3523 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3524 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3525 // Caller is asking for component details, so they'd better be 3526 // asking for specific encryption matching behavior, or be triaged 3527 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3528 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3529 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3530 triaged = false; 3531 } 3532 } 3533 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3534 | PackageManager.MATCH_SYSTEM_ONLY 3535 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3536 triaged = false; 3537 } 3538 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3539 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3540 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3541 } 3542 return updateFlags(flags, userId); 3543 } 3544 3545 /** 3546 * Update given flags when being used to request {@link ApplicationInfo}. 3547 */ 3548 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3549 return updateFlagsForPackage(flags, userId, cookie); 3550 } 3551 3552 /** 3553 * Update given flags when being used to request {@link ComponentInfo}. 3554 */ 3555 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3556 if (cookie instanceof Intent) { 3557 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3558 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3559 } 3560 } 3561 3562 boolean triaged = true; 3563 // Caller is asking for component details, so they'd better be 3564 // asking for specific encryption matching behavior, or be triaged 3565 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3566 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3567 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3568 triaged = false; 3569 } 3570 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3571 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3572 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3573 } 3574 3575 return updateFlags(flags, userId); 3576 } 3577 3578 /** 3579 * Update given flags when being used to request {@link ResolveInfo}. 3580 */ 3581 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3582 // Safe mode means we shouldn't match any third-party components 3583 if (mSafeMode) { 3584 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3585 } 3586 3587 return updateFlagsForComponent(flags, userId, cookie); 3588 } 3589 3590 @Override 3591 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3592 if (!sUserManager.exists(userId)) return null; 3593 flags = updateFlagsForComponent(flags, userId, component); 3594 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3595 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3596 synchronized (mPackages) { 3597 PackageParser.Activity a = mActivities.mActivities.get(component); 3598 3599 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3600 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3601 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3602 if (ps == null) return null; 3603 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3604 userId); 3605 } 3606 if (mResolveComponentName.equals(component)) { 3607 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3608 new PackageUserState(), userId); 3609 } 3610 } 3611 return null; 3612 } 3613 3614 @Override 3615 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3616 String resolvedType) { 3617 synchronized (mPackages) { 3618 if (component.equals(mResolveComponentName)) { 3619 // The resolver supports EVERYTHING! 3620 return true; 3621 } 3622 PackageParser.Activity a = mActivities.mActivities.get(component); 3623 if (a == null) { 3624 return false; 3625 } 3626 for (int i=0; i<a.intents.size(); i++) { 3627 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3628 intent.getData(), intent.getCategories(), TAG) >= 0) { 3629 return true; 3630 } 3631 } 3632 return false; 3633 } 3634 } 3635 3636 @Override 3637 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3638 if (!sUserManager.exists(userId)) return null; 3639 flags = updateFlagsForComponent(flags, userId, component); 3640 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3641 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3642 synchronized (mPackages) { 3643 PackageParser.Activity a = mReceivers.mActivities.get(component); 3644 if (DEBUG_PACKAGE_INFO) Log.v( 3645 TAG, "getReceiverInfo " + component + ": " + a); 3646 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3647 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3648 if (ps == null) return null; 3649 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3650 userId); 3651 } 3652 } 3653 return null; 3654 } 3655 3656 @Override 3657 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3658 if (!sUserManager.exists(userId)) return null; 3659 flags = updateFlagsForComponent(flags, userId, component); 3660 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3661 false /* requireFullPermission */, false /* checkShell */, "get service info"); 3662 synchronized (mPackages) { 3663 PackageParser.Service s = mServices.mServices.get(component); 3664 if (DEBUG_PACKAGE_INFO) Log.v( 3665 TAG, "getServiceInfo " + component + ": " + s); 3666 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3667 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3668 if (ps == null) return null; 3669 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3670 userId); 3671 } 3672 } 3673 return null; 3674 } 3675 3676 @Override 3677 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3678 if (!sUserManager.exists(userId)) return null; 3679 flags = updateFlagsForComponent(flags, userId, component); 3680 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3681 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 3682 synchronized (mPackages) { 3683 PackageParser.Provider p = mProviders.mProviders.get(component); 3684 if (DEBUG_PACKAGE_INFO) Log.v( 3685 TAG, "getProviderInfo " + component + ": " + p); 3686 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3687 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3688 if (ps == null) return null; 3689 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3690 userId); 3691 } 3692 } 3693 return null; 3694 } 3695 3696 @Override 3697 public String[] getSystemSharedLibraryNames() { 3698 Set<String> libSet; 3699 synchronized (mPackages) { 3700 libSet = mSharedLibraries.keySet(); 3701 int size = libSet.size(); 3702 if (size > 0) { 3703 String[] libs = new String[size]; 3704 libSet.toArray(libs); 3705 return libs; 3706 } 3707 } 3708 return null; 3709 } 3710 3711 @Override 3712 public @NonNull String getServicesSystemSharedLibraryPackageName() { 3713 synchronized (mPackages) { 3714 return mServicesSystemSharedLibraryPackageName; 3715 } 3716 } 3717 3718 @Override 3719 public @NonNull String getSharedSystemSharedLibraryPackageName() { 3720 synchronized (mPackages) { 3721 return mSharedSystemSharedLibraryPackageName; 3722 } 3723 } 3724 3725 @Override 3726 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 3727 synchronized (mPackages) { 3728 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values()); 3729 3730 final FeatureInfo fi = new FeatureInfo(); 3731 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3732 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3733 res.add(fi); 3734 3735 return new ParceledListSlice<>(res); 3736 } 3737 } 3738 3739 @Override 3740 public boolean hasSystemFeature(String name, int version) { 3741 synchronized (mPackages) { 3742 final FeatureInfo feat = mAvailableFeatures.get(name); 3743 if (feat == null) { 3744 return false; 3745 } else { 3746 return feat.version >= version; 3747 } 3748 } 3749 } 3750 3751 @Override 3752 public int checkPermission(String permName, String pkgName, int userId) { 3753 if (!sUserManager.exists(userId)) { 3754 return PackageManager.PERMISSION_DENIED; 3755 } 3756 3757 synchronized (mPackages) { 3758 final PackageParser.Package p = mPackages.get(pkgName); 3759 if (p != null && p.mExtras != null) { 3760 final PackageSetting ps = (PackageSetting) p.mExtras; 3761 final PermissionsState permissionsState = ps.getPermissionsState(); 3762 if (permissionsState.hasPermission(permName, userId)) { 3763 return PackageManager.PERMISSION_GRANTED; 3764 } 3765 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3766 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3767 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3768 return PackageManager.PERMISSION_GRANTED; 3769 } 3770 } 3771 } 3772 3773 return PackageManager.PERMISSION_DENIED; 3774 } 3775 3776 @Override 3777 public int checkUidPermission(String permName, int uid) { 3778 final int userId = UserHandle.getUserId(uid); 3779 3780 if (!sUserManager.exists(userId)) { 3781 return PackageManager.PERMISSION_DENIED; 3782 } 3783 3784 synchronized (mPackages) { 3785 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3786 if (obj != null) { 3787 final SettingBase ps = (SettingBase) obj; 3788 final PermissionsState permissionsState = ps.getPermissionsState(); 3789 if (permissionsState.hasPermission(permName, userId)) { 3790 return PackageManager.PERMISSION_GRANTED; 3791 } 3792 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3793 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3794 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3795 return PackageManager.PERMISSION_GRANTED; 3796 } 3797 } else { 3798 ArraySet<String> perms = mSystemPermissions.get(uid); 3799 if (perms != null) { 3800 if (perms.contains(permName)) { 3801 return PackageManager.PERMISSION_GRANTED; 3802 } 3803 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3804 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3805 return PackageManager.PERMISSION_GRANTED; 3806 } 3807 } 3808 } 3809 } 3810 3811 return PackageManager.PERMISSION_DENIED; 3812 } 3813 3814 @Override 3815 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3816 if (UserHandle.getCallingUserId() != userId) { 3817 mContext.enforceCallingPermission( 3818 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3819 "isPermissionRevokedByPolicy for user " + userId); 3820 } 3821 3822 if (checkPermission(permission, packageName, userId) 3823 == PackageManager.PERMISSION_GRANTED) { 3824 return false; 3825 } 3826 3827 final long identity = Binder.clearCallingIdentity(); 3828 try { 3829 final int flags = getPermissionFlags(permission, packageName, userId); 3830 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3831 } finally { 3832 Binder.restoreCallingIdentity(identity); 3833 } 3834 } 3835 3836 @Override 3837 public String getPermissionControllerPackageName() { 3838 synchronized (mPackages) { 3839 return mRequiredInstallerPackage; 3840 } 3841 } 3842 3843 /** 3844 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3845 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3846 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3847 * @param message the message to log on security exception 3848 */ 3849 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3850 boolean checkShell, String message) { 3851 if (userId < 0) { 3852 throw new IllegalArgumentException("Invalid userId " + userId); 3853 } 3854 if (checkShell) { 3855 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3856 } 3857 if (userId == UserHandle.getUserId(callingUid)) return; 3858 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3859 if (requireFullPermission) { 3860 mContext.enforceCallingOrSelfPermission( 3861 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3862 } else { 3863 try { 3864 mContext.enforceCallingOrSelfPermission( 3865 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3866 } catch (SecurityException se) { 3867 mContext.enforceCallingOrSelfPermission( 3868 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3869 } 3870 } 3871 } 3872 } 3873 3874 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3875 if (callingUid == Process.SHELL_UID) { 3876 if (userHandle >= 0 3877 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3878 throw new SecurityException("Shell does not have permission to access user " 3879 + userHandle); 3880 } else if (userHandle < 0) { 3881 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3882 + Debug.getCallers(3)); 3883 } 3884 } 3885 } 3886 3887 private BasePermission findPermissionTreeLP(String permName) { 3888 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3889 if (permName.startsWith(bp.name) && 3890 permName.length() > bp.name.length() && 3891 permName.charAt(bp.name.length()) == '.') { 3892 return bp; 3893 } 3894 } 3895 return null; 3896 } 3897 3898 private BasePermission checkPermissionTreeLP(String permName) { 3899 if (permName != null) { 3900 BasePermission bp = findPermissionTreeLP(permName); 3901 if (bp != null) { 3902 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3903 return bp; 3904 } 3905 throw new SecurityException("Calling uid " 3906 + Binder.getCallingUid() 3907 + " is not allowed to add to permission tree " 3908 + bp.name + " owned by uid " + bp.uid); 3909 } 3910 } 3911 throw new SecurityException("No permission tree found for " + permName); 3912 } 3913 3914 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3915 if (s1 == null) { 3916 return s2 == null; 3917 } 3918 if (s2 == null) { 3919 return false; 3920 } 3921 if (s1.getClass() != s2.getClass()) { 3922 return false; 3923 } 3924 return s1.equals(s2); 3925 } 3926 3927 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3928 if (pi1.icon != pi2.icon) return false; 3929 if (pi1.logo != pi2.logo) return false; 3930 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3931 if (!compareStrings(pi1.name, pi2.name)) return false; 3932 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3933 // We'll take care of setting this one. 3934 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3935 // These are not currently stored in settings. 3936 //if (!compareStrings(pi1.group, pi2.group)) return false; 3937 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3938 //if (pi1.labelRes != pi2.labelRes) return false; 3939 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3940 return true; 3941 } 3942 3943 int permissionInfoFootprint(PermissionInfo info) { 3944 int size = info.name.length(); 3945 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3946 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3947 return size; 3948 } 3949 3950 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3951 int size = 0; 3952 for (BasePermission perm : mSettings.mPermissions.values()) { 3953 if (perm.uid == tree.uid) { 3954 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3955 } 3956 } 3957 return size; 3958 } 3959 3960 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3961 // We calculate the max size of permissions defined by this uid and throw 3962 // if that plus the size of 'info' would exceed our stated maximum. 3963 if (tree.uid != Process.SYSTEM_UID) { 3964 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3965 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3966 throw new SecurityException("Permission tree size cap exceeded"); 3967 } 3968 } 3969 } 3970 3971 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3972 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3973 throw new SecurityException("Label must be specified in permission"); 3974 } 3975 BasePermission tree = checkPermissionTreeLP(info.name); 3976 BasePermission bp = mSettings.mPermissions.get(info.name); 3977 boolean added = bp == null; 3978 boolean changed = true; 3979 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3980 if (added) { 3981 enforcePermissionCapLocked(info, tree); 3982 bp = new BasePermission(info.name, tree.sourcePackage, 3983 BasePermission.TYPE_DYNAMIC); 3984 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3985 throw new SecurityException( 3986 "Not allowed to modify non-dynamic permission " 3987 + info.name); 3988 } else { 3989 if (bp.protectionLevel == fixedLevel 3990 && bp.perm.owner.equals(tree.perm.owner) 3991 && bp.uid == tree.uid 3992 && comparePermissionInfos(bp.perm.info, info)) { 3993 changed = false; 3994 } 3995 } 3996 bp.protectionLevel = fixedLevel; 3997 info = new PermissionInfo(info); 3998 info.protectionLevel = fixedLevel; 3999 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 4000 bp.perm.info.packageName = tree.perm.info.packageName; 4001 bp.uid = tree.uid; 4002 if (added) { 4003 mSettings.mPermissions.put(info.name, bp); 4004 } 4005 if (changed) { 4006 if (!async) { 4007 mSettings.writeLPr(); 4008 } else { 4009 scheduleWriteSettingsLocked(); 4010 } 4011 } 4012 return added; 4013 } 4014 4015 @Override 4016 public boolean addPermission(PermissionInfo info) { 4017 synchronized (mPackages) { 4018 return addPermissionLocked(info, false); 4019 } 4020 } 4021 4022 @Override 4023 public boolean addPermissionAsync(PermissionInfo info) { 4024 synchronized (mPackages) { 4025 return addPermissionLocked(info, true); 4026 } 4027 } 4028 4029 @Override 4030 public void removePermission(String name) { 4031 synchronized (mPackages) { 4032 checkPermissionTreeLP(name); 4033 BasePermission bp = mSettings.mPermissions.get(name); 4034 if (bp != null) { 4035 if (bp.type != BasePermission.TYPE_DYNAMIC) { 4036 throw new SecurityException( 4037 "Not allowed to modify non-dynamic permission " 4038 + name); 4039 } 4040 mSettings.mPermissions.remove(name); 4041 mSettings.writeLPr(); 4042 } 4043 } 4044 } 4045 4046 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 4047 BasePermission bp) { 4048 int index = pkg.requestedPermissions.indexOf(bp.name); 4049 if (index == -1) { 4050 throw new SecurityException("Package " + pkg.packageName 4051 + " has not requested permission " + bp.name); 4052 } 4053 if (!bp.isRuntime() && !bp.isDevelopment()) { 4054 throw new SecurityException("Permission " + bp.name 4055 + " is not a changeable permission type"); 4056 } 4057 } 4058 4059 @Override 4060 public void grantRuntimePermission(String packageName, String name, final int userId) { 4061 if (!sUserManager.exists(userId)) { 4062 Log.e(TAG, "No such user:" + userId); 4063 return; 4064 } 4065 4066 mContext.enforceCallingOrSelfPermission( 4067 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 4068 "grantRuntimePermission"); 4069 4070 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4071 true /* requireFullPermission */, true /* checkShell */, 4072 "grantRuntimePermission"); 4073 4074 final int uid; 4075 final SettingBase sb; 4076 4077 synchronized (mPackages) { 4078 final PackageParser.Package pkg = mPackages.get(packageName); 4079 if (pkg == null) { 4080 throw new IllegalArgumentException("Unknown package: " + packageName); 4081 } 4082 4083 final BasePermission bp = mSettings.mPermissions.get(name); 4084 if (bp == null) { 4085 throw new IllegalArgumentException("Unknown permission: " + name); 4086 } 4087 4088 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4089 4090 // If a permission review is required for legacy apps we represent 4091 // their permissions as always granted runtime ones since we need 4092 // to keep the review required permission flag per user while an 4093 // install permission's state is shared across all users. 4094 if (Build.PERMISSIONS_REVIEW_REQUIRED 4095 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4096 && bp.isRuntime()) { 4097 return; 4098 } 4099 4100 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4101 sb = (SettingBase) pkg.mExtras; 4102 if (sb == null) { 4103 throw new IllegalArgumentException("Unknown package: " + packageName); 4104 } 4105 4106 final PermissionsState permissionsState = sb.getPermissionsState(); 4107 4108 final int flags = permissionsState.getPermissionFlags(name, userId); 4109 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4110 throw new SecurityException("Cannot grant system fixed permission " 4111 + name + " for package " + packageName); 4112 } 4113 4114 if (bp.isDevelopment()) { 4115 // Development permissions must be handled specially, since they are not 4116 // normal runtime permissions. For now they apply to all users. 4117 if (permissionsState.grantInstallPermission(bp) != 4118 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4119 scheduleWriteSettingsLocked(); 4120 } 4121 return; 4122 } 4123 4124 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4125 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4126 return; 4127 } 4128 4129 final int result = permissionsState.grantRuntimePermission(bp, userId); 4130 switch (result) { 4131 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4132 return; 4133 } 4134 4135 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4136 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4137 mHandler.post(new Runnable() { 4138 @Override 4139 public void run() { 4140 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4141 } 4142 }); 4143 } 4144 break; 4145 } 4146 4147 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4148 4149 // Not critical if that is lost - app has to request again. 4150 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4151 } 4152 4153 // Only need to do this if user is initialized. Otherwise it's a new user 4154 // and there are no processes running as the user yet and there's no need 4155 // to make an expensive call to remount processes for the changed permissions. 4156 if (READ_EXTERNAL_STORAGE.equals(name) 4157 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4158 final long token = Binder.clearCallingIdentity(); 4159 try { 4160 if (sUserManager.isInitialized(userId)) { 4161 MountServiceInternal mountServiceInternal = LocalServices.getService( 4162 MountServiceInternal.class); 4163 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 4164 } 4165 } finally { 4166 Binder.restoreCallingIdentity(token); 4167 } 4168 } 4169 } 4170 4171 @Override 4172 public void revokeRuntimePermission(String packageName, String name, int userId) { 4173 if (!sUserManager.exists(userId)) { 4174 Log.e(TAG, "No such user:" + userId); 4175 return; 4176 } 4177 4178 mContext.enforceCallingOrSelfPermission( 4179 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4180 "revokeRuntimePermission"); 4181 4182 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4183 true /* requireFullPermission */, true /* checkShell */, 4184 "revokeRuntimePermission"); 4185 4186 final int appId; 4187 4188 synchronized (mPackages) { 4189 final PackageParser.Package pkg = mPackages.get(packageName); 4190 if (pkg == null) { 4191 throw new IllegalArgumentException("Unknown package: " + packageName); 4192 } 4193 4194 final BasePermission bp = mSettings.mPermissions.get(name); 4195 if (bp == null) { 4196 throw new IllegalArgumentException("Unknown permission: " + name); 4197 } 4198 4199 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4200 4201 // If a permission review is required for legacy apps we represent 4202 // their permissions as always granted runtime ones since we need 4203 // to keep the review required permission flag per user while an 4204 // install permission's state is shared across all users. 4205 if (Build.PERMISSIONS_REVIEW_REQUIRED 4206 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4207 && bp.isRuntime()) { 4208 return; 4209 } 4210 4211 SettingBase sb = (SettingBase) pkg.mExtras; 4212 if (sb == null) { 4213 throw new IllegalArgumentException("Unknown package: " + packageName); 4214 } 4215 4216 final PermissionsState permissionsState = sb.getPermissionsState(); 4217 4218 final int flags = permissionsState.getPermissionFlags(name, userId); 4219 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4220 throw new SecurityException("Cannot revoke system fixed permission " 4221 + name + " for package " + packageName); 4222 } 4223 4224 if (bp.isDevelopment()) { 4225 // Development permissions must be handled specially, since they are not 4226 // normal runtime permissions. For now they apply to all users. 4227 if (permissionsState.revokeInstallPermission(bp) != 4228 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4229 scheduleWriteSettingsLocked(); 4230 } 4231 return; 4232 } 4233 4234 if (permissionsState.revokeRuntimePermission(bp, userId) == 4235 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4236 return; 4237 } 4238 4239 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4240 4241 // Critical, after this call app should never have the permission. 4242 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4243 4244 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4245 } 4246 4247 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4248 } 4249 4250 @Override 4251 public void resetRuntimePermissions() { 4252 mContext.enforceCallingOrSelfPermission( 4253 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4254 "revokeRuntimePermission"); 4255 4256 int callingUid = Binder.getCallingUid(); 4257 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4258 mContext.enforceCallingOrSelfPermission( 4259 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4260 "resetRuntimePermissions"); 4261 } 4262 4263 synchronized (mPackages) { 4264 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4265 for (int userId : UserManagerService.getInstance().getUserIds()) { 4266 final int packageCount = mPackages.size(); 4267 for (int i = 0; i < packageCount; i++) { 4268 PackageParser.Package pkg = mPackages.valueAt(i); 4269 if (!(pkg.mExtras instanceof PackageSetting)) { 4270 continue; 4271 } 4272 PackageSetting ps = (PackageSetting) pkg.mExtras; 4273 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4274 } 4275 } 4276 } 4277 } 4278 4279 @Override 4280 public int getPermissionFlags(String name, String packageName, int userId) { 4281 if (!sUserManager.exists(userId)) { 4282 return 0; 4283 } 4284 4285 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4286 4287 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4288 true /* requireFullPermission */, false /* checkShell */, 4289 "getPermissionFlags"); 4290 4291 synchronized (mPackages) { 4292 final PackageParser.Package pkg = mPackages.get(packageName); 4293 if (pkg == null) { 4294 return 0; 4295 } 4296 4297 final BasePermission bp = mSettings.mPermissions.get(name); 4298 if (bp == null) { 4299 return 0; 4300 } 4301 4302 SettingBase sb = (SettingBase) pkg.mExtras; 4303 if (sb == null) { 4304 return 0; 4305 } 4306 4307 PermissionsState permissionsState = sb.getPermissionsState(); 4308 return permissionsState.getPermissionFlags(name, userId); 4309 } 4310 } 4311 4312 @Override 4313 public void updatePermissionFlags(String name, String packageName, int flagMask, 4314 int flagValues, int userId) { 4315 if (!sUserManager.exists(userId)) { 4316 return; 4317 } 4318 4319 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4320 4321 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4322 true /* requireFullPermission */, true /* checkShell */, 4323 "updatePermissionFlags"); 4324 4325 // Only the system can change these flags and nothing else. 4326 if (getCallingUid() != Process.SYSTEM_UID) { 4327 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4328 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4329 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4330 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4331 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4332 } 4333 4334 synchronized (mPackages) { 4335 final PackageParser.Package pkg = mPackages.get(packageName); 4336 if (pkg == null) { 4337 throw new IllegalArgumentException("Unknown package: " + packageName); 4338 } 4339 4340 final BasePermission bp = mSettings.mPermissions.get(name); 4341 if (bp == null) { 4342 throw new IllegalArgumentException("Unknown permission: " + name); 4343 } 4344 4345 SettingBase sb = (SettingBase) pkg.mExtras; 4346 if (sb == null) { 4347 throw new IllegalArgumentException("Unknown package: " + packageName); 4348 } 4349 4350 PermissionsState permissionsState = sb.getPermissionsState(); 4351 4352 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4353 4354 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4355 // Install and runtime permissions are stored in different places, 4356 // so figure out what permission changed and persist the change. 4357 if (permissionsState.getInstallPermissionState(name) != null) { 4358 scheduleWriteSettingsLocked(); 4359 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4360 || hadState) { 4361 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4362 } 4363 } 4364 } 4365 } 4366 4367 /** 4368 * Update the permission flags for all packages and runtime permissions of a user in order 4369 * to allow device or profile owner to remove POLICY_FIXED. 4370 */ 4371 @Override 4372 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4373 if (!sUserManager.exists(userId)) { 4374 return; 4375 } 4376 4377 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4378 4379 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4380 true /* requireFullPermission */, true /* checkShell */, 4381 "updatePermissionFlagsForAllApps"); 4382 4383 // Only the system can change system fixed flags. 4384 if (getCallingUid() != Process.SYSTEM_UID) { 4385 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4386 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4387 } 4388 4389 synchronized (mPackages) { 4390 boolean changed = false; 4391 final int packageCount = mPackages.size(); 4392 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4393 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4394 SettingBase sb = (SettingBase) pkg.mExtras; 4395 if (sb == null) { 4396 continue; 4397 } 4398 PermissionsState permissionsState = sb.getPermissionsState(); 4399 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4400 userId, flagMask, flagValues); 4401 } 4402 if (changed) { 4403 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4404 } 4405 } 4406 } 4407 4408 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4409 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4410 != PackageManager.PERMISSION_GRANTED 4411 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4412 != PackageManager.PERMISSION_GRANTED) { 4413 throw new SecurityException(message + " requires " 4414 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4415 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4416 } 4417 } 4418 4419 @Override 4420 public boolean shouldShowRequestPermissionRationale(String permissionName, 4421 String packageName, int userId) { 4422 if (UserHandle.getCallingUserId() != userId) { 4423 mContext.enforceCallingPermission( 4424 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4425 "canShowRequestPermissionRationale for user " + userId); 4426 } 4427 4428 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4429 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4430 return false; 4431 } 4432 4433 if (checkPermission(permissionName, packageName, userId) 4434 == PackageManager.PERMISSION_GRANTED) { 4435 return false; 4436 } 4437 4438 final int flags; 4439 4440 final long identity = Binder.clearCallingIdentity(); 4441 try { 4442 flags = getPermissionFlags(permissionName, 4443 packageName, userId); 4444 } finally { 4445 Binder.restoreCallingIdentity(identity); 4446 } 4447 4448 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4449 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4450 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4451 4452 if ((flags & fixedFlags) != 0) { 4453 return false; 4454 } 4455 4456 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4457 } 4458 4459 @Override 4460 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4461 mContext.enforceCallingOrSelfPermission( 4462 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4463 "addOnPermissionsChangeListener"); 4464 4465 synchronized (mPackages) { 4466 mOnPermissionChangeListeners.addListenerLocked(listener); 4467 } 4468 } 4469 4470 @Override 4471 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4472 synchronized (mPackages) { 4473 mOnPermissionChangeListeners.removeListenerLocked(listener); 4474 } 4475 } 4476 4477 @Override 4478 public boolean isProtectedBroadcast(String actionName) { 4479 synchronized (mPackages) { 4480 if (mProtectedBroadcasts.contains(actionName)) { 4481 return true; 4482 } else if (actionName != null) { 4483 // TODO: remove these terrible hacks 4484 if (actionName.startsWith("android.net.netmon.lingerExpired") 4485 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4486 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 4487 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 4488 return true; 4489 } 4490 } 4491 } 4492 return false; 4493 } 4494 4495 @Override 4496 public int checkSignatures(String pkg1, String pkg2) { 4497 synchronized (mPackages) { 4498 final PackageParser.Package p1 = mPackages.get(pkg1); 4499 final PackageParser.Package p2 = mPackages.get(pkg2); 4500 if (p1 == null || p1.mExtras == null 4501 || p2 == null || p2.mExtras == null) { 4502 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4503 } 4504 return compareSignatures(p1.mSignatures, p2.mSignatures); 4505 } 4506 } 4507 4508 @Override 4509 public int checkUidSignatures(int uid1, int uid2) { 4510 // Map to base uids. 4511 uid1 = UserHandle.getAppId(uid1); 4512 uid2 = UserHandle.getAppId(uid2); 4513 // reader 4514 synchronized (mPackages) { 4515 Signature[] s1; 4516 Signature[] s2; 4517 Object obj = mSettings.getUserIdLPr(uid1); 4518 if (obj != null) { 4519 if (obj instanceof SharedUserSetting) { 4520 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4521 } else if (obj instanceof PackageSetting) { 4522 s1 = ((PackageSetting)obj).signatures.mSignatures; 4523 } else { 4524 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4525 } 4526 } else { 4527 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4528 } 4529 obj = mSettings.getUserIdLPr(uid2); 4530 if (obj != null) { 4531 if (obj instanceof SharedUserSetting) { 4532 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4533 } else if (obj instanceof PackageSetting) { 4534 s2 = ((PackageSetting)obj).signatures.mSignatures; 4535 } else { 4536 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4537 } 4538 } else { 4539 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4540 } 4541 return compareSignatures(s1, s2); 4542 } 4543 } 4544 4545 /** 4546 * This method should typically only be used when granting or revoking 4547 * permissions, since the app may immediately restart after this call. 4548 * <p> 4549 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 4550 * guard your work against the app being relaunched. 4551 */ 4552 private void killUid(int appId, int userId, String reason) { 4553 final long identity = Binder.clearCallingIdentity(); 4554 try { 4555 IActivityManager am = ActivityManagerNative.getDefault(); 4556 if (am != null) { 4557 try { 4558 am.killUid(appId, userId, reason); 4559 } catch (RemoteException e) { 4560 /* ignore - same process */ 4561 } 4562 } 4563 } finally { 4564 Binder.restoreCallingIdentity(identity); 4565 } 4566 } 4567 4568 /** 4569 * Compares two sets of signatures. Returns: 4570 * <br /> 4571 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4572 * <br /> 4573 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4574 * <br /> 4575 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4576 * <br /> 4577 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4578 * <br /> 4579 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4580 */ 4581 static int compareSignatures(Signature[] s1, Signature[] s2) { 4582 if (s1 == null) { 4583 return s2 == null 4584 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4585 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4586 } 4587 4588 if (s2 == null) { 4589 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4590 } 4591 4592 if (s1.length != s2.length) { 4593 return PackageManager.SIGNATURE_NO_MATCH; 4594 } 4595 4596 // Since both signature sets are of size 1, we can compare without HashSets. 4597 if (s1.length == 1) { 4598 return s1[0].equals(s2[0]) ? 4599 PackageManager.SIGNATURE_MATCH : 4600 PackageManager.SIGNATURE_NO_MATCH; 4601 } 4602 4603 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4604 for (Signature sig : s1) { 4605 set1.add(sig); 4606 } 4607 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4608 for (Signature sig : s2) { 4609 set2.add(sig); 4610 } 4611 // Make sure s2 contains all signatures in s1. 4612 if (set1.equals(set2)) { 4613 return PackageManager.SIGNATURE_MATCH; 4614 } 4615 return PackageManager.SIGNATURE_NO_MATCH; 4616 } 4617 4618 /** 4619 * If the database version for this type of package (internal storage or 4620 * external storage) is less than the version where package signatures 4621 * were updated, return true. 4622 */ 4623 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4624 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4625 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4626 } 4627 4628 /** 4629 * Used for backward compatibility to make sure any packages with 4630 * certificate chains get upgraded to the new style. {@code existingSigs} 4631 * will be in the old format (since they were stored on disk from before the 4632 * system upgrade) and {@code scannedSigs} will be in the newer format. 4633 */ 4634 private int compareSignaturesCompat(PackageSignatures existingSigs, 4635 PackageParser.Package scannedPkg) { 4636 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4637 return PackageManager.SIGNATURE_NO_MATCH; 4638 } 4639 4640 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4641 for (Signature sig : existingSigs.mSignatures) { 4642 existingSet.add(sig); 4643 } 4644 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4645 for (Signature sig : scannedPkg.mSignatures) { 4646 try { 4647 Signature[] chainSignatures = sig.getChainSignatures(); 4648 for (Signature chainSig : chainSignatures) { 4649 scannedCompatSet.add(chainSig); 4650 } 4651 } catch (CertificateEncodingException e) { 4652 scannedCompatSet.add(sig); 4653 } 4654 } 4655 /* 4656 * Make sure the expanded scanned set contains all signatures in the 4657 * existing one. 4658 */ 4659 if (scannedCompatSet.equals(existingSet)) { 4660 // Migrate the old signatures to the new scheme. 4661 existingSigs.assignSignatures(scannedPkg.mSignatures); 4662 // The new KeySets will be re-added later in the scanning process. 4663 synchronized (mPackages) { 4664 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4665 } 4666 return PackageManager.SIGNATURE_MATCH; 4667 } 4668 return PackageManager.SIGNATURE_NO_MATCH; 4669 } 4670 4671 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4672 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4673 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4674 } 4675 4676 private int compareSignaturesRecover(PackageSignatures existingSigs, 4677 PackageParser.Package scannedPkg) { 4678 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4679 return PackageManager.SIGNATURE_NO_MATCH; 4680 } 4681 4682 String msg = null; 4683 try { 4684 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4685 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4686 + scannedPkg.packageName); 4687 return PackageManager.SIGNATURE_MATCH; 4688 } 4689 } catch (CertificateException e) { 4690 msg = e.getMessage(); 4691 } 4692 4693 logCriticalInfo(Log.INFO, 4694 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4695 return PackageManager.SIGNATURE_NO_MATCH; 4696 } 4697 4698 @Override 4699 public List<String> getAllPackages() { 4700 synchronized (mPackages) { 4701 return new ArrayList<String>(mPackages.keySet()); 4702 } 4703 } 4704 4705 @Override 4706 public String[] getPackagesForUid(int uid) { 4707 uid = UserHandle.getAppId(uid); 4708 // reader 4709 synchronized (mPackages) { 4710 Object obj = mSettings.getUserIdLPr(uid); 4711 if (obj instanceof SharedUserSetting) { 4712 final SharedUserSetting sus = (SharedUserSetting) obj; 4713 final int N = sus.packages.size(); 4714 final String[] res = new String[N]; 4715 final Iterator<PackageSetting> it = sus.packages.iterator(); 4716 int i = 0; 4717 while (it.hasNext()) { 4718 res[i++] = it.next().name; 4719 } 4720 return res; 4721 } else if (obj instanceof PackageSetting) { 4722 final PackageSetting ps = (PackageSetting) obj; 4723 return new String[] { ps.name }; 4724 } 4725 } 4726 return null; 4727 } 4728 4729 @Override 4730 public String getNameForUid(int uid) { 4731 // reader 4732 synchronized (mPackages) { 4733 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4734 if (obj instanceof SharedUserSetting) { 4735 final SharedUserSetting sus = (SharedUserSetting) obj; 4736 return sus.name + ":" + sus.userId; 4737 } else if (obj instanceof PackageSetting) { 4738 final PackageSetting ps = (PackageSetting) obj; 4739 return ps.name; 4740 } 4741 } 4742 return null; 4743 } 4744 4745 @Override 4746 public int getUidForSharedUser(String sharedUserName) { 4747 if(sharedUserName == null) { 4748 return -1; 4749 } 4750 // reader 4751 synchronized (mPackages) { 4752 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4753 if (suid == null) { 4754 return -1; 4755 } 4756 return suid.userId; 4757 } 4758 } 4759 4760 @Override 4761 public int getFlagsForUid(int uid) { 4762 synchronized (mPackages) { 4763 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4764 if (obj instanceof SharedUserSetting) { 4765 final SharedUserSetting sus = (SharedUserSetting) obj; 4766 return sus.pkgFlags; 4767 } else if (obj instanceof PackageSetting) { 4768 final PackageSetting ps = (PackageSetting) obj; 4769 return ps.pkgFlags; 4770 } 4771 } 4772 return 0; 4773 } 4774 4775 @Override 4776 public int getPrivateFlagsForUid(int uid) { 4777 synchronized (mPackages) { 4778 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4779 if (obj instanceof SharedUserSetting) { 4780 final SharedUserSetting sus = (SharedUserSetting) obj; 4781 return sus.pkgPrivateFlags; 4782 } else if (obj instanceof PackageSetting) { 4783 final PackageSetting ps = (PackageSetting) obj; 4784 return ps.pkgPrivateFlags; 4785 } 4786 } 4787 return 0; 4788 } 4789 4790 @Override 4791 public boolean isUidPrivileged(int uid) { 4792 uid = UserHandle.getAppId(uid); 4793 // reader 4794 synchronized (mPackages) { 4795 Object obj = mSettings.getUserIdLPr(uid); 4796 if (obj instanceof SharedUserSetting) { 4797 final SharedUserSetting sus = (SharedUserSetting) obj; 4798 final Iterator<PackageSetting> it = sus.packages.iterator(); 4799 while (it.hasNext()) { 4800 if (it.next().isPrivileged()) { 4801 return true; 4802 } 4803 } 4804 } else if (obj instanceof PackageSetting) { 4805 final PackageSetting ps = (PackageSetting) obj; 4806 return ps.isPrivileged(); 4807 } 4808 } 4809 return false; 4810 } 4811 4812 @Override 4813 public String[] getAppOpPermissionPackages(String permissionName) { 4814 synchronized (mPackages) { 4815 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4816 if (pkgs == null) { 4817 return null; 4818 } 4819 return pkgs.toArray(new String[pkgs.size()]); 4820 } 4821 } 4822 4823 @Override 4824 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4825 int flags, int userId) { 4826 try { 4827 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 4828 4829 if (!sUserManager.exists(userId)) return null; 4830 flags = updateFlagsForResolve(flags, userId, intent); 4831 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4832 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 4833 4834 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 4835 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 4836 flags, userId); 4837 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4838 4839 final ResolveInfo bestChoice = 4840 chooseBestActivity(intent, resolvedType, flags, query, userId); 4841 4842 if (isEphemeralAllowed(intent, query, userId)) { 4843 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 4844 final EphemeralResolveInfo ai = 4845 getEphemeralResolveInfo(intent, resolvedType, userId); 4846 if (ai != null) { 4847 if (DEBUG_EPHEMERAL) { 4848 Slog.v(TAG, "Returning an EphemeralResolveInfo"); 4849 } 4850 bestChoice.ephemeralInstaller = mEphemeralInstallerInfo; 4851 bestChoice.ephemeralResolveInfo = ai; 4852 } 4853 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4854 } 4855 return bestChoice; 4856 } finally { 4857 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4858 } 4859 } 4860 4861 @Override 4862 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4863 IntentFilter filter, int match, ComponentName activity) { 4864 final int userId = UserHandle.getCallingUserId(); 4865 if (DEBUG_PREFERRED) { 4866 Log.v(TAG, "setLastChosenActivity intent=" + intent 4867 + " resolvedType=" + resolvedType 4868 + " flags=" + flags 4869 + " filter=" + filter 4870 + " match=" + match 4871 + " activity=" + activity); 4872 filter.dump(new PrintStreamPrinter(System.out), " "); 4873 } 4874 intent.setComponent(null); 4875 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4876 userId); 4877 // Find any earlier preferred or last chosen entries and nuke them 4878 findPreferredActivity(intent, resolvedType, 4879 flags, query, 0, false, true, false, userId); 4880 // Add the new activity as the last chosen for this filter 4881 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4882 "Setting last chosen"); 4883 } 4884 4885 @Override 4886 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4887 final int userId = UserHandle.getCallingUserId(); 4888 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4889 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4890 userId); 4891 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4892 false, false, false, userId); 4893 } 4894 4895 4896 private boolean isEphemeralAllowed( 4897 Intent intent, List<ResolveInfo> resolvedActivites, int userId) { 4898 // Short circuit and return early if possible. 4899 if (DISABLE_EPHEMERAL_APPS) { 4900 return false; 4901 } 4902 final int callingUser = UserHandle.getCallingUserId(); 4903 if (callingUser != UserHandle.USER_SYSTEM) { 4904 return false; 4905 } 4906 if (mEphemeralResolverConnection == null) { 4907 return false; 4908 } 4909 if (intent.getComponent() != null) { 4910 return false; 4911 } 4912 if (intent.getPackage() != null) { 4913 return false; 4914 } 4915 final boolean isWebUri = hasWebURI(intent); 4916 if (!isWebUri) { 4917 return false; 4918 } 4919 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4920 synchronized (mPackages) { 4921 final int count = resolvedActivites.size(); 4922 for (int n = 0; n < count; n++) { 4923 ResolveInfo info = resolvedActivites.get(n); 4924 String packageName = info.activityInfo.packageName; 4925 PackageSetting ps = mSettings.mPackages.get(packageName); 4926 if (ps != null) { 4927 // Try to get the status from User settings first 4928 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4929 int status = (int) (packedStatus >> 32); 4930 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4931 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4932 if (DEBUG_EPHEMERAL) { 4933 Slog.v(TAG, "DENY ephemeral apps;" 4934 + " pkg: " + packageName + ", status: " + status); 4935 } 4936 return false; 4937 } 4938 } 4939 } 4940 } 4941 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4942 return true; 4943 } 4944 4945 private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType, 4946 int userId) { 4947 MessageDigest digest = null; 4948 try { 4949 digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM); 4950 } catch (NoSuchAlgorithmException e) { 4951 // If we can't create a digest, ignore ephemeral apps. 4952 return null; 4953 } 4954 4955 final byte[] hostBytes = intent.getData().getHost().getBytes(); 4956 final byte[] digestBytes = digest.digest(hostBytes); 4957 int shaPrefix = 4958 digestBytes[0] << 24 4959 | digestBytes[1] << 16 4960 | digestBytes[2] << 8 4961 | digestBytes[3] << 0; 4962 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4963 mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix); 4964 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4965 // No hash prefix match; there are no ephemeral apps for this domain. 4966 return null; 4967 } 4968 for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) { 4969 EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i); 4970 if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) { 4971 continue; 4972 } 4973 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 4974 // No filters; this should never happen. 4975 if (filters.isEmpty()) { 4976 continue; 4977 } 4978 // We have a domain match; resolve the filters to see if anything matches. 4979 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4980 for (int j = filters.size() - 1; j >= 0; --j) { 4981 final EphemeralResolveIntentInfo intentInfo = 4982 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 4983 ephemeralResolver.addFilter(intentInfo); 4984 } 4985 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 4986 intent, resolvedType, false /*defaultOnly*/, userId); 4987 if (!matchedResolveInfoList.isEmpty()) { 4988 return matchedResolveInfoList.get(0); 4989 } 4990 } 4991 // Hash or filter mis-match; no ephemeral apps for this domain. 4992 return null; 4993 } 4994 4995 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4996 int flags, List<ResolveInfo> query, int userId) { 4997 if (query != null) { 4998 final int N = query.size(); 4999 if (N == 1) { 5000 return query.get(0); 5001 } else if (N > 1) { 5002 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 5003 // If there is more than one activity with the same priority, 5004 // then let the user decide between them. 5005 ResolveInfo r0 = query.get(0); 5006 ResolveInfo r1 = query.get(1); 5007 if (DEBUG_INTENT_MATCHING || debug) { 5008 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 5009 + r1.activityInfo.name + "=" + r1.priority); 5010 } 5011 // If the first activity has a higher priority, or a different 5012 // default, then it is always desirable to pick it. 5013 if (r0.priority != r1.priority 5014 || r0.preferredOrder != r1.preferredOrder 5015 || r0.isDefault != r1.isDefault) { 5016 return query.get(0); 5017 } 5018 // If we have saved a preference for a preferred activity for 5019 // this Intent, use that. 5020 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 5021 flags, query, r0.priority, true, false, debug, userId); 5022 if (ri != null) { 5023 return ri; 5024 } 5025 ri = new ResolveInfo(mResolveInfo); 5026 ri.activityInfo = new ActivityInfo(ri.activityInfo); 5027 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 5028 ri.activityInfo.applicationInfo = new ApplicationInfo( 5029 ri.activityInfo.applicationInfo); 5030 if (userId != 0) { 5031 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 5032 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 5033 } 5034 // Make sure that the resolver is displayable in car mode 5035 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 5036 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 5037 return ri; 5038 } 5039 } 5040 return null; 5041 } 5042 5043 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 5044 int flags, List<ResolveInfo> query, boolean debug, int userId) { 5045 final int N = query.size(); 5046 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 5047 .get(userId); 5048 // Get the list of persistent preferred activities that handle the intent 5049 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 5050 List<PersistentPreferredActivity> pprefs = ppir != null 5051 ? ppir.queryIntent(intent, resolvedType, 5052 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5053 : null; 5054 if (pprefs != null && pprefs.size() > 0) { 5055 final int M = pprefs.size(); 5056 for (int i=0; i<M; i++) { 5057 final PersistentPreferredActivity ppa = pprefs.get(i); 5058 if (DEBUG_PREFERRED || debug) { 5059 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 5060 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 5061 + "\n component=" + ppa.mComponent); 5062 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5063 } 5064 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 5065 flags | MATCH_DISABLED_COMPONENTS, userId); 5066 if (DEBUG_PREFERRED || debug) { 5067 Slog.v(TAG, "Found persistent preferred activity:"); 5068 if (ai != null) { 5069 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5070 } else { 5071 Slog.v(TAG, " null"); 5072 } 5073 } 5074 if (ai == null) { 5075 // This previously registered persistent preferred activity 5076 // component is no longer known. Ignore it and do NOT remove it. 5077 continue; 5078 } 5079 for (int j=0; j<N; j++) { 5080 final ResolveInfo ri = query.get(j); 5081 if (!ri.activityInfo.applicationInfo.packageName 5082 .equals(ai.applicationInfo.packageName)) { 5083 continue; 5084 } 5085 if (!ri.activityInfo.name.equals(ai.name)) { 5086 continue; 5087 } 5088 // Found a persistent preference that can handle the intent. 5089 if (DEBUG_PREFERRED || debug) { 5090 Slog.v(TAG, "Returning persistent preferred activity: " + 5091 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5092 } 5093 return ri; 5094 } 5095 } 5096 } 5097 return null; 5098 } 5099 5100 // TODO: handle preferred activities missing while user has amnesia 5101 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5102 List<ResolveInfo> query, int priority, boolean always, 5103 boolean removeMatches, boolean debug, int userId) { 5104 if (!sUserManager.exists(userId)) return null; 5105 flags = updateFlagsForResolve(flags, userId, intent); 5106 // writer 5107 synchronized (mPackages) { 5108 if (intent.getSelector() != null) { 5109 intent = intent.getSelector(); 5110 } 5111 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 5112 5113 // Try to find a matching persistent preferred activity. 5114 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5115 debug, userId); 5116 5117 // If a persistent preferred activity matched, use it. 5118 if (pri != null) { 5119 return pri; 5120 } 5121 5122 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5123 // Get the list of preferred activities that handle the intent 5124 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5125 List<PreferredActivity> prefs = pir != null 5126 ? pir.queryIntent(intent, resolvedType, 5127 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5128 : null; 5129 if (prefs != null && prefs.size() > 0) { 5130 boolean changed = false; 5131 try { 5132 // First figure out how good the original match set is. 5133 // We will only allow preferred activities that came 5134 // from the same match quality. 5135 int match = 0; 5136 5137 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5138 5139 final int N = query.size(); 5140 for (int j=0; j<N; j++) { 5141 final ResolveInfo ri = query.get(j); 5142 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5143 + ": 0x" + Integer.toHexString(match)); 5144 if (ri.match > match) { 5145 match = ri.match; 5146 } 5147 } 5148 5149 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5150 + Integer.toHexString(match)); 5151 5152 match &= IntentFilter.MATCH_CATEGORY_MASK; 5153 final int M = prefs.size(); 5154 for (int i=0; i<M; i++) { 5155 final PreferredActivity pa = prefs.get(i); 5156 if (DEBUG_PREFERRED || debug) { 5157 Slog.v(TAG, "Checking PreferredActivity ds=" 5158 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5159 + "\n component=" + pa.mPref.mComponent); 5160 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5161 } 5162 if (pa.mPref.mMatch != match) { 5163 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5164 + Integer.toHexString(pa.mPref.mMatch)); 5165 continue; 5166 } 5167 // If it's not an "always" type preferred activity and that's what we're 5168 // looking for, skip it. 5169 if (always && !pa.mPref.mAlways) { 5170 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5171 continue; 5172 } 5173 final ActivityInfo ai = getActivityInfo( 5174 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5175 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5176 userId); 5177 if (DEBUG_PREFERRED || debug) { 5178 Slog.v(TAG, "Found preferred activity:"); 5179 if (ai != null) { 5180 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5181 } else { 5182 Slog.v(TAG, " null"); 5183 } 5184 } 5185 if (ai == null) { 5186 // This previously registered preferred activity 5187 // component is no longer known. Most likely an update 5188 // to the app was installed and in the new version this 5189 // component no longer exists. Clean it up by removing 5190 // it from the preferred activities list, and skip it. 5191 Slog.w(TAG, "Removing dangling preferred activity: " 5192 + pa.mPref.mComponent); 5193 pir.removeFilter(pa); 5194 changed = true; 5195 continue; 5196 } 5197 for (int j=0; j<N; j++) { 5198 final ResolveInfo ri = query.get(j); 5199 if (!ri.activityInfo.applicationInfo.packageName 5200 .equals(ai.applicationInfo.packageName)) { 5201 continue; 5202 } 5203 if (!ri.activityInfo.name.equals(ai.name)) { 5204 continue; 5205 } 5206 5207 if (removeMatches) { 5208 pir.removeFilter(pa); 5209 changed = true; 5210 if (DEBUG_PREFERRED) { 5211 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 5212 } 5213 break; 5214 } 5215 5216 // Okay we found a previously set preferred or last chosen app. 5217 // If the result set is different from when this 5218 // was created, we need to clear it and re-ask the 5219 // user their preference, if we're looking for an "always" type entry. 5220 if (always && !pa.mPref.sameSet(query)) { 5221 Slog.i(TAG, "Result set changed, dropping preferred activity for " 5222 + intent + " type " + resolvedType); 5223 if (DEBUG_PREFERRED) { 5224 Slog.v(TAG, "Removing preferred activity since set changed " 5225 + pa.mPref.mComponent); 5226 } 5227 pir.removeFilter(pa); 5228 // Re-add the filter as a "last chosen" entry (!always) 5229 PreferredActivity lastChosen = new PreferredActivity( 5230 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5231 pir.addFilter(lastChosen); 5232 changed = true; 5233 return null; 5234 } 5235 5236 // Yay! Either the set matched or we're looking for the last chosen 5237 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5238 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5239 return ri; 5240 } 5241 } 5242 } finally { 5243 if (changed) { 5244 if (DEBUG_PREFERRED) { 5245 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5246 } 5247 scheduleWritePackageRestrictionsLocked(userId); 5248 } 5249 } 5250 } 5251 } 5252 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5253 return null; 5254 } 5255 5256 /* 5257 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5258 */ 5259 @Override 5260 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5261 int targetUserId) { 5262 mContext.enforceCallingOrSelfPermission( 5263 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5264 List<CrossProfileIntentFilter> matches = 5265 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5266 if (matches != null) { 5267 int size = matches.size(); 5268 for (int i = 0; i < size; i++) { 5269 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5270 } 5271 } 5272 if (hasWebURI(intent)) { 5273 // cross-profile app linking works only towards the parent. 5274 final UserInfo parent = getProfileParent(sourceUserId); 5275 synchronized(mPackages) { 5276 int flags = updateFlagsForResolve(0, parent.id, intent); 5277 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5278 intent, resolvedType, flags, sourceUserId, parent.id); 5279 return xpDomainInfo != null; 5280 } 5281 } 5282 return false; 5283 } 5284 5285 private UserInfo getProfileParent(int userId) { 5286 final long identity = Binder.clearCallingIdentity(); 5287 try { 5288 return sUserManager.getProfileParent(userId); 5289 } finally { 5290 Binder.restoreCallingIdentity(identity); 5291 } 5292 } 5293 5294 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5295 String resolvedType, int userId) { 5296 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5297 if (resolver != null) { 5298 return resolver.queryIntent(intent, resolvedType, false, userId); 5299 } 5300 return null; 5301 } 5302 5303 @Override 5304 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5305 String resolvedType, int flags, int userId) { 5306 try { 5307 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5308 5309 return new ParceledListSlice<>( 5310 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5311 } finally { 5312 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5313 } 5314 } 5315 5316 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5317 String resolvedType, int flags, int userId) { 5318 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5319 flags = updateFlagsForResolve(flags, userId, intent); 5320 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5321 false /* requireFullPermission */, false /* checkShell */, 5322 "query intent activities"); 5323 ComponentName comp = intent.getComponent(); 5324 if (comp == null) { 5325 if (intent.getSelector() != null) { 5326 intent = intent.getSelector(); 5327 comp = intent.getComponent(); 5328 } 5329 } 5330 5331 if (comp != null) { 5332 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5333 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5334 if (ai != null) { 5335 final ResolveInfo ri = new ResolveInfo(); 5336 ri.activityInfo = ai; 5337 list.add(ri); 5338 } 5339 return list; 5340 } 5341 5342 // reader 5343 synchronized (mPackages) { 5344 final String pkgName = intent.getPackage(); 5345 if (pkgName == null) { 5346 List<CrossProfileIntentFilter> matchingFilters = 5347 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5348 // Check for results that need to skip the current profile. 5349 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5350 resolvedType, flags, userId); 5351 if (xpResolveInfo != null) { 5352 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 5353 result.add(xpResolveInfo); 5354 return filterIfNotSystemUser(result, userId); 5355 } 5356 5357 // Check for results in the current profile. 5358 List<ResolveInfo> result = mActivities.queryIntent( 5359 intent, resolvedType, flags, userId); 5360 result = filterIfNotSystemUser(result, userId); 5361 5362 // Check for cross profile results. 5363 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5364 xpResolveInfo = queryCrossProfileIntents( 5365 matchingFilters, intent, resolvedType, flags, userId, 5366 hasNonNegativePriorityResult); 5367 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5368 boolean isVisibleToUser = filterIfNotSystemUser( 5369 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5370 if (isVisibleToUser) { 5371 result.add(xpResolveInfo); 5372 Collections.sort(result, mResolvePrioritySorter); 5373 } 5374 } 5375 if (hasWebURI(intent)) { 5376 CrossProfileDomainInfo xpDomainInfo = null; 5377 final UserInfo parent = getProfileParent(userId); 5378 if (parent != null) { 5379 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5380 flags, userId, parent.id); 5381 } 5382 if (xpDomainInfo != null) { 5383 if (xpResolveInfo != null) { 5384 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5385 // in the result. 5386 result.remove(xpResolveInfo); 5387 } 5388 if (result.size() == 0) { 5389 result.add(xpDomainInfo.resolveInfo); 5390 return result; 5391 } 5392 } else if (result.size() <= 1) { 5393 return result; 5394 } 5395 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 5396 xpDomainInfo, userId); 5397 Collections.sort(result, mResolvePrioritySorter); 5398 } 5399 return result; 5400 } 5401 final PackageParser.Package pkg = mPackages.get(pkgName); 5402 if (pkg != null) { 5403 return filterIfNotSystemUser( 5404 mActivities.queryIntentForPackage( 5405 intent, resolvedType, flags, pkg.activities, userId), 5406 userId); 5407 } 5408 return new ArrayList<ResolveInfo>(); 5409 } 5410 } 5411 5412 private static class CrossProfileDomainInfo { 5413 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5414 ResolveInfo resolveInfo; 5415 /* Best domain verification status of the activities found in the other profile */ 5416 int bestDomainVerificationStatus; 5417 } 5418 5419 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5420 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5421 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5422 sourceUserId)) { 5423 return null; 5424 } 5425 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5426 resolvedType, flags, parentUserId); 5427 5428 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5429 return null; 5430 } 5431 CrossProfileDomainInfo result = null; 5432 int size = resultTargetUser.size(); 5433 for (int i = 0; i < size; i++) { 5434 ResolveInfo riTargetUser = resultTargetUser.get(i); 5435 // Intent filter verification is only for filters that specify a host. So don't return 5436 // those that handle all web uris. 5437 if (riTargetUser.handleAllWebDataURI) { 5438 continue; 5439 } 5440 String packageName = riTargetUser.activityInfo.packageName; 5441 PackageSetting ps = mSettings.mPackages.get(packageName); 5442 if (ps == null) { 5443 continue; 5444 } 5445 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5446 int status = (int)(verificationState >> 32); 5447 if (result == null) { 5448 result = new CrossProfileDomainInfo(); 5449 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5450 sourceUserId, parentUserId); 5451 result.bestDomainVerificationStatus = status; 5452 } else { 5453 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5454 result.bestDomainVerificationStatus); 5455 } 5456 } 5457 // Don't consider matches with status NEVER across profiles. 5458 if (result != null && result.bestDomainVerificationStatus 5459 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5460 return null; 5461 } 5462 return result; 5463 } 5464 5465 /** 5466 * Verification statuses are ordered from the worse to the best, except for 5467 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5468 */ 5469 private int bestDomainVerificationStatus(int status1, int status2) { 5470 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5471 return status2; 5472 } 5473 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5474 return status1; 5475 } 5476 return (int) MathUtils.max(status1, status2); 5477 } 5478 5479 private boolean isUserEnabled(int userId) { 5480 long callingId = Binder.clearCallingIdentity(); 5481 try { 5482 UserInfo userInfo = sUserManager.getUserInfo(userId); 5483 return userInfo != null && userInfo.isEnabled(); 5484 } finally { 5485 Binder.restoreCallingIdentity(callingId); 5486 } 5487 } 5488 5489 /** 5490 * Filter out activities with systemUserOnly flag set, when current user is not System. 5491 * 5492 * @return filtered list 5493 */ 5494 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5495 if (userId == UserHandle.USER_SYSTEM) { 5496 return resolveInfos; 5497 } 5498 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5499 ResolveInfo info = resolveInfos.get(i); 5500 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5501 resolveInfos.remove(i); 5502 } 5503 } 5504 return resolveInfos; 5505 } 5506 5507 /** 5508 * @param resolveInfos list of resolve infos in descending priority order 5509 * @return if the list contains a resolve info with non-negative priority 5510 */ 5511 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5512 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5513 } 5514 5515 private static boolean hasWebURI(Intent intent) { 5516 if (intent.getData() == null) { 5517 return false; 5518 } 5519 final String scheme = intent.getScheme(); 5520 if (TextUtils.isEmpty(scheme)) { 5521 return false; 5522 } 5523 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5524 } 5525 5526 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5527 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5528 int userId) { 5529 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5530 5531 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5532 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5533 candidates.size()); 5534 } 5535 5536 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5537 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5538 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5539 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5540 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5541 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5542 5543 synchronized (mPackages) { 5544 final int count = candidates.size(); 5545 // First, try to use linked apps. Partition the candidates into four lists: 5546 // one for the final results, one for the "do not use ever", one for "undefined status" 5547 // and finally one for "browser app type". 5548 for (int n=0; n<count; n++) { 5549 ResolveInfo info = candidates.get(n); 5550 String packageName = info.activityInfo.packageName; 5551 PackageSetting ps = mSettings.mPackages.get(packageName); 5552 if (ps != null) { 5553 // Add to the special match all list (Browser use case) 5554 if (info.handleAllWebDataURI) { 5555 matchAllList.add(info); 5556 continue; 5557 } 5558 // Try to get the status from User settings first 5559 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5560 int status = (int)(packedStatus >> 32); 5561 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5562 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5563 if (DEBUG_DOMAIN_VERIFICATION) { 5564 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5565 + " : linkgen=" + linkGeneration); 5566 } 5567 // Use link-enabled generation as preferredOrder, i.e. 5568 // prefer newly-enabled over earlier-enabled. 5569 info.preferredOrder = linkGeneration; 5570 alwaysList.add(info); 5571 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5572 if (DEBUG_DOMAIN_VERIFICATION) { 5573 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5574 } 5575 neverList.add(info); 5576 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5577 if (DEBUG_DOMAIN_VERIFICATION) { 5578 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5579 } 5580 alwaysAskList.add(info); 5581 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5582 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5583 if (DEBUG_DOMAIN_VERIFICATION) { 5584 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5585 } 5586 undefinedList.add(info); 5587 } 5588 } 5589 } 5590 5591 // We'll want to include browser possibilities in a few cases 5592 boolean includeBrowser = false; 5593 5594 // First try to add the "always" resolution(s) for the current user, if any 5595 if (alwaysList.size() > 0) { 5596 result.addAll(alwaysList); 5597 } else { 5598 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5599 result.addAll(undefinedList); 5600 // Maybe add one for the other profile. 5601 if (xpDomainInfo != null && ( 5602 xpDomainInfo.bestDomainVerificationStatus 5603 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5604 result.add(xpDomainInfo.resolveInfo); 5605 } 5606 includeBrowser = true; 5607 } 5608 5609 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5610 // If there were 'always' entries their preferred order has been set, so we also 5611 // back that off to make the alternatives equivalent 5612 if (alwaysAskList.size() > 0) { 5613 for (ResolveInfo i : result) { 5614 i.preferredOrder = 0; 5615 } 5616 result.addAll(alwaysAskList); 5617 includeBrowser = true; 5618 } 5619 5620 if (includeBrowser) { 5621 // Also add browsers (all of them or only the default one) 5622 if (DEBUG_DOMAIN_VERIFICATION) { 5623 Slog.v(TAG, " ...including browsers in candidate set"); 5624 } 5625 if ((matchFlags & MATCH_ALL) != 0) { 5626 result.addAll(matchAllList); 5627 } else { 5628 // Browser/generic handling case. If there's a default browser, go straight 5629 // to that (but only if there is no other higher-priority match). 5630 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5631 int maxMatchPrio = 0; 5632 ResolveInfo defaultBrowserMatch = null; 5633 final int numCandidates = matchAllList.size(); 5634 for (int n = 0; n < numCandidates; n++) { 5635 ResolveInfo info = matchAllList.get(n); 5636 // track the highest overall match priority... 5637 if (info.priority > maxMatchPrio) { 5638 maxMatchPrio = info.priority; 5639 } 5640 // ...and the highest-priority default browser match 5641 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5642 if (defaultBrowserMatch == null 5643 || (defaultBrowserMatch.priority < info.priority)) { 5644 if (debug) { 5645 Slog.v(TAG, "Considering default browser match " + info); 5646 } 5647 defaultBrowserMatch = info; 5648 } 5649 } 5650 } 5651 if (defaultBrowserMatch != null 5652 && defaultBrowserMatch.priority >= maxMatchPrio 5653 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5654 { 5655 if (debug) { 5656 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5657 } 5658 result.add(defaultBrowserMatch); 5659 } else { 5660 result.addAll(matchAllList); 5661 } 5662 } 5663 5664 // If there is nothing selected, add all candidates and remove the ones that the user 5665 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5666 if (result.size() == 0) { 5667 result.addAll(candidates); 5668 result.removeAll(neverList); 5669 } 5670 } 5671 } 5672 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5673 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5674 result.size()); 5675 for (ResolveInfo info : result) { 5676 Slog.v(TAG, " + " + info.activityInfo); 5677 } 5678 } 5679 return result; 5680 } 5681 5682 // Returns a packed value as a long: 5683 // 5684 // high 'int'-sized word: link status: undefined/ask/never/always. 5685 // low 'int'-sized word: relative priority among 'always' results. 5686 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5687 long result = ps.getDomainVerificationStatusForUser(userId); 5688 // if none available, get the master status 5689 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5690 if (ps.getIntentFilterVerificationInfo() != null) { 5691 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5692 } 5693 } 5694 return result; 5695 } 5696 5697 private ResolveInfo querySkipCurrentProfileIntents( 5698 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5699 int flags, int sourceUserId) { 5700 if (matchingFilters != null) { 5701 int size = matchingFilters.size(); 5702 for (int i = 0; i < size; i ++) { 5703 CrossProfileIntentFilter filter = matchingFilters.get(i); 5704 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5705 // Checking if there are activities in the target user that can handle the 5706 // intent. 5707 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5708 resolvedType, flags, sourceUserId); 5709 if (resolveInfo != null) { 5710 return resolveInfo; 5711 } 5712 } 5713 } 5714 } 5715 return null; 5716 } 5717 5718 // Return matching ResolveInfo in target user if any. 5719 private ResolveInfo queryCrossProfileIntents( 5720 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5721 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5722 if (matchingFilters != null) { 5723 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5724 // match the same intent. For performance reasons, it is better not to 5725 // run queryIntent twice for the same userId 5726 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5727 int size = matchingFilters.size(); 5728 for (int i = 0; i < size; i++) { 5729 CrossProfileIntentFilter filter = matchingFilters.get(i); 5730 int targetUserId = filter.getTargetUserId(); 5731 boolean skipCurrentProfile = 5732 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5733 boolean skipCurrentProfileIfNoMatchFound = 5734 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5735 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5736 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5737 // Checking if there are activities in the target user that can handle the 5738 // intent. 5739 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5740 resolvedType, flags, sourceUserId); 5741 if (resolveInfo != null) return resolveInfo; 5742 alreadyTriedUserIds.put(targetUserId, true); 5743 } 5744 } 5745 } 5746 return null; 5747 } 5748 5749 /** 5750 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5751 * will forward the intent to the filter's target user. 5752 * Otherwise, returns null. 5753 */ 5754 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5755 String resolvedType, int flags, int sourceUserId) { 5756 int targetUserId = filter.getTargetUserId(); 5757 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5758 resolvedType, flags, targetUserId); 5759 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5760 // If all the matches in the target profile are suspended, return null. 5761 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5762 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5763 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5764 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5765 targetUserId); 5766 } 5767 } 5768 } 5769 return null; 5770 } 5771 5772 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5773 int sourceUserId, int targetUserId) { 5774 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5775 long ident = Binder.clearCallingIdentity(); 5776 boolean targetIsProfile; 5777 try { 5778 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5779 } finally { 5780 Binder.restoreCallingIdentity(ident); 5781 } 5782 String className; 5783 if (targetIsProfile) { 5784 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5785 } else { 5786 className = FORWARD_INTENT_TO_PARENT; 5787 } 5788 ComponentName forwardingActivityComponentName = new ComponentName( 5789 mAndroidApplication.packageName, className); 5790 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5791 sourceUserId); 5792 if (!targetIsProfile) { 5793 forwardingActivityInfo.showUserIcon = targetUserId; 5794 forwardingResolveInfo.noResourceId = true; 5795 } 5796 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5797 forwardingResolveInfo.priority = 0; 5798 forwardingResolveInfo.preferredOrder = 0; 5799 forwardingResolveInfo.match = 0; 5800 forwardingResolveInfo.isDefault = true; 5801 forwardingResolveInfo.filter = filter; 5802 forwardingResolveInfo.targetUserId = targetUserId; 5803 return forwardingResolveInfo; 5804 } 5805 5806 @Override 5807 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5808 Intent[] specifics, String[] specificTypes, Intent intent, 5809 String resolvedType, int flags, int userId) { 5810 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 5811 specificTypes, intent, resolvedType, flags, userId)); 5812 } 5813 5814 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 5815 Intent[] specifics, String[] specificTypes, Intent intent, 5816 String resolvedType, int flags, int userId) { 5817 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5818 flags = updateFlagsForResolve(flags, userId, intent); 5819 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5820 false /* requireFullPermission */, false /* checkShell */, 5821 "query intent activity options"); 5822 final String resultsAction = intent.getAction(); 5823 5824 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 5825 | PackageManager.GET_RESOLVED_FILTER, userId); 5826 5827 if (DEBUG_INTENT_MATCHING) { 5828 Log.v(TAG, "Query " + intent + ": " + results); 5829 } 5830 5831 int specificsPos = 0; 5832 int N; 5833 5834 // todo: note that the algorithm used here is O(N^2). This 5835 // isn't a problem in our current environment, but if we start running 5836 // into situations where we have more than 5 or 10 matches then this 5837 // should probably be changed to something smarter... 5838 5839 // First we go through and resolve each of the specific items 5840 // that were supplied, taking care of removing any corresponding 5841 // duplicate items in the generic resolve list. 5842 if (specifics != null) { 5843 for (int i=0; i<specifics.length; i++) { 5844 final Intent sintent = specifics[i]; 5845 if (sintent == null) { 5846 continue; 5847 } 5848 5849 if (DEBUG_INTENT_MATCHING) { 5850 Log.v(TAG, "Specific #" + i + ": " + sintent); 5851 } 5852 5853 String action = sintent.getAction(); 5854 if (resultsAction != null && resultsAction.equals(action)) { 5855 // If this action was explicitly requested, then don't 5856 // remove things that have it. 5857 action = null; 5858 } 5859 5860 ResolveInfo ri = null; 5861 ActivityInfo ai = null; 5862 5863 ComponentName comp = sintent.getComponent(); 5864 if (comp == null) { 5865 ri = resolveIntent( 5866 sintent, 5867 specificTypes != null ? specificTypes[i] : null, 5868 flags, userId); 5869 if (ri == null) { 5870 continue; 5871 } 5872 if (ri == mResolveInfo) { 5873 // ACK! Must do something better with this. 5874 } 5875 ai = ri.activityInfo; 5876 comp = new ComponentName(ai.applicationInfo.packageName, 5877 ai.name); 5878 } else { 5879 ai = getActivityInfo(comp, flags, userId); 5880 if (ai == null) { 5881 continue; 5882 } 5883 } 5884 5885 // Look for any generic query activities that are duplicates 5886 // of this specific one, and remove them from the results. 5887 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5888 N = results.size(); 5889 int j; 5890 for (j=specificsPos; j<N; j++) { 5891 ResolveInfo sri = results.get(j); 5892 if ((sri.activityInfo.name.equals(comp.getClassName()) 5893 && sri.activityInfo.applicationInfo.packageName.equals( 5894 comp.getPackageName())) 5895 || (action != null && sri.filter.matchAction(action))) { 5896 results.remove(j); 5897 if (DEBUG_INTENT_MATCHING) Log.v( 5898 TAG, "Removing duplicate item from " + j 5899 + " due to specific " + specificsPos); 5900 if (ri == null) { 5901 ri = sri; 5902 } 5903 j--; 5904 N--; 5905 } 5906 } 5907 5908 // Add this specific item to its proper place. 5909 if (ri == null) { 5910 ri = new ResolveInfo(); 5911 ri.activityInfo = ai; 5912 } 5913 results.add(specificsPos, ri); 5914 ri.specificIndex = i; 5915 specificsPos++; 5916 } 5917 } 5918 5919 // Now we go through the remaining generic results and remove any 5920 // duplicate actions that are found here. 5921 N = results.size(); 5922 for (int i=specificsPos; i<N-1; i++) { 5923 final ResolveInfo rii = results.get(i); 5924 if (rii.filter == null) { 5925 continue; 5926 } 5927 5928 // Iterate over all of the actions of this result's intent 5929 // filter... typically this should be just one. 5930 final Iterator<String> it = rii.filter.actionsIterator(); 5931 if (it == null) { 5932 continue; 5933 } 5934 while (it.hasNext()) { 5935 final String action = it.next(); 5936 if (resultsAction != null && resultsAction.equals(action)) { 5937 // If this action was explicitly requested, then don't 5938 // remove things that have it. 5939 continue; 5940 } 5941 for (int j=i+1; j<N; j++) { 5942 final ResolveInfo rij = results.get(j); 5943 if (rij.filter != null && rij.filter.hasAction(action)) { 5944 results.remove(j); 5945 if (DEBUG_INTENT_MATCHING) Log.v( 5946 TAG, "Removing duplicate item from " + j 5947 + " due to action " + action + " at " + i); 5948 j--; 5949 N--; 5950 } 5951 } 5952 } 5953 5954 // If the caller didn't request filter information, drop it now 5955 // so we don't have to marshall/unmarshall it. 5956 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5957 rii.filter = null; 5958 } 5959 } 5960 5961 // Filter out the caller activity if so requested. 5962 if (caller != null) { 5963 N = results.size(); 5964 for (int i=0; i<N; i++) { 5965 ActivityInfo ainfo = results.get(i).activityInfo; 5966 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5967 && caller.getClassName().equals(ainfo.name)) { 5968 results.remove(i); 5969 break; 5970 } 5971 } 5972 } 5973 5974 // If the caller didn't request filter information, 5975 // drop them now so we don't have to 5976 // marshall/unmarshall it. 5977 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5978 N = results.size(); 5979 for (int i=0; i<N; i++) { 5980 results.get(i).filter = null; 5981 } 5982 } 5983 5984 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5985 return results; 5986 } 5987 5988 @Override 5989 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 5990 String resolvedType, int flags, int userId) { 5991 return new ParceledListSlice<>( 5992 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 5993 } 5994 5995 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 5996 String resolvedType, int flags, int userId) { 5997 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5998 flags = updateFlagsForResolve(flags, userId, intent); 5999 ComponentName comp = intent.getComponent(); 6000 if (comp == null) { 6001 if (intent.getSelector() != null) { 6002 intent = intent.getSelector(); 6003 comp = intent.getComponent(); 6004 } 6005 } 6006 if (comp != null) { 6007 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6008 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 6009 if (ai != null) { 6010 ResolveInfo ri = new ResolveInfo(); 6011 ri.activityInfo = ai; 6012 list.add(ri); 6013 } 6014 return list; 6015 } 6016 6017 // reader 6018 synchronized (mPackages) { 6019 String pkgName = intent.getPackage(); 6020 if (pkgName == null) { 6021 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 6022 } 6023 final PackageParser.Package pkg = mPackages.get(pkgName); 6024 if (pkg != null) { 6025 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 6026 userId); 6027 } 6028 return Collections.emptyList(); 6029 } 6030 } 6031 6032 @Override 6033 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 6034 if (!sUserManager.exists(userId)) return null; 6035 flags = updateFlagsForResolve(flags, userId, intent); 6036 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 6037 if (query != null) { 6038 if (query.size() >= 1) { 6039 // If there is more than one service with the same priority, 6040 // just arbitrarily pick the first one. 6041 return query.get(0); 6042 } 6043 } 6044 return null; 6045 } 6046 6047 @Override 6048 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 6049 String resolvedType, int flags, int userId) { 6050 return new ParceledListSlice<>( 6051 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 6052 } 6053 6054 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 6055 String resolvedType, int flags, int userId) { 6056 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6057 flags = updateFlagsForResolve(flags, userId, intent); 6058 ComponentName comp = intent.getComponent(); 6059 if (comp == null) { 6060 if (intent.getSelector() != null) { 6061 intent = intent.getSelector(); 6062 comp = intent.getComponent(); 6063 } 6064 } 6065 if (comp != null) { 6066 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6067 final ServiceInfo si = getServiceInfo(comp, flags, userId); 6068 if (si != null) { 6069 final ResolveInfo ri = new ResolveInfo(); 6070 ri.serviceInfo = si; 6071 list.add(ri); 6072 } 6073 return list; 6074 } 6075 6076 // reader 6077 synchronized (mPackages) { 6078 String pkgName = intent.getPackage(); 6079 if (pkgName == null) { 6080 return mServices.queryIntent(intent, resolvedType, flags, userId); 6081 } 6082 final PackageParser.Package pkg = mPackages.get(pkgName); 6083 if (pkg != null) { 6084 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 6085 userId); 6086 } 6087 return Collections.emptyList(); 6088 } 6089 } 6090 6091 @Override 6092 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 6093 String resolvedType, int flags, int userId) { 6094 return new ParceledListSlice<>( 6095 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 6096 } 6097 6098 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 6099 Intent intent, String resolvedType, int flags, int userId) { 6100 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6101 flags = updateFlagsForResolve(flags, userId, intent); 6102 ComponentName comp = intent.getComponent(); 6103 if (comp == null) { 6104 if (intent.getSelector() != null) { 6105 intent = intent.getSelector(); 6106 comp = intent.getComponent(); 6107 } 6108 } 6109 if (comp != null) { 6110 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6111 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 6112 if (pi != null) { 6113 final ResolveInfo ri = new ResolveInfo(); 6114 ri.providerInfo = pi; 6115 list.add(ri); 6116 } 6117 return list; 6118 } 6119 6120 // reader 6121 synchronized (mPackages) { 6122 String pkgName = intent.getPackage(); 6123 if (pkgName == null) { 6124 return mProviders.queryIntent(intent, resolvedType, flags, userId); 6125 } 6126 final PackageParser.Package pkg = mPackages.get(pkgName); 6127 if (pkg != null) { 6128 return mProviders.queryIntentForPackage( 6129 intent, resolvedType, flags, pkg.providers, userId); 6130 } 6131 return Collections.emptyList(); 6132 } 6133 } 6134 6135 @Override 6136 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 6137 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6138 flags = updateFlagsForPackage(flags, userId, null); 6139 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6140 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6141 true /* requireFullPermission */, false /* checkShell */, 6142 "get installed packages"); 6143 6144 // writer 6145 synchronized (mPackages) { 6146 ArrayList<PackageInfo> list; 6147 if (listUninstalled) { 6148 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 6149 for (PackageSetting ps : mSettings.mPackages.values()) { 6150 final PackageInfo pi; 6151 if (ps.pkg != null) { 6152 pi = generatePackageInfo(ps, flags, userId); 6153 } else { 6154 pi = generatePackageInfo(ps, flags, userId); 6155 } 6156 if (pi != null) { 6157 list.add(pi); 6158 } 6159 } 6160 } else { 6161 list = new ArrayList<PackageInfo>(mPackages.size()); 6162 for (PackageParser.Package p : mPackages.values()) { 6163 final PackageInfo pi = 6164 generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 6165 if (pi != null) { 6166 list.add(pi); 6167 } 6168 } 6169 } 6170 6171 return new ParceledListSlice<PackageInfo>(list); 6172 } 6173 } 6174 6175 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 6176 String[] permissions, boolean[] tmp, int flags, int userId) { 6177 int numMatch = 0; 6178 final PermissionsState permissionsState = ps.getPermissionsState(); 6179 for (int i=0; i<permissions.length; i++) { 6180 final String permission = permissions[i]; 6181 if (permissionsState.hasPermission(permission, userId)) { 6182 tmp[i] = true; 6183 numMatch++; 6184 } else { 6185 tmp[i] = false; 6186 } 6187 } 6188 if (numMatch == 0) { 6189 return; 6190 } 6191 final PackageInfo pi; 6192 if (ps.pkg != null) { 6193 pi = generatePackageInfo(ps, flags, userId); 6194 } else { 6195 pi = generatePackageInfo(ps, flags, userId); 6196 } 6197 // The above might return null in cases of uninstalled apps or install-state 6198 // skew across users/profiles. 6199 if (pi != null) { 6200 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 6201 if (numMatch == permissions.length) { 6202 pi.requestedPermissions = permissions; 6203 } else { 6204 pi.requestedPermissions = new String[numMatch]; 6205 numMatch = 0; 6206 for (int i=0; i<permissions.length; i++) { 6207 if (tmp[i]) { 6208 pi.requestedPermissions[numMatch] = permissions[i]; 6209 numMatch++; 6210 } 6211 } 6212 } 6213 } 6214 list.add(pi); 6215 } 6216 } 6217 6218 @Override 6219 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 6220 String[] permissions, int flags, int userId) { 6221 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6222 flags = updateFlagsForPackage(flags, userId, permissions); 6223 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6224 6225 // writer 6226 synchronized (mPackages) { 6227 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 6228 boolean[] tmpBools = new boolean[permissions.length]; 6229 if (listUninstalled) { 6230 for (PackageSetting ps : mSettings.mPackages.values()) { 6231 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 6232 } 6233 } else { 6234 for (PackageParser.Package pkg : mPackages.values()) { 6235 PackageSetting ps = (PackageSetting)pkg.mExtras; 6236 if (ps != null) { 6237 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6238 userId); 6239 } 6240 } 6241 } 6242 6243 return new ParceledListSlice<PackageInfo>(list); 6244 } 6245 } 6246 6247 @Override 6248 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 6249 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6250 flags = updateFlagsForApplication(flags, userId, null); 6251 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6252 6253 // writer 6254 synchronized (mPackages) { 6255 ArrayList<ApplicationInfo> list; 6256 if (listUninstalled) { 6257 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 6258 for (PackageSetting ps : mSettings.mPackages.values()) { 6259 ApplicationInfo ai; 6260 if (ps.pkg != null) { 6261 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 6262 ps.readUserState(userId), userId); 6263 } else { 6264 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 6265 } 6266 if (ai != null) { 6267 list.add(ai); 6268 } 6269 } 6270 } else { 6271 list = new ArrayList<ApplicationInfo>(mPackages.size()); 6272 for (PackageParser.Package p : mPackages.values()) { 6273 if (p.mExtras != null) { 6274 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6275 ((PackageSetting)p.mExtras).readUserState(userId), userId); 6276 if (ai != null) { 6277 list.add(ai); 6278 } 6279 } 6280 } 6281 } 6282 6283 return new ParceledListSlice<ApplicationInfo>(list); 6284 } 6285 } 6286 6287 @Override 6288 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 6289 if (DISABLE_EPHEMERAL_APPS) { 6290 return null; 6291 } 6292 6293 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6294 "getEphemeralApplications"); 6295 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6296 true /* requireFullPermission */, false /* checkShell */, 6297 "getEphemeralApplications"); 6298 synchronized (mPackages) { 6299 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 6300 .getEphemeralApplicationsLPw(userId); 6301 if (ephemeralApps != null) { 6302 return new ParceledListSlice<>(ephemeralApps); 6303 } 6304 } 6305 return null; 6306 } 6307 6308 @Override 6309 public boolean isEphemeralApplication(String packageName, int userId) { 6310 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6311 true /* requireFullPermission */, false /* checkShell */, 6312 "isEphemeral"); 6313 if (DISABLE_EPHEMERAL_APPS) { 6314 return false; 6315 } 6316 6317 if (!isCallerSameApp(packageName)) { 6318 return false; 6319 } 6320 synchronized (mPackages) { 6321 PackageParser.Package pkg = mPackages.get(packageName); 6322 if (pkg != null) { 6323 return pkg.applicationInfo.isEphemeralApp(); 6324 } 6325 } 6326 return false; 6327 } 6328 6329 @Override 6330 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6331 if (DISABLE_EPHEMERAL_APPS) { 6332 return null; 6333 } 6334 6335 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6336 true /* requireFullPermission */, false /* checkShell */, 6337 "getCookie"); 6338 if (!isCallerSameApp(packageName)) { 6339 return null; 6340 } 6341 synchronized (mPackages) { 6342 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6343 packageName, userId); 6344 } 6345 } 6346 6347 @Override 6348 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6349 if (DISABLE_EPHEMERAL_APPS) { 6350 return true; 6351 } 6352 6353 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6354 true /* requireFullPermission */, true /* checkShell */, 6355 "setCookie"); 6356 if (!isCallerSameApp(packageName)) { 6357 return false; 6358 } 6359 synchronized (mPackages) { 6360 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6361 packageName, cookie, userId); 6362 } 6363 } 6364 6365 @Override 6366 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6367 if (DISABLE_EPHEMERAL_APPS) { 6368 return null; 6369 } 6370 6371 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6372 "getEphemeralApplicationIcon"); 6373 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6374 true /* requireFullPermission */, false /* checkShell */, 6375 "getEphemeralApplicationIcon"); 6376 synchronized (mPackages) { 6377 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6378 packageName, userId); 6379 } 6380 } 6381 6382 private boolean isCallerSameApp(String packageName) { 6383 PackageParser.Package pkg = mPackages.get(packageName); 6384 return pkg != null 6385 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6386 } 6387 6388 @Override 6389 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 6390 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 6391 } 6392 6393 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 6394 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6395 6396 // reader 6397 synchronized (mPackages) { 6398 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6399 final int userId = UserHandle.getCallingUserId(); 6400 while (i.hasNext()) { 6401 final PackageParser.Package p = i.next(); 6402 if (p.applicationInfo == null) continue; 6403 6404 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 6405 && !p.applicationInfo.isDirectBootAware(); 6406 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 6407 && p.applicationInfo.isDirectBootAware(); 6408 6409 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6410 && (!mSafeMode || isSystemApp(p)) 6411 && (matchesUnaware || matchesAware)) { 6412 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6413 if (ps != null) { 6414 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6415 ps.readUserState(userId), userId); 6416 if (ai != null) { 6417 finalList.add(ai); 6418 } 6419 } 6420 } 6421 } 6422 } 6423 6424 return finalList; 6425 } 6426 6427 @Override 6428 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6429 if (!sUserManager.exists(userId)) return null; 6430 flags = updateFlagsForComponent(flags, userId, name); 6431 // reader 6432 synchronized (mPackages) { 6433 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6434 PackageSetting ps = provider != null 6435 ? mSettings.mPackages.get(provider.owner.packageName) 6436 : null; 6437 return ps != null 6438 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6439 ? PackageParser.generateProviderInfo(provider, flags, 6440 ps.readUserState(userId), userId) 6441 : null; 6442 } 6443 } 6444 6445 /** 6446 * @deprecated 6447 */ 6448 @Deprecated 6449 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6450 // reader 6451 synchronized (mPackages) { 6452 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6453 .entrySet().iterator(); 6454 final int userId = UserHandle.getCallingUserId(); 6455 while (i.hasNext()) { 6456 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6457 PackageParser.Provider p = entry.getValue(); 6458 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6459 6460 if (ps != null && p.syncable 6461 && (!mSafeMode || (p.info.applicationInfo.flags 6462 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6463 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6464 ps.readUserState(userId), userId); 6465 if (info != null) { 6466 outNames.add(entry.getKey()); 6467 outInfo.add(info); 6468 } 6469 } 6470 } 6471 } 6472 } 6473 6474 @Override 6475 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6476 int uid, int flags) { 6477 final int userId = processName != null ? UserHandle.getUserId(uid) 6478 : UserHandle.getCallingUserId(); 6479 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6480 flags = updateFlagsForComponent(flags, userId, processName); 6481 6482 ArrayList<ProviderInfo> finalList = null; 6483 // reader 6484 synchronized (mPackages) { 6485 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6486 while (i.hasNext()) { 6487 final PackageParser.Provider p = i.next(); 6488 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6489 if (ps != null && p.info.authority != null 6490 && (processName == null 6491 || (p.info.processName.equals(processName) 6492 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6493 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6494 if (finalList == null) { 6495 finalList = new ArrayList<ProviderInfo>(3); 6496 } 6497 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6498 ps.readUserState(userId), userId); 6499 if (info != null) { 6500 finalList.add(info); 6501 } 6502 } 6503 } 6504 } 6505 6506 if (finalList != null) { 6507 Collections.sort(finalList, mProviderInitOrderSorter); 6508 return new ParceledListSlice<ProviderInfo>(finalList); 6509 } 6510 6511 return ParceledListSlice.emptyList(); 6512 } 6513 6514 @Override 6515 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6516 // reader 6517 synchronized (mPackages) { 6518 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6519 return PackageParser.generateInstrumentationInfo(i, flags); 6520 } 6521 } 6522 6523 @Override 6524 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 6525 String targetPackage, int flags) { 6526 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 6527 } 6528 6529 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 6530 int flags) { 6531 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 6532 6533 // reader 6534 synchronized (mPackages) { 6535 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6536 while (i.hasNext()) { 6537 final PackageParser.Instrumentation p = i.next(); 6538 if (targetPackage == null 6539 || targetPackage.equals(p.info.targetPackage)) { 6540 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6541 flags); 6542 if (ii != null) { 6543 finalList.add(ii); 6544 } 6545 } 6546 } 6547 } 6548 6549 return finalList; 6550 } 6551 6552 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6553 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6554 if (overlays == null) { 6555 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6556 return; 6557 } 6558 for (PackageParser.Package opkg : overlays.values()) { 6559 // Not much to do if idmap fails: we already logged the error 6560 // and we certainly don't want to abort installation of pkg simply 6561 // because an overlay didn't fit properly. For these reasons, 6562 // ignore the return value of createIdmapForPackagePairLI. 6563 createIdmapForPackagePairLI(pkg, opkg); 6564 } 6565 } 6566 6567 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6568 PackageParser.Package opkg) { 6569 if (!opkg.mTrustedOverlay) { 6570 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6571 opkg.baseCodePath + ": overlay not trusted"); 6572 return false; 6573 } 6574 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6575 if (overlaySet == null) { 6576 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6577 opkg.baseCodePath + " but target package has no known overlays"); 6578 return false; 6579 } 6580 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6581 // TODO: generate idmap for split APKs 6582 try { 6583 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6584 } catch (InstallerException e) { 6585 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6586 + opkg.baseCodePath); 6587 return false; 6588 } 6589 PackageParser.Package[] overlayArray = 6590 overlaySet.values().toArray(new PackageParser.Package[0]); 6591 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6592 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6593 return p1.mOverlayPriority - p2.mOverlayPriority; 6594 } 6595 }; 6596 Arrays.sort(overlayArray, cmp); 6597 6598 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6599 int i = 0; 6600 for (PackageParser.Package p : overlayArray) { 6601 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6602 } 6603 return true; 6604 } 6605 6606 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6607 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6608 try { 6609 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6610 } finally { 6611 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6612 } 6613 } 6614 6615 private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6616 final File[] files = dir.listFiles(); 6617 if (ArrayUtils.isEmpty(files)) { 6618 Log.d(TAG, "No files in app dir " + dir); 6619 return; 6620 } 6621 6622 if (DEBUG_PACKAGE_SCANNING) { 6623 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6624 + " flags=0x" + Integer.toHexString(parseFlags)); 6625 } 6626 6627 for (File file : files) { 6628 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6629 && !PackageInstallerService.isStageName(file.getName()); 6630 if (!isPackage) { 6631 // Ignore entries which are not packages 6632 continue; 6633 } 6634 try { 6635 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6636 scanFlags, currentTime, null); 6637 } catch (PackageManagerException e) { 6638 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6639 6640 // Delete invalid userdata apps 6641 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6642 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6643 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6644 removeCodePathLI(file); 6645 } 6646 } 6647 } 6648 } 6649 6650 private static File getSettingsProblemFile() { 6651 File dataDir = Environment.getDataDirectory(); 6652 File systemDir = new File(dataDir, "system"); 6653 File fname = new File(systemDir, "uiderrors.txt"); 6654 return fname; 6655 } 6656 6657 static void reportSettingsProblem(int priority, String msg) { 6658 logCriticalInfo(priority, msg); 6659 } 6660 6661 static void logCriticalInfo(int priority, String msg) { 6662 Slog.println(priority, TAG, msg); 6663 EventLogTags.writePmCriticalInfo(msg); 6664 try { 6665 File fname = getSettingsProblemFile(); 6666 FileOutputStream out = new FileOutputStream(fname, true); 6667 PrintWriter pw = new FastPrintWriter(out); 6668 SimpleDateFormat formatter = new SimpleDateFormat(); 6669 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6670 pw.println(dateString + ": " + msg); 6671 pw.close(); 6672 FileUtils.setPermissions( 6673 fname.toString(), 6674 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6675 -1, -1); 6676 } catch (java.io.IOException e) { 6677 } 6678 } 6679 6680 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6681 final int policyFlags) throws PackageManagerException { 6682 if (ps != null 6683 && ps.codePath.equals(srcFile) 6684 && ps.timeStamp == srcFile.lastModified() 6685 && !isCompatSignatureUpdateNeeded(pkg) 6686 && !isRecoverSignatureUpdateNeeded(pkg)) { 6687 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6688 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6689 ArraySet<PublicKey> signingKs; 6690 synchronized (mPackages) { 6691 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6692 } 6693 if (ps.signatures.mSignatures != null 6694 && ps.signatures.mSignatures.length != 0 6695 && signingKs != null) { 6696 // Optimization: reuse the existing cached certificates 6697 // if the package appears to be unchanged. 6698 pkg.mSignatures = ps.signatures.mSignatures; 6699 pkg.mSigningKeys = signingKs; 6700 return; 6701 } 6702 6703 Slog.w(TAG, "PackageSetting for " + ps.name 6704 + " is missing signatures. Collecting certs again to recover them."); 6705 } else { 6706 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6707 } 6708 6709 try { 6710 PackageParser.collectCertificates(pkg, policyFlags); 6711 } catch (PackageParserException e) { 6712 throw PackageManagerException.from(e); 6713 } 6714 } 6715 6716 /** 6717 * Traces a package scan. 6718 * @see #scanPackageLI(File, int, int, long, UserHandle) 6719 */ 6720 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 6721 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6722 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6723 try { 6724 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6725 } finally { 6726 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6727 } 6728 } 6729 6730 /** 6731 * Scans a package and returns the newly parsed package. 6732 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6733 */ 6734 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6735 long currentTime, UserHandle user) throws PackageManagerException { 6736 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6737 PackageParser pp = new PackageParser(); 6738 pp.setSeparateProcesses(mSeparateProcesses); 6739 pp.setOnlyCoreApps(mOnlyCore); 6740 pp.setDisplayMetrics(mMetrics); 6741 6742 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6743 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6744 } 6745 6746 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 6747 final PackageParser.Package pkg; 6748 try { 6749 pkg = pp.parsePackage(scanFile, parseFlags); 6750 } catch (PackageParserException e) { 6751 throw PackageManagerException.from(e); 6752 } finally { 6753 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6754 } 6755 6756 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6757 } 6758 6759 /** 6760 * Scans a package and returns the newly parsed package. 6761 * @throws PackageManagerException on a parse error. 6762 */ 6763 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6764 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 6765 throws PackageManagerException { 6766 // If the package has children and this is the first dive in the function 6767 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6768 // packages (parent and children) would be successfully scanned before the 6769 // actual scan since scanning mutates internal state and we want to atomically 6770 // install the package and its children. 6771 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6772 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6773 scanFlags |= SCAN_CHECK_ONLY; 6774 } 6775 } else { 6776 scanFlags &= ~SCAN_CHECK_ONLY; 6777 } 6778 6779 // Scan the parent 6780 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 6781 scanFlags, currentTime, user); 6782 6783 // Scan the children 6784 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6785 for (int i = 0; i < childCount; i++) { 6786 PackageParser.Package childPackage = pkg.childPackages.get(i); 6787 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 6788 currentTime, user); 6789 } 6790 6791 6792 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6793 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 6794 } 6795 6796 return scannedPkg; 6797 } 6798 6799 /** 6800 * Scans a package and returns the newly parsed package. 6801 * @throws PackageManagerException on a parse error. 6802 */ 6803 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6804 int policyFlags, int scanFlags, long currentTime, UserHandle user) 6805 throws PackageManagerException { 6806 PackageSetting ps = null; 6807 PackageSetting updatedPkg; 6808 // reader 6809 synchronized (mPackages) { 6810 // Look to see if we already know about this package. 6811 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6812 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6813 // This package has been renamed to its original name. Let's 6814 // use that. 6815 ps = mSettings.peekPackageLPr(oldName); 6816 } 6817 // If there was no original package, see one for the real package name. 6818 if (ps == null) { 6819 ps = mSettings.peekPackageLPr(pkg.packageName); 6820 } 6821 // Check to see if this package could be hiding/updating a system 6822 // package. Must look for it either under the original or real 6823 // package name depending on our state. 6824 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6825 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6826 6827 // If this is a package we don't know about on the system partition, we 6828 // may need to remove disabled child packages on the system partition 6829 // or may need to not add child packages if the parent apk is updated 6830 // on the data partition and no longer defines this child package. 6831 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6832 // If this is a parent package for an updated system app and this system 6833 // app got an OTA update which no longer defines some of the child packages 6834 // we have to prune them from the disabled system packages. 6835 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6836 if (disabledPs != null) { 6837 final int scannedChildCount = (pkg.childPackages != null) 6838 ? pkg.childPackages.size() : 0; 6839 final int disabledChildCount = disabledPs.childPackageNames != null 6840 ? disabledPs.childPackageNames.size() : 0; 6841 for (int i = 0; i < disabledChildCount; i++) { 6842 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6843 boolean disabledPackageAvailable = false; 6844 for (int j = 0; j < scannedChildCount; j++) { 6845 PackageParser.Package childPkg = pkg.childPackages.get(j); 6846 if (childPkg.packageName.equals(disabledChildPackageName)) { 6847 disabledPackageAvailable = true; 6848 break; 6849 } 6850 } 6851 if (!disabledPackageAvailable) { 6852 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6853 } 6854 } 6855 } 6856 } 6857 } 6858 6859 boolean updatedPkgBetter = false; 6860 // First check if this is a system package that may involve an update 6861 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6862 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6863 // it needs to drop FLAG_PRIVILEGED. 6864 if (locationIsPrivileged(scanFile)) { 6865 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6866 } else { 6867 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6868 } 6869 6870 if (ps != null && !ps.codePath.equals(scanFile)) { 6871 // The path has changed from what was last scanned... check the 6872 // version of the new path against what we have stored to determine 6873 // what to do. 6874 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6875 if (pkg.mVersionCode <= ps.versionCode) { 6876 // The system package has been updated and the code path does not match 6877 // Ignore entry. Skip it. 6878 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6879 + " ignored: updated version " + ps.versionCode 6880 + " better than this " + pkg.mVersionCode); 6881 if (!updatedPkg.codePath.equals(scanFile)) { 6882 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6883 + ps.name + " changing from " + updatedPkg.codePathString 6884 + " to " + scanFile); 6885 updatedPkg.codePath = scanFile; 6886 updatedPkg.codePathString = scanFile.toString(); 6887 updatedPkg.resourcePath = scanFile; 6888 updatedPkg.resourcePathString = scanFile.toString(); 6889 } 6890 updatedPkg.pkg = pkg; 6891 updatedPkg.versionCode = pkg.mVersionCode; 6892 6893 // Update the disabled system child packages to point to the package too. 6894 final int childCount = updatedPkg.childPackageNames != null 6895 ? updatedPkg.childPackageNames.size() : 0; 6896 for (int i = 0; i < childCount; i++) { 6897 String childPackageName = updatedPkg.childPackageNames.get(i); 6898 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 6899 childPackageName); 6900 if (updatedChildPkg != null) { 6901 updatedChildPkg.pkg = pkg; 6902 updatedChildPkg.versionCode = pkg.mVersionCode; 6903 } 6904 } 6905 6906 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 6907 + scanFile + " ignored: updated version " + ps.versionCode 6908 + " better than this " + pkg.mVersionCode); 6909 } else { 6910 // The current app on the system partition is better than 6911 // what we have updated to on the data partition; switch 6912 // back to the system partition version. 6913 // At this point, its safely assumed that package installation for 6914 // apps in system partition will go through. If not there won't be a working 6915 // version of the app 6916 // writer 6917 synchronized (mPackages) { 6918 // Just remove the loaded entries from package lists. 6919 mPackages.remove(ps.name); 6920 } 6921 6922 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6923 + " reverting from " + ps.codePathString 6924 + ": new version " + pkg.mVersionCode 6925 + " better than installed " + ps.versionCode); 6926 6927 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6928 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6929 synchronized (mInstallLock) { 6930 args.cleanUpResourcesLI(); 6931 } 6932 synchronized (mPackages) { 6933 mSettings.enableSystemPackageLPw(ps.name); 6934 } 6935 updatedPkgBetter = true; 6936 } 6937 } 6938 } 6939 6940 if (updatedPkg != null) { 6941 // An updated system app will not have the PARSE_IS_SYSTEM flag set 6942 // initially 6943 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 6944 6945 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 6946 // flag set initially 6947 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 6948 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 6949 } 6950 } 6951 6952 // Verify certificates against what was last scanned 6953 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 6954 6955 /* 6956 * A new system app appeared, but we already had a non-system one of the 6957 * same name installed earlier. 6958 */ 6959 boolean shouldHideSystemApp = false; 6960 if (updatedPkg == null && ps != null 6961 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 6962 /* 6963 * Check to make sure the signatures match first. If they don't, 6964 * wipe the installed application and its data. 6965 */ 6966 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 6967 != PackageManager.SIGNATURE_MATCH) { 6968 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 6969 + " signatures don't match existing userdata copy; removing"); 6970 try (PackageFreezer freezer = freezePackage(pkg.packageName, 6971 "scanPackageInternalLI")) { 6972 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 6973 } 6974 ps = null; 6975 } else { 6976 /* 6977 * If the newly-added system app is an older version than the 6978 * already installed version, hide it. It will be scanned later 6979 * and re-added like an update. 6980 */ 6981 if (pkg.mVersionCode <= ps.versionCode) { 6982 shouldHideSystemApp = true; 6983 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 6984 + " but new version " + pkg.mVersionCode + " better than installed " 6985 + ps.versionCode + "; hiding system"); 6986 } else { 6987 /* 6988 * The newly found system app is a newer version that the 6989 * one previously installed. Simply remove the 6990 * already-installed application and replace it with our own 6991 * while keeping the application data. 6992 */ 6993 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6994 + " reverting from " + ps.codePathString + ": new version " 6995 + pkg.mVersionCode + " better than installed " + ps.versionCode); 6996 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6997 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6998 synchronized (mInstallLock) { 6999 args.cleanUpResourcesLI(); 7000 } 7001 } 7002 } 7003 } 7004 7005 // The apk is forward locked (not public) if its code and resources 7006 // are kept in different files. (except for app in either system or 7007 // vendor path). 7008 // TODO grab this value from PackageSettings 7009 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7010 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 7011 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 7012 } 7013 } 7014 7015 // TODO: extend to support forward-locked splits 7016 String resourcePath = null; 7017 String baseResourcePath = null; 7018 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 7019 if (ps != null && ps.resourcePathString != null) { 7020 resourcePath = ps.resourcePathString; 7021 baseResourcePath = ps.resourcePathString; 7022 } else { 7023 // Should not happen at all. Just log an error. 7024 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 7025 } 7026 } else { 7027 resourcePath = pkg.codePath; 7028 baseResourcePath = pkg.baseCodePath; 7029 } 7030 7031 // Set application objects path explicitly. 7032 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 7033 pkg.setApplicationInfoCodePath(pkg.codePath); 7034 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 7035 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 7036 pkg.setApplicationInfoResourcePath(resourcePath); 7037 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 7038 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 7039 7040 // Note that we invoke the following method only if we are about to unpack an application 7041 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 7042 | SCAN_UPDATE_SIGNATURE, currentTime, user); 7043 7044 /* 7045 * If the system app should be overridden by a previously installed 7046 * data, hide the system app now and let the /data/app scan pick it up 7047 * again. 7048 */ 7049 if (shouldHideSystemApp) { 7050 synchronized (mPackages) { 7051 mSettings.disableSystemPackageLPw(pkg.packageName, true); 7052 } 7053 } 7054 7055 return scannedPkg; 7056 } 7057 7058 private static String fixProcessName(String defProcessName, 7059 String processName, int uid) { 7060 if (processName == null) { 7061 return defProcessName; 7062 } 7063 return processName; 7064 } 7065 7066 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 7067 throws PackageManagerException { 7068 if (pkgSetting.signatures.mSignatures != null) { 7069 // Already existing package. Make sure signatures match 7070 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 7071 == PackageManager.SIGNATURE_MATCH; 7072 if (!match) { 7073 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 7074 == PackageManager.SIGNATURE_MATCH; 7075 } 7076 if (!match) { 7077 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 7078 == PackageManager.SIGNATURE_MATCH; 7079 } 7080 if (!match) { 7081 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 7082 + pkg.packageName + " signatures do not match the " 7083 + "previously installed version; ignoring!"); 7084 } 7085 } 7086 7087 // Check for shared user signatures 7088 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 7089 // Already existing package. Make sure signatures match 7090 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7091 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 7092 if (!match) { 7093 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 7094 == PackageManager.SIGNATURE_MATCH; 7095 } 7096 if (!match) { 7097 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 7098 == PackageManager.SIGNATURE_MATCH; 7099 } 7100 if (!match) { 7101 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 7102 "Package " + pkg.packageName 7103 + " has no signatures that match those in shared user " 7104 + pkgSetting.sharedUser.name + "; ignoring!"); 7105 } 7106 } 7107 } 7108 7109 /** 7110 * Enforces that only the system UID or root's UID can call a method exposed 7111 * via Binder. 7112 * 7113 * @param message used as message if SecurityException is thrown 7114 * @throws SecurityException if the caller is not system or root 7115 */ 7116 private static final void enforceSystemOrRoot(String message) { 7117 final int uid = Binder.getCallingUid(); 7118 if (uid != Process.SYSTEM_UID && uid != 0) { 7119 throw new SecurityException(message); 7120 } 7121 } 7122 7123 @Override 7124 public void performFstrimIfNeeded() { 7125 enforceSystemOrRoot("Only the system can request fstrim"); 7126 7127 // Before everything else, see whether we need to fstrim. 7128 try { 7129 IMountService ms = PackageHelper.getMountService(); 7130 if (ms != null) { 7131 final boolean isUpgrade = isUpgrade(); 7132 boolean doTrim = isUpgrade; 7133 if (doTrim) { 7134 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 7135 } else { 7136 final long interval = android.provider.Settings.Global.getLong( 7137 mContext.getContentResolver(), 7138 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 7139 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 7140 if (interval > 0) { 7141 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 7142 if (timeSinceLast > interval) { 7143 doTrim = true; 7144 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 7145 + "; running immediately"); 7146 } 7147 } 7148 } 7149 if (doTrim) { 7150 if (!isFirstBoot()) { 7151 try { 7152 ActivityManagerNative.getDefault().showBootMessage( 7153 mContext.getResources().getString( 7154 R.string.android_upgrading_fstrim), true); 7155 } catch (RemoteException e) { 7156 } 7157 } 7158 ms.runMaintenance(); 7159 } 7160 } else { 7161 Slog.e(TAG, "Mount service unavailable!"); 7162 } 7163 } catch (RemoteException e) { 7164 // Can't happen; MountService is local 7165 } 7166 } 7167 7168 @Override 7169 public void updatePackagesIfNeeded() { 7170 enforceSystemOrRoot("Only the system can request package update"); 7171 7172 // We need to re-extract after an OTA. 7173 boolean causeUpgrade = isUpgrade(); 7174 7175 // First boot or factory reset. 7176 // Note: we also handle devices that are upgrading to N right now as if it is their 7177 // first boot, as they do not have profile data. 7178 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 7179 7180 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 7181 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 7182 7183 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 7184 return; 7185 } 7186 7187 List<PackageParser.Package> pkgs; 7188 synchronized (mPackages) { 7189 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 7190 } 7191 7192 int numberOfPackagesVisited = 0; 7193 int numberOfPackagesOptimized = 0; 7194 int numberOfPackagesSkipped = 0; 7195 int numberOfPackagesFailed = 0; 7196 final int numberOfPackagesToDexopt = pkgs.size(); 7197 final long startTime = System.nanoTime(); 7198 7199 for (PackageParser.Package pkg : pkgs) { 7200 numberOfPackagesVisited++; 7201 7202 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 7203 if (DEBUG_DEXOPT) { 7204 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 7205 } 7206 numberOfPackagesSkipped++; 7207 continue; 7208 } 7209 7210 if (DEBUG_DEXOPT) { 7211 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 7212 numberOfPackagesToDexopt + ": " + pkg.packageName); 7213 } 7214 7215 if (mIsPreNUpgrade) { 7216 try { 7217 ActivityManagerNative.getDefault().showBootMessage( 7218 mContext.getResources().getString(R.string.android_upgrading_apk, 7219 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 7220 } catch (RemoteException e) { 7221 } 7222 } 7223 7224 // checkProfiles is false to avoid merging profiles during boot which 7225 // might interfere with background compilation (b/28612421). 7226 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 7227 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 7228 // trade-off worth doing to save boot time work. 7229 int dexOptStatus = performDexOptTraced(pkg.packageName, 7230 null /* instructionSet */, 7231 false /* checkProfiles */, 7232 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT), 7233 false /* force */); 7234 switch (dexOptStatus) { 7235 case PackageDexOptimizer.DEX_OPT_PERFORMED: 7236 numberOfPackagesOptimized++; 7237 break; 7238 case PackageDexOptimizer.DEX_OPT_SKIPPED: 7239 numberOfPackagesSkipped++; 7240 break; 7241 case PackageDexOptimizer.DEX_OPT_FAILED: 7242 numberOfPackagesFailed++; 7243 break; 7244 default: 7245 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 7246 break; 7247 } 7248 } 7249 7250 final int elapsedTimeSeconds = 7251 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 7252 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", numberOfPackagesOptimized); 7253 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", numberOfPackagesSkipped); 7254 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", numberOfPackagesFailed); 7255 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 7256 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 7257 } 7258 7259 @Override 7260 public void notifyPackageUse(String packageName, int reason) { 7261 synchronized (mPackages) { 7262 PackageParser.Package p = mPackages.get(packageName); 7263 if (p == null) { 7264 return; 7265 } 7266 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 7267 } 7268 } 7269 7270 // TODO: this is not used nor needed. Delete it. 7271 @Override 7272 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 7273 int dexOptStatus = performDexOptTraced(packageName, instructionSet, 7274 false /* checkProfiles */, getFullCompilerFilter(), false /* force */); 7275 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7276 } 7277 7278 @Override 7279 public boolean performDexOpt(String packageName, String instructionSet, 7280 boolean checkProfiles, int compileReason, boolean force) { 7281 int dexOptStatus = performDexOptTraced(packageName, instructionSet, checkProfiles, 7282 getCompilerFilterForReason(compileReason), force); 7283 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7284 } 7285 7286 @Override 7287 public boolean performDexOptMode(String packageName, String instructionSet, 7288 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7289 int dexOptStatus = performDexOptTraced(packageName, instructionSet, checkProfiles, 7290 targetCompilerFilter, force); 7291 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7292 } 7293 7294 private int performDexOptTraced(String packageName, String instructionSet, 7295 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7296 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7297 try { 7298 return performDexOptInternal(packageName, instructionSet, checkProfiles, 7299 targetCompilerFilter, force); 7300 } finally { 7301 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7302 } 7303 } 7304 7305 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 7306 // if the package can now be considered up to date for the given filter. 7307 private int performDexOptInternal(String packageName, String instructionSet, 7308 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7309 PackageParser.Package p; 7310 final String targetInstructionSet; 7311 synchronized (mPackages) { 7312 p = mPackages.get(packageName); 7313 if (p == null) { 7314 // Package could not be found. Report failure. 7315 return PackageDexOptimizer.DEX_OPT_FAILED; 7316 } 7317 mPackageUsage.write(false); 7318 7319 targetInstructionSet = instructionSet != null ? instructionSet : 7320 getPrimaryInstructionSet(p.applicationInfo); 7321 } 7322 long callingId = Binder.clearCallingIdentity(); 7323 try { 7324 synchronized (mInstallLock) { 7325 final String[] instructionSets = new String[] { targetInstructionSet }; 7326 return performDexOptInternalWithDependenciesLI(p, instructionSets, checkProfiles, 7327 targetCompilerFilter, force); 7328 } 7329 } finally { 7330 Binder.restoreCallingIdentity(callingId); 7331 } 7332 } 7333 7334 public ArraySet<String> getOptimizablePackages() { 7335 ArraySet<String> pkgs = new ArraySet<String>(); 7336 synchronized (mPackages) { 7337 for (PackageParser.Package p : mPackages.values()) { 7338 if (PackageDexOptimizer.canOptimizePackage(p)) { 7339 pkgs.add(p.packageName); 7340 } 7341 } 7342 } 7343 return pkgs; 7344 } 7345 7346 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7347 String instructionSets[], boolean checkProfiles, String targetCompilerFilter, 7348 boolean force) { 7349 // Select the dex optimizer based on the force parameter. 7350 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7351 // allocate an object here. 7352 PackageDexOptimizer pdo = force 7353 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7354 : mPackageDexOptimizer; 7355 7356 // Optimize all dependencies first. Note: we ignore the return value and march on 7357 // on errors. 7358 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7359 if (!deps.isEmpty()) { 7360 for (PackageParser.Package depPackage : deps) { 7361 // TODO: Analyze and investigate if we (should) profile libraries. 7362 // Currently this will do a full compilation of the library by default. 7363 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 7364 false /* checkProfiles */, 7365 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY)); 7366 } 7367 } 7368 7369 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 7370 targetCompilerFilter); 7371 } 7372 7373 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7374 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7375 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7376 Set<String> collectedNames = new HashSet<>(); 7377 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7378 7379 retValue.remove(p); 7380 7381 return retValue; 7382 } else { 7383 return Collections.emptyList(); 7384 } 7385 } 7386 7387 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7388 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7389 if (!collectedNames.contains(p.packageName)) { 7390 collectedNames.add(p.packageName); 7391 collected.add(p); 7392 7393 if (p.usesLibraries != null) { 7394 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7395 } 7396 if (p.usesOptionalLibraries != null) { 7397 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7398 collectedNames); 7399 } 7400 } 7401 } 7402 7403 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7404 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7405 for (String libName : libs) { 7406 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7407 if (libPkg != null) { 7408 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7409 } 7410 } 7411 } 7412 7413 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7414 synchronized (mPackages) { 7415 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7416 if (lib != null && lib.apk != null) { 7417 return mPackages.get(lib.apk); 7418 } 7419 } 7420 return null; 7421 } 7422 7423 public void shutdown() { 7424 mPackageUsage.write(true); 7425 } 7426 7427 @Override 7428 public void forceDexOpt(String packageName) { 7429 enforceSystemOrRoot("forceDexOpt"); 7430 7431 PackageParser.Package pkg; 7432 synchronized (mPackages) { 7433 pkg = mPackages.get(packageName); 7434 if (pkg == null) { 7435 throw new IllegalArgumentException("Unknown package: " + packageName); 7436 } 7437 } 7438 7439 synchronized (mInstallLock) { 7440 final String[] instructionSets = new String[] { 7441 getPrimaryInstructionSet(pkg.applicationInfo) }; 7442 7443 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7444 7445 // Whoever is calling forceDexOpt wants a fully compiled package. 7446 // Don't use profiles since that may cause compilation to be skipped. 7447 final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets, 7448 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7449 true /* force */); 7450 7451 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7452 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7453 throw new IllegalStateException("Failed to dexopt: " + res); 7454 } 7455 } 7456 } 7457 7458 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7459 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7460 Slog.w(TAG, "Unable to update from " + oldPkg.name 7461 + " to " + newPkg.packageName 7462 + ": old package not in system partition"); 7463 return false; 7464 } else if (mPackages.get(oldPkg.name) != null) { 7465 Slog.w(TAG, "Unable to update from " + oldPkg.name 7466 + " to " + newPkg.packageName 7467 + ": old package still exists"); 7468 return false; 7469 } 7470 return true; 7471 } 7472 7473 void removeCodePathLI(File codePath) { 7474 if (codePath.isDirectory()) { 7475 try { 7476 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7477 } catch (InstallerException e) { 7478 Slog.w(TAG, "Failed to remove code path", e); 7479 } 7480 } else { 7481 codePath.delete(); 7482 } 7483 } 7484 7485 private int[] resolveUserIds(int userId) { 7486 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 7487 } 7488 7489 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7490 if (pkg == null) { 7491 Slog.wtf(TAG, "Package was null!", new Throwable()); 7492 return; 7493 } 7494 clearAppDataLeafLIF(pkg, userId, flags); 7495 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7496 for (int i = 0; i < childCount; i++) { 7497 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7498 } 7499 } 7500 7501 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7502 final PackageSetting ps; 7503 synchronized (mPackages) { 7504 ps = mSettings.mPackages.get(pkg.packageName); 7505 } 7506 for (int realUserId : resolveUserIds(userId)) { 7507 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7508 try { 7509 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7510 ceDataInode); 7511 } catch (InstallerException e) { 7512 Slog.w(TAG, String.valueOf(e)); 7513 } 7514 } 7515 } 7516 7517 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7518 if (pkg == null) { 7519 Slog.wtf(TAG, "Package was null!", new Throwable()); 7520 return; 7521 } 7522 destroyAppDataLeafLIF(pkg, userId, flags); 7523 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7524 for (int i = 0; i < childCount; i++) { 7525 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7526 } 7527 } 7528 7529 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7530 final PackageSetting ps; 7531 synchronized (mPackages) { 7532 ps = mSettings.mPackages.get(pkg.packageName); 7533 } 7534 for (int realUserId : resolveUserIds(userId)) { 7535 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7536 try { 7537 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7538 ceDataInode); 7539 } catch (InstallerException e) { 7540 Slog.w(TAG, String.valueOf(e)); 7541 } 7542 } 7543 } 7544 7545 private void destroyAppProfilesLIF(PackageParser.Package pkg) { 7546 if (pkg == null) { 7547 Slog.wtf(TAG, "Package was null!", new Throwable()); 7548 return; 7549 } 7550 destroyAppProfilesLeafLIF(pkg); 7551 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7552 for (int i = 0; i < childCount; i++) { 7553 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 7554 } 7555 } 7556 7557 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 7558 try { 7559 mInstaller.destroyAppProfiles(pkg.packageName); 7560 } catch (InstallerException e) { 7561 Slog.w(TAG, String.valueOf(e)); 7562 } 7563 } 7564 7565 private void clearAppProfilesLIF(PackageParser.Package pkg) { 7566 if (pkg == null) { 7567 Slog.wtf(TAG, "Package was null!", new Throwable()); 7568 return; 7569 } 7570 clearAppProfilesLeafLIF(pkg); 7571 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7572 for (int i = 0; i < childCount; i++) { 7573 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 7574 } 7575 } 7576 7577 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 7578 try { 7579 mInstaller.clearAppProfiles(pkg.packageName); 7580 } catch (InstallerException e) { 7581 Slog.w(TAG, String.valueOf(e)); 7582 } 7583 } 7584 7585 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7586 long lastUpdateTime) { 7587 // Set parent install/update time 7588 PackageSetting ps = (PackageSetting) pkg.mExtras; 7589 if (ps != null) { 7590 ps.firstInstallTime = firstInstallTime; 7591 ps.lastUpdateTime = lastUpdateTime; 7592 } 7593 // Set children install/update time 7594 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7595 for (int i = 0; i < childCount; i++) { 7596 PackageParser.Package childPkg = pkg.childPackages.get(i); 7597 ps = (PackageSetting) childPkg.mExtras; 7598 if (ps != null) { 7599 ps.firstInstallTime = firstInstallTime; 7600 ps.lastUpdateTime = lastUpdateTime; 7601 } 7602 } 7603 } 7604 7605 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7606 PackageParser.Package changingLib) { 7607 if (file.path != null) { 7608 usesLibraryFiles.add(file.path); 7609 return; 7610 } 7611 PackageParser.Package p = mPackages.get(file.apk); 7612 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7613 // If we are doing this while in the middle of updating a library apk, 7614 // then we need to make sure to use that new apk for determining the 7615 // dependencies here. (We haven't yet finished committing the new apk 7616 // to the package manager state.) 7617 if (p == null || p.packageName.equals(changingLib.packageName)) { 7618 p = changingLib; 7619 } 7620 } 7621 if (p != null) { 7622 usesLibraryFiles.addAll(p.getAllCodePaths()); 7623 } 7624 } 7625 7626 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7627 PackageParser.Package changingLib) throws PackageManagerException { 7628 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7629 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7630 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7631 for (int i=0; i<N; i++) { 7632 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7633 if (file == null) { 7634 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7635 "Package " + pkg.packageName + " requires unavailable shared library " 7636 + pkg.usesLibraries.get(i) + "; failing!"); 7637 } 7638 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7639 } 7640 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7641 for (int i=0; i<N; i++) { 7642 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7643 if (file == null) { 7644 Slog.w(TAG, "Package " + pkg.packageName 7645 + " desires unavailable shared library " 7646 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7647 } else { 7648 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7649 } 7650 } 7651 N = usesLibraryFiles.size(); 7652 if (N > 0) { 7653 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7654 } else { 7655 pkg.usesLibraryFiles = null; 7656 } 7657 } 7658 } 7659 7660 private static boolean hasString(List<String> list, List<String> which) { 7661 if (list == null) { 7662 return false; 7663 } 7664 for (int i=list.size()-1; i>=0; i--) { 7665 for (int j=which.size()-1; j>=0; j--) { 7666 if (which.get(j).equals(list.get(i))) { 7667 return true; 7668 } 7669 } 7670 } 7671 return false; 7672 } 7673 7674 private void updateAllSharedLibrariesLPw() { 7675 for (PackageParser.Package pkg : mPackages.values()) { 7676 try { 7677 updateSharedLibrariesLPw(pkg, null); 7678 } catch (PackageManagerException e) { 7679 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7680 } 7681 } 7682 } 7683 7684 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7685 PackageParser.Package changingPkg) { 7686 ArrayList<PackageParser.Package> res = null; 7687 for (PackageParser.Package pkg : mPackages.values()) { 7688 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7689 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7690 if (res == null) { 7691 res = new ArrayList<PackageParser.Package>(); 7692 } 7693 res.add(pkg); 7694 try { 7695 updateSharedLibrariesLPw(pkg, changingPkg); 7696 } catch (PackageManagerException e) { 7697 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7698 } 7699 } 7700 } 7701 return res; 7702 } 7703 7704 /** 7705 * Derive the value of the {@code cpuAbiOverride} based on the provided 7706 * value and an optional stored value from the package settings. 7707 */ 7708 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7709 String cpuAbiOverride = null; 7710 7711 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7712 cpuAbiOverride = null; 7713 } else if (abiOverride != null) { 7714 cpuAbiOverride = abiOverride; 7715 } else if (settings != null) { 7716 cpuAbiOverride = settings.cpuAbiOverrideString; 7717 } 7718 7719 return cpuAbiOverride; 7720 } 7721 7722 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 7723 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 7724 throws PackageManagerException { 7725 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7726 // If the package has children and this is the first dive in the function 7727 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7728 // whether all packages (parent and children) would be successfully scanned 7729 // before the actual scan since scanning mutates internal state and we want 7730 // to atomically install the package and its children. 7731 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7732 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7733 scanFlags |= SCAN_CHECK_ONLY; 7734 } 7735 } else { 7736 scanFlags &= ~SCAN_CHECK_ONLY; 7737 } 7738 7739 final PackageParser.Package scannedPkg; 7740 try { 7741 // Scan the parent 7742 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 7743 // Scan the children 7744 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7745 for (int i = 0; i < childCount; i++) { 7746 PackageParser.Package childPkg = pkg.childPackages.get(i); 7747 scanPackageLI(childPkg, policyFlags, 7748 scanFlags, currentTime, user); 7749 } 7750 } finally { 7751 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7752 } 7753 7754 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7755 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 7756 } 7757 7758 return scannedPkg; 7759 } 7760 7761 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 7762 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7763 boolean success = false; 7764 try { 7765 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 7766 currentTime, user); 7767 success = true; 7768 return res; 7769 } finally { 7770 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 7771 // DELETE_DATA_ON_FAILURES is only used by frozen paths 7772 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 7773 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 7774 destroyAppProfilesLIF(pkg); 7775 } 7776 } 7777 } 7778 7779 /** 7780 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 7781 */ 7782 private static boolean apkHasCode(String fileName) { 7783 StrictJarFile jarFile = null; 7784 try { 7785 jarFile = new StrictJarFile(fileName, 7786 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 7787 return jarFile.findEntry("classes.dex") != null; 7788 } catch (IOException ignore) { 7789 } finally { 7790 try { 7791 jarFile.close(); 7792 } catch (IOException ignore) {} 7793 } 7794 return false; 7795 } 7796 7797 /** 7798 * Enforces code policy for the package. This ensures that if an APK has 7799 * declared hasCode="true" in its manifest that the APK actually contains 7800 * code. 7801 * 7802 * @throws PackageManagerException If bytecode could not be found when it should exist 7803 */ 7804 private static void enforceCodePolicy(PackageParser.Package pkg) 7805 throws PackageManagerException { 7806 final boolean shouldHaveCode = 7807 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 7808 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 7809 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7810 "Package " + pkg.baseCodePath + " code is missing"); 7811 } 7812 7813 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 7814 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 7815 final boolean splitShouldHaveCode = 7816 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 7817 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 7818 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7819 "Package " + pkg.splitCodePaths[i] + " code is missing"); 7820 } 7821 } 7822 } 7823 } 7824 7825 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 7826 final int policyFlags, final int scanFlags, long currentTime, UserHandle user) 7827 throws PackageManagerException { 7828 final File scanFile = new File(pkg.codePath); 7829 if (pkg.applicationInfo.getCodePath() == null || 7830 pkg.applicationInfo.getResourcePath() == null) { 7831 // Bail out. The resource and code paths haven't been set. 7832 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7833 "Code and resource paths haven't been set correctly"); 7834 } 7835 7836 // Apply policy 7837 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 7838 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 7839 if (pkg.applicationInfo.isDirectBootAware()) { 7840 // we're direct boot aware; set for all components 7841 for (PackageParser.Service s : pkg.services) { 7842 s.info.encryptionAware = s.info.directBootAware = true; 7843 } 7844 for (PackageParser.Provider p : pkg.providers) { 7845 p.info.encryptionAware = p.info.directBootAware = true; 7846 } 7847 for (PackageParser.Activity a : pkg.activities) { 7848 a.info.encryptionAware = a.info.directBootAware = true; 7849 } 7850 for (PackageParser.Activity r : pkg.receivers) { 7851 r.info.encryptionAware = r.info.directBootAware = true; 7852 } 7853 } 7854 } else { 7855 // Only allow system apps to be flagged as core apps. 7856 pkg.coreApp = false; 7857 // clear flags not applicable to regular apps 7858 pkg.applicationInfo.privateFlags &= 7859 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 7860 pkg.applicationInfo.privateFlags &= 7861 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 7862 } 7863 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 7864 7865 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 7866 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7867 } 7868 7869 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 7870 enforceCodePolicy(pkg); 7871 } 7872 7873 if (mCustomResolverComponentName != null && 7874 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 7875 setUpCustomResolverActivity(pkg); 7876 } 7877 7878 if (pkg.packageName.equals("android")) { 7879 synchronized (mPackages) { 7880 if (mAndroidApplication != null) { 7881 Slog.w(TAG, "*************************************************"); 7882 Slog.w(TAG, "Core android package being redefined. Skipping."); 7883 Slog.w(TAG, " file=" + scanFile); 7884 Slog.w(TAG, "*************************************************"); 7885 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7886 "Core android package being redefined. Skipping."); 7887 } 7888 7889 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7890 // Set up information for our fall-back user intent resolution activity. 7891 mPlatformPackage = pkg; 7892 pkg.mVersionCode = mSdkVersion; 7893 mAndroidApplication = pkg.applicationInfo; 7894 7895 if (!mResolverReplaced) { 7896 mResolveActivity.applicationInfo = mAndroidApplication; 7897 mResolveActivity.name = ResolverActivity.class.getName(); 7898 mResolveActivity.packageName = mAndroidApplication.packageName; 7899 mResolveActivity.processName = "system:ui"; 7900 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7901 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 7902 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 7903 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 7904 mResolveActivity.exported = true; 7905 mResolveActivity.enabled = true; 7906 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 7907 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 7908 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 7909 | ActivityInfo.CONFIG_SCREEN_LAYOUT 7910 | ActivityInfo.CONFIG_ORIENTATION 7911 | ActivityInfo.CONFIG_KEYBOARD 7912 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 7913 mResolveInfo.activityInfo = mResolveActivity; 7914 mResolveInfo.priority = 0; 7915 mResolveInfo.preferredOrder = 0; 7916 mResolveInfo.match = 0; 7917 mResolveComponentName = new ComponentName( 7918 mAndroidApplication.packageName, mResolveActivity.name); 7919 } 7920 } 7921 } 7922 } 7923 7924 if (DEBUG_PACKAGE_SCANNING) { 7925 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 7926 Log.d(TAG, "Scanning package " + pkg.packageName); 7927 } 7928 7929 synchronized (mPackages) { 7930 if (mPackages.containsKey(pkg.packageName) 7931 || mSharedLibraries.containsKey(pkg.packageName)) { 7932 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7933 "Application package " + pkg.packageName 7934 + " already installed. Skipping duplicate."); 7935 } 7936 7937 // If we're only installing presumed-existing packages, require that the 7938 // scanned APK is both already known and at the path previously established 7939 // for it. Previously unknown packages we pick up normally, but if we have an 7940 // a priori expectation about this package's install presence, enforce it. 7941 // With a singular exception for new system packages. When an OTA contains 7942 // a new system package, we allow the codepath to change from a system location 7943 // to the user-installed location. If we don't allow this change, any newer, 7944 // user-installed version of the application will be ignored. 7945 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 7946 if (mExpectingBetter.containsKey(pkg.packageName)) { 7947 logCriticalInfo(Log.WARN, 7948 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 7949 } else { 7950 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 7951 if (known != null) { 7952 if (DEBUG_PACKAGE_SCANNING) { 7953 Log.d(TAG, "Examining " + pkg.codePath 7954 + " and requiring known paths " + known.codePathString 7955 + " & " + known.resourcePathString); 7956 } 7957 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 7958 || !pkg.applicationInfo.getResourcePath().equals( 7959 known.resourcePathString)) { 7960 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 7961 "Application package " + pkg.packageName 7962 + " found at " + pkg.applicationInfo.getCodePath() 7963 + " but expected at " + known.codePathString 7964 + "; ignoring."); 7965 } 7966 } 7967 } 7968 } 7969 } 7970 7971 // Initialize package source and resource directories 7972 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 7973 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 7974 7975 SharedUserSetting suid = null; 7976 PackageSetting pkgSetting = null; 7977 7978 if (!isSystemApp(pkg)) { 7979 // Only system apps can use these features. 7980 pkg.mOriginalPackages = null; 7981 pkg.mRealPackage = null; 7982 pkg.mAdoptPermissions = null; 7983 } 7984 7985 // Getting the package setting may have a side-effect, so if we 7986 // are only checking if scan would succeed, stash a copy of the 7987 // old setting to restore at the end. 7988 PackageSetting nonMutatedPs = null; 7989 7990 // writer 7991 synchronized (mPackages) { 7992 if (pkg.mSharedUserId != null) { 7993 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 7994 if (suid == null) { 7995 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7996 "Creating application package " + pkg.packageName 7997 + " for shared user failed"); 7998 } 7999 if (DEBUG_PACKAGE_SCANNING) { 8000 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8001 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 8002 + "): packages=" + suid.packages); 8003 } 8004 } 8005 8006 // Check if we are renaming from an original package name. 8007 PackageSetting origPackage = null; 8008 String realName = null; 8009 if (pkg.mOriginalPackages != null) { 8010 // This package may need to be renamed to a previously 8011 // installed name. Let's check on that... 8012 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 8013 if (pkg.mOriginalPackages.contains(renamed)) { 8014 // This package had originally been installed as the 8015 // original name, and we have already taken care of 8016 // transitioning to the new one. Just update the new 8017 // one to continue using the old name. 8018 realName = pkg.mRealPackage; 8019 if (!pkg.packageName.equals(renamed)) { 8020 // Callers into this function may have already taken 8021 // care of renaming the package; only do it here if 8022 // it is not already done. 8023 pkg.setPackageName(renamed); 8024 } 8025 8026 } else { 8027 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 8028 if ((origPackage = mSettings.peekPackageLPr( 8029 pkg.mOriginalPackages.get(i))) != null) { 8030 // We do have the package already installed under its 8031 // original name... should we use it? 8032 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 8033 // New package is not compatible with original. 8034 origPackage = null; 8035 continue; 8036 } else if (origPackage.sharedUser != null) { 8037 // Make sure uid is compatible between packages. 8038 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 8039 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 8040 + " to " + pkg.packageName + ": old uid " 8041 + origPackage.sharedUser.name 8042 + " differs from " + pkg.mSharedUserId); 8043 origPackage = null; 8044 continue; 8045 } 8046 // TODO: Add case when shared user id is added [b/28144775] 8047 } else { 8048 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 8049 + pkg.packageName + " to old name " + origPackage.name); 8050 } 8051 break; 8052 } 8053 } 8054 } 8055 } 8056 8057 if (mTransferedPackages.contains(pkg.packageName)) { 8058 Slog.w(TAG, "Package " + pkg.packageName 8059 + " was transferred to another, but its .apk remains"); 8060 } 8061 8062 // See comments in nonMutatedPs declaration 8063 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8064 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 8065 if (foundPs != null) { 8066 nonMutatedPs = new PackageSetting(foundPs); 8067 } 8068 } 8069 8070 // Just create the setting, don't add it yet. For already existing packages 8071 // the PkgSetting exists already and doesn't have to be created. 8072 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 8073 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 8074 pkg.applicationInfo.primaryCpuAbi, 8075 pkg.applicationInfo.secondaryCpuAbi, 8076 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 8077 user, false); 8078 if (pkgSetting == null) { 8079 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8080 "Creating application package " + pkg.packageName + " failed"); 8081 } 8082 8083 if (pkgSetting.origPackage != null) { 8084 // If we are first transitioning from an original package, 8085 // fix up the new package's name now. We need to do this after 8086 // looking up the package under its new name, so getPackageLP 8087 // can take care of fiddling things correctly. 8088 pkg.setPackageName(origPackage.name); 8089 8090 // File a report about this. 8091 String msg = "New package " + pkgSetting.realName 8092 + " renamed to replace old package " + pkgSetting.name; 8093 reportSettingsProblem(Log.WARN, msg); 8094 8095 // Make a note of it. 8096 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8097 mTransferedPackages.add(origPackage.name); 8098 } 8099 8100 // No longer need to retain this. 8101 pkgSetting.origPackage = null; 8102 } 8103 8104 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 8105 // Make a note of it. 8106 mTransferedPackages.add(pkg.packageName); 8107 } 8108 8109 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 8110 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 8111 } 8112 8113 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8114 // Check all shared libraries and map to their actual file path. 8115 // We only do this here for apps not on a system dir, because those 8116 // are the only ones that can fail an install due to this. We 8117 // will take care of the system apps by updating all of their 8118 // library paths after the scan is done. 8119 updateSharedLibrariesLPw(pkg, null); 8120 } 8121 8122 if (mFoundPolicyFile) { 8123 SELinuxMMAC.assignSeinfoValue(pkg); 8124 } 8125 8126 pkg.applicationInfo.uid = pkgSetting.appId; 8127 pkg.mExtras = pkgSetting; 8128 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 8129 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 8130 // We just determined the app is signed correctly, so bring 8131 // over the latest parsed certs. 8132 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8133 } else { 8134 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8135 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8136 "Package " + pkg.packageName + " upgrade keys do not match the " 8137 + "previously installed version"); 8138 } else { 8139 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8140 String msg = "System package " + pkg.packageName 8141 + " signature changed; retaining data."; 8142 reportSettingsProblem(Log.WARN, msg); 8143 } 8144 } 8145 } else { 8146 try { 8147 verifySignaturesLP(pkgSetting, pkg); 8148 // We just determined the app is signed correctly, so bring 8149 // over the latest parsed certs. 8150 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8151 } catch (PackageManagerException e) { 8152 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8153 throw e; 8154 } 8155 // The signature has changed, but this package is in the system 8156 // image... let's recover! 8157 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8158 // However... if this package is part of a shared user, but it 8159 // doesn't match the signature of the shared user, let's fail. 8160 // What this means is that you can't change the signatures 8161 // associated with an overall shared user, which doesn't seem all 8162 // that unreasonable. 8163 if (pkgSetting.sharedUser != null) { 8164 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8165 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 8166 throw new PackageManagerException( 8167 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 8168 "Signature mismatch for shared user: " 8169 + pkgSetting.sharedUser); 8170 } 8171 } 8172 // File a report about this. 8173 String msg = "System package " + pkg.packageName 8174 + " signature changed; retaining data."; 8175 reportSettingsProblem(Log.WARN, msg); 8176 } 8177 } 8178 // Verify that this new package doesn't have any content providers 8179 // that conflict with existing packages. Only do this if the 8180 // package isn't already installed, since we don't want to break 8181 // things that are installed. 8182 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 8183 final int N = pkg.providers.size(); 8184 int i; 8185 for (i=0; i<N; i++) { 8186 PackageParser.Provider p = pkg.providers.get(i); 8187 if (p.info.authority != null) { 8188 String names[] = p.info.authority.split(";"); 8189 for (int j = 0; j < names.length; j++) { 8190 if (mProvidersByAuthority.containsKey(names[j])) { 8191 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8192 final String otherPackageName = 8193 ((other != null && other.getComponentName() != null) ? 8194 other.getComponentName().getPackageName() : "?"); 8195 throw new PackageManagerException( 8196 INSTALL_FAILED_CONFLICTING_PROVIDER, 8197 "Can't install because provider name " + names[j] 8198 + " (in package " + pkg.applicationInfo.packageName 8199 + ") is already used by " + otherPackageName); 8200 } 8201 } 8202 } 8203 } 8204 } 8205 8206 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 8207 // This package wants to adopt ownership of permissions from 8208 // another package. 8209 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 8210 final String origName = pkg.mAdoptPermissions.get(i); 8211 final PackageSetting orig = mSettings.peekPackageLPr(origName); 8212 if (orig != null) { 8213 if (verifyPackageUpdateLPr(orig, pkg)) { 8214 Slog.i(TAG, "Adopting permissions from " + origName + " to " 8215 + pkg.packageName); 8216 mSettings.transferPermissionsLPw(origName, pkg.packageName); 8217 } 8218 } 8219 } 8220 } 8221 } 8222 8223 final String pkgName = pkg.packageName; 8224 8225 final long scanFileTime = scanFile.lastModified(); 8226 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 8227 pkg.applicationInfo.processName = fixProcessName( 8228 pkg.applicationInfo.packageName, 8229 pkg.applicationInfo.processName, 8230 pkg.applicationInfo.uid); 8231 8232 if (pkg != mPlatformPackage) { 8233 // Get all of our default paths setup 8234 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 8235 } 8236 8237 final String path = scanFile.getPath(); 8238 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 8239 8240 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 8241 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 8242 8243 // Some system apps still use directory structure for native libraries 8244 // in which case we might end up not detecting abi solely based on apk 8245 // structure. Try to detect abi based on directory structure. 8246 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 8247 pkg.applicationInfo.primaryCpuAbi == null) { 8248 setBundledAppAbisAndRoots(pkg, pkgSetting); 8249 setNativeLibraryPaths(pkg); 8250 } 8251 8252 } else { 8253 if ((scanFlags & SCAN_MOVE) != 0) { 8254 // We haven't run dex-opt for this move (since we've moved the compiled output too) 8255 // but we already have this packages package info in the PackageSetting. We just 8256 // use that and derive the native library path based on the new codepath. 8257 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 8258 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 8259 } 8260 8261 // Set native library paths again. For moves, the path will be updated based on the 8262 // ABIs we've determined above. For non-moves, the path will be updated based on the 8263 // ABIs we determined during compilation, but the path will depend on the final 8264 // package path (after the rename away from the stage path). 8265 setNativeLibraryPaths(pkg); 8266 } 8267 8268 // This is a special case for the "system" package, where the ABI is 8269 // dictated by the zygote configuration (and init.rc). We should keep track 8270 // of this ABI so that we can deal with "normal" applications that run under 8271 // the same UID correctly. 8272 if (mPlatformPackage == pkg) { 8273 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 8274 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 8275 } 8276 8277 // If there's a mismatch between the abi-override in the package setting 8278 // and the abiOverride specified for the install. Warn about this because we 8279 // would've already compiled the app without taking the package setting into 8280 // account. 8281 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 8282 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 8283 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 8284 " for package " + pkg.packageName); 8285 } 8286 } 8287 8288 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8289 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8290 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 8291 8292 // Copy the derived override back to the parsed package, so that we can 8293 // update the package settings accordingly. 8294 pkg.cpuAbiOverride = cpuAbiOverride; 8295 8296 if (DEBUG_ABI_SELECTION) { 8297 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 8298 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 8299 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 8300 } 8301 8302 // Push the derived path down into PackageSettings so we know what to 8303 // clean up at uninstall time. 8304 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 8305 8306 if (DEBUG_ABI_SELECTION) { 8307 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 8308 " primary=" + pkg.applicationInfo.primaryCpuAbi + 8309 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 8310 } 8311 8312 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 8313 // We don't do this here during boot because we can do it all 8314 // at once after scanning all existing packages. 8315 // 8316 // We also do this *before* we perform dexopt on this package, so that 8317 // we can avoid redundant dexopts, and also to make sure we've got the 8318 // code and package path correct. 8319 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 8320 pkg, true /* boot complete */); 8321 } 8322 8323 if (mFactoryTest && pkg.requestedPermissions.contains( 8324 android.Manifest.permission.FACTORY_TEST)) { 8325 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 8326 } 8327 8328 ArrayList<PackageParser.Package> clientLibPkgs = null; 8329 8330 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8331 if (nonMutatedPs != null) { 8332 synchronized (mPackages) { 8333 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 8334 } 8335 } 8336 return pkg; 8337 } 8338 8339 // Only privileged apps and updated privileged apps can add child packages. 8340 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 8341 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 8342 throw new PackageManagerException("Only privileged apps and updated " 8343 + "privileged apps can add child packages. Ignoring package " 8344 + pkg.packageName); 8345 } 8346 final int childCount = pkg.childPackages.size(); 8347 for (int i = 0; i < childCount; i++) { 8348 PackageParser.Package childPkg = pkg.childPackages.get(i); 8349 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 8350 childPkg.packageName)) { 8351 throw new PackageManagerException("Cannot override a child package of " 8352 + "another disabled system app. Ignoring package " + pkg.packageName); 8353 } 8354 } 8355 } 8356 8357 // writer 8358 synchronized (mPackages) { 8359 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8360 // Only system apps can add new shared libraries. 8361 if (pkg.libraryNames != null) { 8362 for (int i=0; i<pkg.libraryNames.size(); i++) { 8363 String name = pkg.libraryNames.get(i); 8364 boolean allowed = false; 8365 if (pkg.isUpdatedSystemApp()) { 8366 // New library entries can only be added through the 8367 // system image. This is important to get rid of a lot 8368 // of nasty edge cases: for example if we allowed a non- 8369 // system update of the app to add a library, then uninstalling 8370 // the update would make the library go away, and assumptions 8371 // we made such as through app install filtering would now 8372 // have allowed apps on the device which aren't compatible 8373 // with it. Better to just have the restriction here, be 8374 // conservative, and create many fewer cases that can negatively 8375 // impact the user experience. 8376 final PackageSetting sysPs = mSettings 8377 .getDisabledSystemPkgLPr(pkg.packageName); 8378 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 8379 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 8380 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 8381 allowed = true; 8382 break; 8383 } 8384 } 8385 } 8386 } else { 8387 allowed = true; 8388 } 8389 if (allowed) { 8390 if (!mSharedLibraries.containsKey(name)) { 8391 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 8392 } else if (!name.equals(pkg.packageName)) { 8393 Slog.w(TAG, "Package " + pkg.packageName + " library " 8394 + name + " already exists; skipping"); 8395 } 8396 } else { 8397 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 8398 + name + " that is not declared on system image; skipping"); 8399 } 8400 } 8401 if ((scanFlags & SCAN_BOOTING) == 0) { 8402 // If we are not booting, we need to update any applications 8403 // that are clients of our shared library. If we are booting, 8404 // this will all be done once the scan is complete. 8405 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 8406 } 8407 } 8408 } 8409 } 8410 8411 if ((scanFlags & SCAN_BOOTING) != 0) { 8412 // No apps can run during boot scan, so they don't need to be frozen 8413 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 8414 // Caller asked to not kill app, so it's probably not frozen 8415 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 8416 // Caller asked us to ignore frozen check for some reason; they 8417 // probably didn't know the package name 8418 } else { 8419 // We're doing major surgery on this package, so it better be frozen 8420 // right now to keep it from launching 8421 checkPackageFrozen(pkgName); 8422 } 8423 8424 // Also need to kill any apps that are dependent on the library. 8425 if (clientLibPkgs != null) { 8426 for (int i=0; i<clientLibPkgs.size(); i++) { 8427 PackageParser.Package clientPkg = clientLibPkgs.get(i); 8428 killApplication(clientPkg.applicationInfo.packageName, 8429 clientPkg.applicationInfo.uid, "update lib"); 8430 } 8431 } 8432 8433 // Make sure we're not adding any bogus keyset info 8434 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8435 ksms.assertScannedPackageValid(pkg); 8436 8437 // writer 8438 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 8439 8440 boolean createIdmapFailed = false; 8441 synchronized (mPackages) { 8442 // We don't expect installation to fail beyond this point 8443 8444 // Add the new setting to mSettings 8445 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 8446 // Add the new setting to mPackages 8447 mPackages.put(pkg.applicationInfo.packageName, pkg); 8448 // Make sure we don't accidentally delete its data. 8449 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 8450 while (iter.hasNext()) { 8451 PackageCleanItem item = iter.next(); 8452 if (pkgName.equals(item.packageName)) { 8453 iter.remove(); 8454 } 8455 } 8456 8457 // Take care of first install / last update times. 8458 if (currentTime != 0) { 8459 if (pkgSetting.firstInstallTime == 0) { 8460 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8461 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 8462 pkgSetting.lastUpdateTime = currentTime; 8463 } 8464 } else if (pkgSetting.firstInstallTime == 0) { 8465 // We need *something*. Take time time stamp of the file. 8466 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8467 } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8468 if (scanFileTime != pkgSetting.timeStamp) { 8469 // A package on the system image has changed; consider this 8470 // to be an update. 8471 pkgSetting.lastUpdateTime = scanFileTime; 8472 } 8473 } 8474 8475 // Add the package's KeySets to the global KeySetManagerService 8476 ksms.addScannedPackageLPw(pkg); 8477 8478 int N = pkg.providers.size(); 8479 StringBuilder r = null; 8480 int i; 8481 for (i=0; i<N; i++) { 8482 PackageParser.Provider p = pkg.providers.get(i); 8483 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 8484 p.info.processName, pkg.applicationInfo.uid); 8485 mProviders.addProvider(p); 8486 p.syncable = p.info.isSyncable; 8487 if (p.info.authority != null) { 8488 String names[] = p.info.authority.split(";"); 8489 p.info.authority = null; 8490 for (int j = 0; j < names.length; j++) { 8491 if (j == 1 && p.syncable) { 8492 // We only want the first authority for a provider to possibly be 8493 // syncable, so if we already added this provider using a different 8494 // authority clear the syncable flag. We copy the provider before 8495 // changing it because the mProviders object contains a reference 8496 // to a provider that we don't want to change. 8497 // Only do this for the second authority since the resulting provider 8498 // object can be the same for all future authorities for this provider. 8499 p = new PackageParser.Provider(p); 8500 p.syncable = false; 8501 } 8502 if (!mProvidersByAuthority.containsKey(names[j])) { 8503 mProvidersByAuthority.put(names[j], p); 8504 if (p.info.authority == null) { 8505 p.info.authority = names[j]; 8506 } else { 8507 p.info.authority = p.info.authority + ";" + names[j]; 8508 } 8509 if (DEBUG_PACKAGE_SCANNING) { 8510 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8511 Log.d(TAG, "Registered content provider: " + names[j] 8512 + ", className = " + p.info.name + ", isSyncable = " 8513 + p.info.isSyncable); 8514 } 8515 } else { 8516 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8517 Slog.w(TAG, "Skipping provider name " + names[j] + 8518 " (in package " + pkg.applicationInfo.packageName + 8519 "): name already used by " 8520 + ((other != null && other.getComponentName() != null) 8521 ? other.getComponentName().getPackageName() : "?")); 8522 } 8523 } 8524 } 8525 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8526 if (r == null) { 8527 r = new StringBuilder(256); 8528 } else { 8529 r.append(' '); 8530 } 8531 r.append(p.info.name); 8532 } 8533 } 8534 if (r != null) { 8535 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8536 } 8537 8538 N = pkg.services.size(); 8539 r = null; 8540 for (i=0; i<N; i++) { 8541 PackageParser.Service s = pkg.services.get(i); 8542 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8543 s.info.processName, pkg.applicationInfo.uid); 8544 mServices.addService(s); 8545 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8546 if (r == null) { 8547 r = new StringBuilder(256); 8548 } else { 8549 r.append(' '); 8550 } 8551 r.append(s.info.name); 8552 } 8553 } 8554 if (r != null) { 8555 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8556 } 8557 8558 N = pkg.receivers.size(); 8559 r = null; 8560 for (i=0; i<N; i++) { 8561 PackageParser.Activity a = pkg.receivers.get(i); 8562 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8563 a.info.processName, pkg.applicationInfo.uid); 8564 mReceivers.addActivity(a, "receiver"); 8565 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8566 if (r == null) { 8567 r = new StringBuilder(256); 8568 } else { 8569 r.append(' '); 8570 } 8571 r.append(a.info.name); 8572 } 8573 } 8574 if (r != null) { 8575 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8576 } 8577 8578 N = pkg.activities.size(); 8579 r = null; 8580 for (i=0; i<N; i++) { 8581 PackageParser.Activity a = pkg.activities.get(i); 8582 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8583 a.info.processName, pkg.applicationInfo.uid); 8584 mActivities.addActivity(a, "activity"); 8585 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8586 if (r == null) { 8587 r = new StringBuilder(256); 8588 } else { 8589 r.append(' '); 8590 } 8591 r.append(a.info.name); 8592 } 8593 } 8594 if (r != null) { 8595 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8596 } 8597 8598 N = pkg.permissionGroups.size(); 8599 r = null; 8600 for (i=0; i<N; i++) { 8601 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8602 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8603 if (cur == null) { 8604 mPermissionGroups.put(pg.info.name, pg); 8605 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8606 if (r == null) { 8607 r = new StringBuilder(256); 8608 } else { 8609 r.append(' '); 8610 } 8611 r.append(pg.info.name); 8612 } 8613 } else { 8614 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8615 + pg.info.packageName + " ignored: original from " 8616 + cur.info.packageName); 8617 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8618 if (r == null) { 8619 r = new StringBuilder(256); 8620 } else { 8621 r.append(' '); 8622 } 8623 r.append("DUP:"); 8624 r.append(pg.info.name); 8625 } 8626 } 8627 } 8628 if (r != null) { 8629 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8630 } 8631 8632 N = pkg.permissions.size(); 8633 r = null; 8634 for (i=0; i<N; i++) { 8635 PackageParser.Permission p = pkg.permissions.get(i); 8636 8637 // Assume by default that we did not install this permission into the system. 8638 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8639 8640 // Now that permission groups have a special meaning, we ignore permission 8641 // groups for legacy apps to prevent unexpected behavior. In particular, 8642 // permissions for one app being granted to someone just becase they happen 8643 // to be in a group defined by another app (before this had no implications). 8644 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8645 p.group = mPermissionGroups.get(p.info.group); 8646 // Warn for a permission in an unknown group. 8647 if (p.info.group != null && p.group == null) { 8648 Slog.w(TAG, "Permission " + p.info.name + " from package " 8649 + p.info.packageName + " in an unknown group " + p.info.group); 8650 } 8651 } 8652 8653 ArrayMap<String, BasePermission> permissionMap = 8654 p.tree ? mSettings.mPermissionTrees 8655 : mSettings.mPermissions; 8656 BasePermission bp = permissionMap.get(p.info.name); 8657 8658 // Allow system apps to redefine non-system permissions 8659 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8660 final boolean currentOwnerIsSystem = (bp.perm != null 8661 && isSystemApp(bp.perm.owner)); 8662 if (isSystemApp(p.owner)) { 8663 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8664 // It's a built-in permission and no owner, take ownership now 8665 bp.packageSetting = pkgSetting; 8666 bp.perm = p; 8667 bp.uid = pkg.applicationInfo.uid; 8668 bp.sourcePackage = p.info.packageName; 8669 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8670 } else if (!currentOwnerIsSystem) { 8671 String msg = "New decl " + p.owner + " of permission " 8672 + p.info.name + " is system; overriding " + bp.sourcePackage; 8673 reportSettingsProblem(Log.WARN, msg); 8674 bp = null; 8675 } 8676 } 8677 } 8678 8679 if (bp == null) { 8680 bp = new BasePermission(p.info.name, p.info.packageName, 8681 BasePermission.TYPE_NORMAL); 8682 permissionMap.put(p.info.name, bp); 8683 } 8684 8685 if (bp.perm == null) { 8686 if (bp.sourcePackage == null 8687 || bp.sourcePackage.equals(p.info.packageName)) { 8688 BasePermission tree = findPermissionTreeLP(p.info.name); 8689 if (tree == null 8690 || tree.sourcePackage.equals(p.info.packageName)) { 8691 bp.packageSetting = pkgSetting; 8692 bp.perm = p; 8693 bp.uid = pkg.applicationInfo.uid; 8694 bp.sourcePackage = p.info.packageName; 8695 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8696 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8697 if (r == null) { 8698 r = new StringBuilder(256); 8699 } else { 8700 r.append(' '); 8701 } 8702 r.append(p.info.name); 8703 } 8704 } else { 8705 Slog.w(TAG, "Permission " + p.info.name + " from package " 8706 + p.info.packageName + " ignored: base tree " 8707 + tree.name + " is from package " 8708 + tree.sourcePackage); 8709 } 8710 } else { 8711 Slog.w(TAG, "Permission " + p.info.name + " from package " 8712 + p.info.packageName + " ignored: original from " 8713 + bp.sourcePackage); 8714 } 8715 } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8716 if (r == null) { 8717 r = new StringBuilder(256); 8718 } else { 8719 r.append(' '); 8720 } 8721 r.append("DUP:"); 8722 r.append(p.info.name); 8723 } 8724 if (bp.perm == p) { 8725 bp.protectionLevel = p.info.protectionLevel; 8726 } 8727 } 8728 8729 if (r != null) { 8730 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 8731 } 8732 8733 N = pkg.instrumentation.size(); 8734 r = null; 8735 for (i=0; i<N; i++) { 8736 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8737 a.info.packageName = pkg.applicationInfo.packageName; 8738 a.info.sourceDir = pkg.applicationInfo.sourceDir; 8739 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 8740 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 8741 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 8742 a.info.dataDir = pkg.applicationInfo.dataDir; 8743 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 8744 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 8745 8746 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 8747 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 8748 mInstrumentation.put(a.getComponentName(), a); 8749 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8750 if (r == null) { 8751 r = new StringBuilder(256); 8752 } else { 8753 r.append(' '); 8754 } 8755 r.append(a.info.name); 8756 } 8757 } 8758 if (r != null) { 8759 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 8760 } 8761 8762 if (pkg.protectedBroadcasts != null) { 8763 N = pkg.protectedBroadcasts.size(); 8764 for (i=0; i<N; i++) { 8765 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 8766 } 8767 } 8768 8769 pkgSetting.setTimeStamp(scanFileTime); 8770 8771 // Create idmap files for pairs of (packages, overlay packages). 8772 // Note: "android", ie framework-res.apk, is handled by native layers. 8773 if (pkg.mOverlayTarget != null) { 8774 // This is an overlay package. 8775 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 8776 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 8777 mOverlays.put(pkg.mOverlayTarget, 8778 new ArrayMap<String, PackageParser.Package>()); 8779 } 8780 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 8781 map.put(pkg.packageName, pkg); 8782 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 8783 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 8784 createIdmapFailed = true; 8785 } 8786 } 8787 } else if (mOverlays.containsKey(pkg.packageName) && 8788 !pkg.packageName.equals("android")) { 8789 // This is a regular package, with one or more known overlay packages. 8790 createIdmapsForPackageLI(pkg); 8791 } 8792 } 8793 8794 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8795 8796 if (createIdmapFailed) { 8797 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8798 "scanPackageLI failed to createIdmap"); 8799 } 8800 return pkg; 8801 } 8802 8803 /** 8804 * Derive the ABI of a non-system package located at {@code scanFile}. This information 8805 * is derived purely on the basis of the contents of {@code scanFile} and 8806 * {@code cpuAbiOverride}. 8807 * 8808 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 8809 */ 8810 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 8811 String cpuAbiOverride, boolean extractLibs) 8812 throws PackageManagerException { 8813 // TODO: We can probably be smarter about this stuff. For installed apps, 8814 // we can calculate this information at install time once and for all. For 8815 // system apps, we can probably assume that this information doesn't change 8816 // after the first boot scan. As things stand, we do lots of unnecessary work. 8817 8818 // Give ourselves some initial paths; we'll come back for another 8819 // pass once we've determined ABI below. 8820 setNativeLibraryPaths(pkg); 8821 8822 // We would never need to extract libs for forward-locked and external packages, 8823 // since the container service will do it for us. We shouldn't attempt to 8824 // extract libs from system app when it was not updated. 8825 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 8826 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 8827 extractLibs = false; 8828 } 8829 8830 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 8831 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 8832 8833 NativeLibraryHelper.Handle handle = null; 8834 try { 8835 handle = NativeLibraryHelper.Handle.create(pkg); 8836 // TODO(multiArch): This can be null for apps that didn't go through the 8837 // usual installation process. We can calculate it again, like we 8838 // do during install time. 8839 // 8840 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 8841 // unnecessary. 8842 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 8843 8844 // Null out the abis so that they can be recalculated. 8845 pkg.applicationInfo.primaryCpuAbi = null; 8846 pkg.applicationInfo.secondaryCpuAbi = null; 8847 if (isMultiArch(pkg.applicationInfo)) { 8848 // Warn if we've set an abiOverride for multi-lib packages.. 8849 // By definition, we need to copy both 32 and 64 bit libraries for 8850 // such packages. 8851 if (pkg.cpuAbiOverride != null 8852 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 8853 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 8854 } 8855 8856 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 8857 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 8858 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 8859 if (extractLibs) { 8860 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8861 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 8862 useIsaSpecificSubdirs); 8863 } else { 8864 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 8865 } 8866 } 8867 8868 maybeThrowExceptionForMultiArchCopy( 8869 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 8870 8871 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 8872 if (extractLibs) { 8873 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8874 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 8875 useIsaSpecificSubdirs); 8876 } else { 8877 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 8878 } 8879 } 8880 8881 maybeThrowExceptionForMultiArchCopy( 8882 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 8883 8884 if (abi64 >= 0) { 8885 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 8886 } 8887 8888 if (abi32 >= 0) { 8889 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 8890 if (abi64 >= 0) { 8891 if (pkg.use32bitAbi) { 8892 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 8893 pkg.applicationInfo.primaryCpuAbi = abi; 8894 } else { 8895 pkg.applicationInfo.secondaryCpuAbi = abi; 8896 } 8897 } else { 8898 pkg.applicationInfo.primaryCpuAbi = abi; 8899 } 8900 } 8901 8902 } else { 8903 String[] abiList = (cpuAbiOverride != null) ? 8904 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 8905 8906 // Enable gross and lame hacks for apps that are built with old 8907 // SDK tools. We must scan their APKs for renderscript bitcode and 8908 // not launch them if it's present. Don't bother checking on devices 8909 // that don't have 64 bit support. 8910 boolean needsRenderScriptOverride = false; 8911 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 8912 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 8913 abiList = Build.SUPPORTED_32_BIT_ABIS; 8914 needsRenderScriptOverride = true; 8915 } 8916 8917 final int copyRet; 8918 if (extractLibs) { 8919 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8920 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 8921 } else { 8922 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 8923 } 8924 8925 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 8926 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 8927 "Error unpackaging native libs for app, errorCode=" + copyRet); 8928 } 8929 8930 if (copyRet >= 0) { 8931 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 8932 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 8933 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 8934 } else if (needsRenderScriptOverride) { 8935 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 8936 } 8937 } 8938 } catch (IOException ioe) { 8939 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 8940 } finally { 8941 IoUtils.closeQuietly(handle); 8942 } 8943 8944 // Now that we've calculated the ABIs and determined if it's an internal app, 8945 // we will go ahead and populate the nativeLibraryPath. 8946 setNativeLibraryPaths(pkg); 8947 } 8948 8949 /** 8950 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 8951 * i.e, so that all packages can be run inside a single process if required. 8952 * 8953 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 8954 * this function will either try and make the ABI for all packages in {@code packagesForUser} 8955 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 8956 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 8957 * updating a package that belongs to a shared user. 8958 * 8959 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 8960 * adds unnecessary complexity. 8961 */ 8962 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 8963 PackageParser.Package scannedPackage, boolean bootComplete) { 8964 String requiredInstructionSet = null; 8965 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 8966 requiredInstructionSet = VMRuntime.getInstructionSet( 8967 scannedPackage.applicationInfo.primaryCpuAbi); 8968 } 8969 8970 PackageSetting requirer = null; 8971 for (PackageSetting ps : packagesForUser) { 8972 // If packagesForUser contains scannedPackage, we skip it. This will happen 8973 // when scannedPackage is an update of an existing package. Without this check, 8974 // we will never be able to change the ABI of any package belonging to a shared 8975 // user, even if it's compatible with other packages. 8976 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8977 if (ps.primaryCpuAbiString == null) { 8978 continue; 8979 } 8980 8981 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 8982 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 8983 // We have a mismatch between instruction sets (say arm vs arm64) warn about 8984 // this but there's not much we can do. 8985 String errorMessage = "Instruction set mismatch, " 8986 + ((requirer == null) ? "[caller]" : requirer) 8987 + " requires " + requiredInstructionSet + " whereas " + ps 8988 + " requires " + instructionSet; 8989 Slog.w(TAG, errorMessage); 8990 } 8991 8992 if (requiredInstructionSet == null) { 8993 requiredInstructionSet = instructionSet; 8994 requirer = ps; 8995 } 8996 } 8997 } 8998 8999 if (requiredInstructionSet != null) { 9000 String adjustedAbi; 9001 if (requirer != null) { 9002 // requirer != null implies that either scannedPackage was null or that scannedPackage 9003 // did not require an ABI, in which case we have to adjust scannedPackage to match 9004 // the ABI of the set (which is the same as requirer's ABI) 9005 adjustedAbi = requirer.primaryCpuAbiString; 9006 if (scannedPackage != null) { 9007 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 9008 } 9009 } else { 9010 // requirer == null implies that we're updating all ABIs in the set to 9011 // match scannedPackage. 9012 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 9013 } 9014 9015 for (PackageSetting ps : packagesForUser) { 9016 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9017 if (ps.primaryCpuAbiString != null) { 9018 continue; 9019 } 9020 9021 ps.primaryCpuAbiString = adjustedAbi; 9022 if (ps.pkg != null && ps.pkg.applicationInfo != null && 9023 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 9024 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 9025 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 9026 + " (requirer=" 9027 + (requirer == null ? "null" : requirer.pkg.packageName) 9028 + ", scannedPackage=" 9029 + (scannedPackage != null ? scannedPackage.packageName : "null") 9030 + ")"); 9031 try { 9032 mInstaller.rmdex(ps.codePathString, 9033 getDexCodeInstructionSet(getPreferredInstructionSet())); 9034 } catch (InstallerException ignored) { 9035 } 9036 } 9037 } 9038 } 9039 } 9040 } 9041 9042 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 9043 synchronized (mPackages) { 9044 mResolverReplaced = true; 9045 // Set up information for custom user intent resolution activity. 9046 mResolveActivity.applicationInfo = pkg.applicationInfo; 9047 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 9048 mResolveActivity.packageName = pkg.applicationInfo.packageName; 9049 mResolveActivity.processName = pkg.applicationInfo.packageName; 9050 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9051 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9052 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9053 mResolveActivity.theme = 0; 9054 mResolveActivity.exported = true; 9055 mResolveActivity.enabled = true; 9056 mResolveInfo.activityInfo = mResolveActivity; 9057 mResolveInfo.priority = 0; 9058 mResolveInfo.preferredOrder = 0; 9059 mResolveInfo.match = 0; 9060 mResolveComponentName = mCustomResolverComponentName; 9061 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 9062 mResolveComponentName); 9063 } 9064 } 9065 9066 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 9067 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 9068 9069 // Set up information for ephemeral installer activity 9070 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 9071 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 9072 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 9073 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 9074 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9075 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9076 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9077 mEphemeralInstallerActivity.theme = 0; 9078 mEphemeralInstallerActivity.exported = true; 9079 mEphemeralInstallerActivity.enabled = true; 9080 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 9081 mEphemeralInstallerInfo.priority = 0; 9082 mEphemeralInstallerInfo.preferredOrder = 0; 9083 mEphemeralInstallerInfo.match = 0; 9084 9085 if (DEBUG_EPHEMERAL) { 9086 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 9087 } 9088 } 9089 9090 private static String calculateBundledApkRoot(final String codePathString) { 9091 final File codePath = new File(codePathString); 9092 final File codeRoot; 9093 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 9094 codeRoot = Environment.getRootDirectory(); 9095 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 9096 codeRoot = Environment.getOemDirectory(); 9097 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 9098 codeRoot = Environment.getVendorDirectory(); 9099 } else { 9100 // Unrecognized code path; take its top real segment as the apk root: 9101 // e.g. /something/app/blah.apk => /something 9102 try { 9103 File f = codePath.getCanonicalFile(); 9104 File parent = f.getParentFile(); // non-null because codePath is a file 9105 File tmp; 9106 while ((tmp = parent.getParentFile()) != null) { 9107 f = parent; 9108 parent = tmp; 9109 } 9110 codeRoot = f; 9111 Slog.w(TAG, "Unrecognized code path " 9112 + codePath + " - using " + codeRoot); 9113 } catch (IOException e) { 9114 // Can't canonicalize the code path -- shenanigans? 9115 Slog.w(TAG, "Can't canonicalize code path " + codePath); 9116 return Environment.getRootDirectory().getPath(); 9117 } 9118 } 9119 return codeRoot.getPath(); 9120 } 9121 9122 /** 9123 * Derive and set the location of native libraries for the given package, 9124 * which varies depending on where and how the package was installed. 9125 */ 9126 private void setNativeLibraryPaths(PackageParser.Package pkg) { 9127 final ApplicationInfo info = pkg.applicationInfo; 9128 final String codePath = pkg.codePath; 9129 final File codeFile = new File(codePath); 9130 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 9131 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 9132 9133 info.nativeLibraryRootDir = null; 9134 info.nativeLibraryRootRequiresIsa = false; 9135 info.nativeLibraryDir = null; 9136 info.secondaryNativeLibraryDir = null; 9137 9138 if (isApkFile(codeFile)) { 9139 // Monolithic install 9140 if (bundledApp) { 9141 // If "/system/lib64/apkname" exists, assume that is the per-package 9142 // native library directory to use; otherwise use "/system/lib/apkname". 9143 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 9144 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 9145 getPrimaryInstructionSet(info)); 9146 9147 // This is a bundled system app so choose the path based on the ABI. 9148 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 9149 // is just the default path. 9150 final String apkName = deriveCodePathName(codePath); 9151 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 9152 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 9153 apkName).getAbsolutePath(); 9154 9155 if (info.secondaryCpuAbi != null) { 9156 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 9157 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 9158 secondaryLibDir, apkName).getAbsolutePath(); 9159 } 9160 } else if (asecApp) { 9161 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 9162 .getAbsolutePath(); 9163 } else { 9164 final String apkName = deriveCodePathName(codePath); 9165 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 9166 .getAbsolutePath(); 9167 } 9168 9169 info.nativeLibraryRootRequiresIsa = false; 9170 info.nativeLibraryDir = info.nativeLibraryRootDir; 9171 } else { 9172 // Cluster install 9173 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 9174 info.nativeLibraryRootRequiresIsa = true; 9175 9176 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 9177 getPrimaryInstructionSet(info)).getAbsolutePath(); 9178 9179 if (info.secondaryCpuAbi != null) { 9180 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 9181 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 9182 } 9183 } 9184 } 9185 9186 /** 9187 * Calculate the abis and roots for a bundled app. These can uniquely 9188 * be determined from the contents of the system partition, i.e whether 9189 * it contains 64 or 32 bit shared libraries etc. We do not validate any 9190 * of this information, and instead assume that the system was built 9191 * sensibly. 9192 */ 9193 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 9194 PackageSetting pkgSetting) { 9195 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 9196 9197 // If "/system/lib64/apkname" exists, assume that is the per-package 9198 // native library directory to use; otherwise use "/system/lib/apkname". 9199 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 9200 setBundledAppAbi(pkg, apkRoot, apkName); 9201 // pkgSetting might be null during rescan following uninstall of updates 9202 // to a bundled app, so accommodate that possibility. The settings in 9203 // that case will be established later from the parsed package. 9204 // 9205 // If the settings aren't null, sync them up with what we've just derived. 9206 // note that apkRoot isn't stored in the package settings. 9207 if (pkgSetting != null) { 9208 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9209 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9210 } 9211 } 9212 9213 /** 9214 * Deduces the ABI of a bundled app and sets the relevant fields on the 9215 * parsed pkg object. 9216 * 9217 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 9218 * under which system libraries are installed. 9219 * @param apkName the name of the installed package. 9220 */ 9221 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 9222 final File codeFile = new File(pkg.codePath); 9223 9224 final boolean has64BitLibs; 9225 final boolean has32BitLibs; 9226 if (isApkFile(codeFile)) { 9227 // Monolithic install 9228 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 9229 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 9230 } else { 9231 // Cluster install 9232 final File rootDir = new File(codeFile, LIB_DIR_NAME); 9233 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 9234 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 9235 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 9236 has64BitLibs = (new File(rootDir, isa)).exists(); 9237 } else { 9238 has64BitLibs = false; 9239 } 9240 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 9241 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 9242 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 9243 has32BitLibs = (new File(rootDir, isa)).exists(); 9244 } else { 9245 has32BitLibs = false; 9246 } 9247 } 9248 9249 if (has64BitLibs && !has32BitLibs) { 9250 // The package has 64 bit libs, but not 32 bit libs. Its primary 9251 // ABI should be 64 bit. We can safely assume here that the bundled 9252 // native libraries correspond to the most preferred ABI in the list. 9253 9254 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9255 pkg.applicationInfo.secondaryCpuAbi = null; 9256 } else if (has32BitLibs && !has64BitLibs) { 9257 // The package has 32 bit libs but not 64 bit libs. Its primary 9258 // ABI should be 32 bit. 9259 9260 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9261 pkg.applicationInfo.secondaryCpuAbi = null; 9262 } else if (has32BitLibs && has64BitLibs) { 9263 // The application has both 64 and 32 bit bundled libraries. We check 9264 // here that the app declares multiArch support, and warn if it doesn't. 9265 // 9266 // We will be lenient here and record both ABIs. The primary will be the 9267 // ABI that's higher on the list, i.e, a device that's configured to prefer 9268 // 64 bit apps will see a 64 bit primary ABI, 9269 9270 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 9271 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 9272 } 9273 9274 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 9275 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9276 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9277 } else { 9278 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9279 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9280 } 9281 } else { 9282 pkg.applicationInfo.primaryCpuAbi = null; 9283 pkg.applicationInfo.secondaryCpuAbi = null; 9284 } 9285 } 9286 9287 private void killApplication(String pkgName, int appId, String reason) { 9288 // Request the ActivityManager to kill the process(only for existing packages) 9289 // so that we do not end up in a confused state while the user is still using the older 9290 // version of the application while the new one gets installed. 9291 final long token = Binder.clearCallingIdentity(); 9292 try { 9293 IActivityManager am = ActivityManagerNative.getDefault(); 9294 if (am != null) { 9295 try { 9296 am.killApplicationWithAppId(pkgName, appId, reason); 9297 } catch (RemoteException e) { 9298 } 9299 } 9300 } finally { 9301 Binder.restoreCallingIdentity(token); 9302 } 9303 } 9304 9305 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 9306 // Remove the parent package setting 9307 PackageSetting ps = (PackageSetting) pkg.mExtras; 9308 if (ps != null) { 9309 removePackageLI(ps, chatty); 9310 } 9311 // Remove the child package setting 9312 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9313 for (int i = 0; i < childCount; i++) { 9314 PackageParser.Package childPkg = pkg.childPackages.get(i); 9315 ps = (PackageSetting) childPkg.mExtras; 9316 if (ps != null) { 9317 removePackageLI(ps, chatty); 9318 } 9319 } 9320 } 9321 9322 void removePackageLI(PackageSetting ps, boolean chatty) { 9323 if (DEBUG_INSTALL) { 9324 if (chatty) 9325 Log.d(TAG, "Removing package " + ps.name); 9326 } 9327 9328 // writer 9329 synchronized (mPackages) { 9330 mPackages.remove(ps.name); 9331 final PackageParser.Package pkg = ps.pkg; 9332 if (pkg != null) { 9333 cleanPackageDataStructuresLILPw(pkg, chatty); 9334 } 9335 } 9336 } 9337 9338 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 9339 if (DEBUG_INSTALL) { 9340 if (chatty) 9341 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 9342 } 9343 9344 // writer 9345 synchronized (mPackages) { 9346 // Remove the parent package 9347 mPackages.remove(pkg.applicationInfo.packageName); 9348 cleanPackageDataStructuresLILPw(pkg, chatty); 9349 9350 // Remove the child packages 9351 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9352 for (int i = 0; i < childCount; i++) { 9353 PackageParser.Package childPkg = pkg.childPackages.get(i); 9354 mPackages.remove(childPkg.applicationInfo.packageName); 9355 cleanPackageDataStructuresLILPw(childPkg, chatty); 9356 } 9357 } 9358 } 9359 9360 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 9361 int N = pkg.providers.size(); 9362 StringBuilder r = null; 9363 int i; 9364 for (i=0; i<N; i++) { 9365 PackageParser.Provider p = pkg.providers.get(i); 9366 mProviders.removeProvider(p); 9367 if (p.info.authority == null) { 9368 9369 /* There was another ContentProvider with this authority when 9370 * this app was installed so this authority is null, 9371 * Ignore it as we don't have to unregister the provider. 9372 */ 9373 continue; 9374 } 9375 String names[] = p.info.authority.split(";"); 9376 for (int j = 0; j < names.length; j++) { 9377 if (mProvidersByAuthority.get(names[j]) == p) { 9378 mProvidersByAuthority.remove(names[j]); 9379 if (DEBUG_REMOVE) { 9380 if (chatty) 9381 Log.d(TAG, "Unregistered content provider: " + names[j] 9382 + ", className = " + p.info.name + ", isSyncable = " 9383 + p.info.isSyncable); 9384 } 9385 } 9386 } 9387 if (DEBUG_REMOVE && chatty) { 9388 if (r == null) { 9389 r = new StringBuilder(256); 9390 } else { 9391 r.append(' '); 9392 } 9393 r.append(p.info.name); 9394 } 9395 } 9396 if (r != null) { 9397 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 9398 } 9399 9400 N = pkg.services.size(); 9401 r = null; 9402 for (i=0; i<N; i++) { 9403 PackageParser.Service s = pkg.services.get(i); 9404 mServices.removeService(s); 9405 if (chatty) { 9406 if (r == null) { 9407 r = new StringBuilder(256); 9408 } else { 9409 r.append(' '); 9410 } 9411 r.append(s.info.name); 9412 } 9413 } 9414 if (r != null) { 9415 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 9416 } 9417 9418 N = pkg.receivers.size(); 9419 r = null; 9420 for (i=0; i<N; i++) { 9421 PackageParser.Activity a = pkg.receivers.get(i); 9422 mReceivers.removeActivity(a, "receiver"); 9423 if (DEBUG_REMOVE && chatty) { 9424 if (r == null) { 9425 r = new StringBuilder(256); 9426 } else { 9427 r.append(' '); 9428 } 9429 r.append(a.info.name); 9430 } 9431 } 9432 if (r != null) { 9433 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 9434 } 9435 9436 N = pkg.activities.size(); 9437 r = null; 9438 for (i=0; i<N; i++) { 9439 PackageParser.Activity a = pkg.activities.get(i); 9440 mActivities.removeActivity(a, "activity"); 9441 if (DEBUG_REMOVE && chatty) { 9442 if (r == null) { 9443 r = new StringBuilder(256); 9444 } else { 9445 r.append(' '); 9446 } 9447 r.append(a.info.name); 9448 } 9449 } 9450 if (r != null) { 9451 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 9452 } 9453 9454 N = pkg.permissions.size(); 9455 r = null; 9456 for (i=0; i<N; i++) { 9457 PackageParser.Permission p = pkg.permissions.get(i); 9458 BasePermission bp = mSettings.mPermissions.get(p.info.name); 9459 if (bp == null) { 9460 bp = mSettings.mPermissionTrees.get(p.info.name); 9461 } 9462 if (bp != null && bp.perm == p) { 9463 bp.perm = null; 9464 if (DEBUG_REMOVE && chatty) { 9465 if (r == null) { 9466 r = new StringBuilder(256); 9467 } else { 9468 r.append(' '); 9469 } 9470 r.append(p.info.name); 9471 } 9472 } 9473 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9474 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 9475 if (appOpPkgs != null) { 9476 appOpPkgs.remove(pkg.packageName); 9477 } 9478 } 9479 } 9480 if (r != null) { 9481 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9482 } 9483 9484 N = pkg.requestedPermissions.size(); 9485 r = null; 9486 for (i=0; i<N; i++) { 9487 String perm = pkg.requestedPermissions.get(i); 9488 BasePermission bp = mSettings.mPermissions.get(perm); 9489 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9490 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 9491 if (appOpPkgs != null) { 9492 appOpPkgs.remove(pkg.packageName); 9493 if (appOpPkgs.isEmpty()) { 9494 mAppOpPermissionPackages.remove(perm); 9495 } 9496 } 9497 } 9498 } 9499 if (r != null) { 9500 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9501 } 9502 9503 N = pkg.instrumentation.size(); 9504 r = null; 9505 for (i=0; i<N; i++) { 9506 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9507 mInstrumentation.remove(a.getComponentName()); 9508 if (DEBUG_REMOVE && chatty) { 9509 if (r == null) { 9510 r = new StringBuilder(256); 9511 } else { 9512 r.append(' '); 9513 } 9514 r.append(a.info.name); 9515 } 9516 } 9517 if (r != null) { 9518 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9519 } 9520 9521 r = null; 9522 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9523 // Only system apps can hold shared libraries. 9524 if (pkg.libraryNames != null) { 9525 for (i=0; i<pkg.libraryNames.size(); i++) { 9526 String name = pkg.libraryNames.get(i); 9527 SharedLibraryEntry cur = mSharedLibraries.get(name); 9528 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9529 mSharedLibraries.remove(name); 9530 if (DEBUG_REMOVE && chatty) { 9531 if (r == null) { 9532 r = new StringBuilder(256); 9533 } else { 9534 r.append(' '); 9535 } 9536 r.append(name); 9537 } 9538 } 9539 } 9540 } 9541 } 9542 if (r != null) { 9543 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9544 } 9545 } 9546 9547 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9548 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9549 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9550 return true; 9551 } 9552 } 9553 return false; 9554 } 9555 9556 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9557 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9558 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9559 9560 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9561 // Update the parent permissions 9562 updatePermissionsLPw(pkg.packageName, pkg, flags); 9563 // Update the child permissions 9564 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9565 for (int i = 0; i < childCount; i++) { 9566 PackageParser.Package childPkg = pkg.childPackages.get(i); 9567 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9568 } 9569 } 9570 9571 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9572 int flags) { 9573 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9574 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9575 } 9576 9577 private void updatePermissionsLPw(String changingPkg, 9578 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9579 // Make sure there are no dangling permission trees. 9580 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9581 while (it.hasNext()) { 9582 final BasePermission bp = it.next(); 9583 if (bp.packageSetting == null) { 9584 // We may not yet have parsed the package, so just see if 9585 // we still know about its settings. 9586 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9587 } 9588 if (bp.packageSetting == null) { 9589 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9590 + " from package " + bp.sourcePackage); 9591 it.remove(); 9592 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9593 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9594 Slog.i(TAG, "Removing old permission tree: " + bp.name 9595 + " from package " + bp.sourcePackage); 9596 flags |= UPDATE_PERMISSIONS_ALL; 9597 it.remove(); 9598 } 9599 } 9600 } 9601 9602 // Make sure all dynamic permissions have been assigned to a package, 9603 // and make sure there are no dangling permissions. 9604 it = mSettings.mPermissions.values().iterator(); 9605 while (it.hasNext()) { 9606 final BasePermission bp = it.next(); 9607 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9608 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9609 + bp.name + " pkg=" + bp.sourcePackage 9610 + " info=" + bp.pendingInfo); 9611 if (bp.packageSetting == null && bp.pendingInfo != null) { 9612 final BasePermission tree = findPermissionTreeLP(bp.name); 9613 if (tree != null && tree.perm != null) { 9614 bp.packageSetting = tree.packageSetting; 9615 bp.perm = new PackageParser.Permission(tree.perm.owner, 9616 new PermissionInfo(bp.pendingInfo)); 9617 bp.perm.info.packageName = tree.perm.info.packageName; 9618 bp.perm.info.name = bp.name; 9619 bp.uid = tree.uid; 9620 } 9621 } 9622 } 9623 if (bp.packageSetting == null) { 9624 // We may not yet have parsed the package, so just see if 9625 // we still know about its settings. 9626 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9627 } 9628 if (bp.packageSetting == null) { 9629 Slog.w(TAG, "Removing dangling permission: " + bp.name 9630 + " from package " + bp.sourcePackage); 9631 it.remove(); 9632 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9633 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9634 Slog.i(TAG, "Removing old permission: " + bp.name 9635 + " from package " + bp.sourcePackage); 9636 flags |= UPDATE_PERMISSIONS_ALL; 9637 it.remove(); 9638 } 9639 } 9640 } 9641 9642 // Now update the permissions for all packages, in particular 9643 // replace the granted permissions of the system packages. 9644 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9645 for (PackageParser.Package pkg : mPackages.values()) { 9646 if (pkg != pkgInfo) { 9647 // Only replace for packages on requested volume 9648 final String volumeUuid = getVolumeUuidForPackage(pkg); 9649 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9650 && Objects.equals(replaceVolumeUuid, volumeUuid); 9651 grantPermissionsLPw(pkg, replace, changingPkg); 9652 } 9653 } 9654 } 9655 9656 if (pkgInfo != null) { 9657 // Only replace for packages on requested volume 9658 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9659 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9660 && Objects.equals(replaceVolumeUuid, volumeUuid); 9661 grantPermissionsLPw(pkgInfo, replace, changingPkg); 9662 } 9663 } 9664 9665 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 9666 String packageOfInterest) { 9667 // IMPORTANT: There are two types of permissions: install and runtime. 9668 // Install time permissions are granted when the app is installed to 9669 // all device users and users added in the future. Runtime permissions 9670 // are granted at runtime explicitly to specific users. Normal and signature 9671 // protected permissions are install time permissions. Dangerous permissions 9672 // are install permissions if the app's target SDK is Lollipop MR1 or older, 9673 // otherwise they are runtime permissions. This function does not manage 9674 // runtime permissions except for the case an app targeting Lollipop MR1 9675 // being upgraded to target a newer SDK, in which case dangerous permissions 9676 // are transformed from install time to runtime ones. 9677 9678 final PackageSetting ps = (PackageSetting) pkg.mExtras; 9679 if (ps == null) { 9680 return; 9681 } 9682 9683 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 9684 9685 PermissionsState permissionsState = ps.getPermissionsState(); 9686 PermissionsState origPermissions = permissionsState; 9687 9688 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 9689 9690 boolean runtimePermissionsRevoked = false; 9691 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 9692 9693 boolean changedInstallPermission = false; 9694 9695 if (replace) { 9696 ps.installPermissionsFixed = false; 9697 if (!ps.isSharedUser()) { 9698 origPermissions = new PermissionsState(permissionsState); 9699 permissionsState.reset(); 9700 } else { 9701 // We need to know only about runtime permission changes since the 9702 // calling code always writes the install permissions state but 9703 // the runtime ones are written only if changed. The only cases of 9704 // changed runtime permissions here are promotion of an install to 9705 // runtime and revocation of a runtime from a shared user. 9706 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 9707 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 9708 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 9709 runtimePermissionsRevoked = true; 9710 } 9711 } 9712 } 9713 9714 permissionsState.setGlobalGids(mGlobalGids); 9715 9716 final int N = pkg.requestedPermissions.size(); 9717 for (int i=0; i<N; i++) { 9718 final String name = pkg.requestedPermissions.get(i); 9719 final BasePermission bp = mSettings.mPermissions.get(name); 9720 9721 if (DEBUG_INSTALL) { 9722 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 9723 } 9724 9725 if (bp == null || bp.packageSetting == null) { 9726 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9727 Slog.w(TAG, "Unknown permission " + name 9728 + " in package " + pkg.packageName); 9729 } 9730 continue; 9731 } 9732 9733 final String perm = bp.name; 9734 boolean allowedSig = false; 9735 int grant = GRANT_DENIED; 9736 9737 // Keep track of app op permissions. 9738 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9739 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 9740 if (pkgs == null) { 9741 pkgs = new ArraySet<>(); 9742 mAppOpPermissionPackages.put(bp.name, pkgs); 9743 } 9744 pkgs.add(pkg.packageName); 9745 } 9746 9747 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 9748 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 9749 >= Build.VERSION_CODES.M; 9750 switch (level) { 9751 case PermissionInfo.PROTECTION_NORMAL: { 9752 // For all apps normal permissions are install time ones. 9753 grant = GRANT_INSTALL; 9754 } break; 9755 9756 case PermissionInfo.PROTECTION_DANGEROUS: { 9757 // If a permission review is required for legacy apps we represent 9758 // their permissions as always granted runtime ones since we need 9759 // to keep the review required permission flag per user while an 9760 // install permission's state is shared across all users. 9761 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 9762 // For legacy apps dangerous permissions are install time ones. 9763 grant = GRANT_INSTALL; 9764 } else if (origPermissions.hasInstallPermission(bp.name)) { 9765 // For legacy apps that became modern, install becomes runtime. 9766 grant = GRANT_UPGRADE; 9767 } else if (mPromoteSystemApps 9768 && isSystemApp(ps) 9769 && mExistingSystemPackages.contains(ps.name)) { 9770 // For legacy system apps, install becomes runtime. 9771 // We cannot check hasInstallPermission() for system apps since those 9772 // permissions were granted implicitly and not persisted pre-M. 9773 grant = GRANT_UPGRADE; 9774 } else { 9775 // For modern apps keep runtime permissions unchanged. 9776 grant = GRANT_RUNTIME; 9777 } 9778 } break; 9779 9780 case PermissionInfo.PROTECTION_SIGNATURE: { 9781 // For all apps signature permissions are install time ones. 9782 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 9783 if (allowedSig) { 9784 grant = GRANT_INSTALL; 9785 } 9786 } break; 9787 } 9788 9789 if (DEBUG_INSTALL) { 9790 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 9791 } 9792 9793 if (grant != GRANT_DENIED) { 9794 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 9795 // If this is an existing, non-system package, then 9796 // we can't add any new permissions to it. 9797 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 9798 // Except... if this is a permission that was added 9799 // to the platform (note: need to only do this when 9800 // updating the platform). 9801 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 9802 grant = GRANT_DENIED; 9803 } 9804 } 9805 } 9806 9807 switch (grant) { 9808 case GRANT_INSTALL: { 9809 // Revoke this as runtime permission to handle the case of 9810 // a runtime permission being downgraded to an install one. 9811 // Also in permission review mode we keep dangerous permissions 9812 // for legacy apps 9813 for (int userId : UserManagerService.getInstance().getUserIds()) { 9814 if (origPermissions.getRuntimePermissionState( 9815 bp.name, userId) != null) { 9816 // Revoke the runtime permission and clear the flags. 9817 origPermissions.revokeRuntimePermission(bp, userId); 9818 origPermissions.updatePermissionFlags(bp, userId, 9819 PackageManager.MASK_PERMISSION_FLAGS, 0); 9820 // If we revoked a permission permission, we have to write. 9821 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9822 changedRuntimePermissionUserIds, userId); 9823 } 9824 } 9825 // Grant an install permission. 9826 if (permissionsState.grantInstallPermission(bp) != 9827 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9828 changedInstallPermission = true; 9829 } 9830 } break; 9831 9832 case GRANT_RUNTIME: { 9833 // Grant previously granted runtime permissions. 9834 for (int userId : UserManagerService.getInstance().getUserIds()) { 9835 PermissionState permissionState = origPermissions 9836 .getRuntimePermissionState(bp.name, userId); 9837 int flags = permissionState != null 9838 ? permissionState.getFlags() : 0; 9839 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 9840 if (permissionsState.grantRuntimePermission(bp, userId) == 9841 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9842 // If we cannot put the permission as it was, we have to write. 9843 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9844 changedRuntimePermissionUserIds, userId); 9845 } 9846 // If the app supports runtime permissions no need for a review. 9847 if (Build.PERMISSIONS_REVIEW_REQUIRED 9848 && appSupportsRuntimePermissions 9849 && (flags & PackageManager 9850 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 9851 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 9852 // Since we changed the flags, we have to write. 9853 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9854 changedRuntimePermissionUserIds, userId); 9855 } 9856 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 9857 && !appSupportsRuntimePermissions) { 9858 // For legacy apps that need a permission review, every new 9859 // runtime permission is granted but it is pending a review. 9860 // We also need to review only platform defined runtime 9861 // permissions as these are the only ones the platform knows 9862 // how to disable the API to simulate revocation as legacy 9863 // apps don't expect to run with revoked permissions. 9864 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 9865 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 9866 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 9867 // We changed the flags, hence have to write. 9868 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9869 changedRuntimePermissionUserIds, userId); 9870 } 9871 } 9872 if (permissionsState.grantRuntimePermission(bp, userId) 9873 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 9874 // We changed the permission, hence have to write. 9875 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9876 changedRuntimePermissionUserIds, userId); 9877 } 9878 } 9879 // Propagate the permission flags. 9880 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 9881 } 9882 } break; 9883 9884 case GRANT_UPGRADE: { 9885 // Grant runtime permissions for a previously held install permission. 9886 PermissionState permissionState = origPermissions 9887 .getInstallPermissionState(bp.name); 9888 final int flags = permissionState != null ? permissionState.getFlags() : 0; 9889 9890 if (origPermissions.revokeInstallPermission(bp) 9891 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 9892 // We will be transferring the permission flags, so clear them. 9893 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 9894 PackageManager.MASK_PERMISSION_FLAGS, 0); 9895 changedInstallPermission = true; 9896 } 9897 9898 // If the permission is not to be promoted to runtime we ignore it and 9899 // also its other flags as they are not applicable to install permissions. 9900 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 9901 for (int userId : currentUserIds) { 9902 if (permissionsState.grantRuntimePermission(bp, userId) != 9903 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9904 // Transfer the permission flags. 9905 permissionsState.updatePermissionFlags(bp, userId, 9906 flags, flags); 9907 // If we granted the permission, we have to write. 9908 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9909 changedRuntimePermissionUserIds, userId); 9910 } 9911 } 9912 } 9913 } break; 9914 9915 default: { 9916 if (packageOfInterest == null 9917 || packageOfInterest.equals(pkg.packageName)) { 9918 Slog.w(TAG, "Not granting permission " + perm 9919 + " to package " + pkg.packageName 9920 + " because it was previously installed without"); 9921 } 9922 } break; 9923 } 9924 } else { 9925 if (permissionsState.revokeInstallPermission(bp) != 9926 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9927 // Also drop the permission flags. 9928 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 9929 PackageManager.MASK_PERMISSION_FLAGS, 0); 9930 changedInstallPermission = true; 9931 Slog.i(TAG, "Un-granting permission " + perm 9932 + " from package " + pkg.packageName 9933 + " (protectionLevel=" + bp.protectionLevel 9934 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9935 + ")"); 9936 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 9937 // Don't print warning for app op permissions, since it is fine for them 9938 // not to be granted, there is a UI for the user to decide. 9939 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9940 Slog.w(TAG, "Not granting permission " + perm 9941 + " to package " + pkg.packageName 9942 + " (protectionLevel=" + bp.protectionLevel 9943 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9944 + ")"); 9945 } 9946 } 9947 } 9948 } 9949 9950 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 9951 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 9952 // This is the first that we have heard about this package, so the 9953 // permissions we have now selected are fixed until explicitly 9954 // changed. 9955 ps.installPermissionsFixed = true; 9956 } 9957 9958 // Persist the runtime permissions state for users with changes. If permissions 9959 // were revoked because no app in the shared user declares them we have to 9960 // write synchronously to avoid losing runtime permissions state. 9961 for (int userId : changedRuntimePermissionUserIds) { 9962 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 9963 } 9964 9965 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9966 } 9967 9968 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 9969 boolean allowed = false; 9970 final int NP = PackageParser.NEW_PERMISSIONS.length; 9971 for (int ip=0; ip<NP; ip++) { 9972 final PackageParser.NewPermissionInfo npi 9973 = PackageParser.NEW_PERMISSIONS[ip]; 9974 if (npi.name.equals(perm) 9975 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 9976 allowed = true; 9977 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 9978 + pkg.packageName); 9979 break; 9980 } 9981 } 9982 return allowed; 9983 } 9984 9985 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 9986 BasePermission bp, PermissionsState origPermissions) { 9987 boolean allowed; 9988 allowed = (compareSignatures( 9989 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 9990 == PackageManager.SIGNATURE_MATCH) 9991 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 9992 == PackageManager.SIGNATURE_MATCH); 9993 if (!allowed && (bp.protectionLevel 9994 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 9995 if (isSystemApp(pkg)) { 9996 // For updated system applications, a system permission 9997 // is granted only if it had been defined by the original application. 9998 if (pkg.isUpdatedSystemApp()) { 9999 final PackageSetting sysPs = mSettings 10000 .getDisabledSystemPkgLPr(pkg.packageName); 10001 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 10002 // If the original was granted this permission, we take 10003 // that grant decision as read and propagate it to the 10004 // update. 10005 if (sysPs.isPrivileged()) { 10006 allowed = true; 10007 } 10008 } else { 10009 // The system apk may have been updated with an older 10010 // version of the one on the data partition, but which 10011 // granted a new system permission that it didn't have 10012 // before. In this case we do want to allow the app to 10013 // now get the new permission if the ancestral apk is 10014 // privileged to get it. 10015 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 10016 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 10017 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 10018 allowed = true; 10019 break; 10020 } 10021 } 10022 } 10023 // Also if a privileged parent package on the system image or any of 10024 // its children requested a privileged permission, the updated child 10025 // packages can also get the permission. 10026 if (pkg.parentPackage != null) { 10027 final PackageSetting disabledSysParentPs = mSettings 10028 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 10029 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 10030 && disabledSysParentPs.isPrivileged()) { 10031 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 10032 allowed = true; 10033 } else if (disabledSysParentPs.pkg.childPackages != null) { 10034 final int count = disabledSysParentPs.pkg.childPackages.size(); 10035 for (int i = 0; i < count; i++) { 10036 PackageParser.Package disabledSysChildPkg = 10037 disabledSysParentPs.pkg.childPackages.get(i); 10038 if (isPackageRequestingPermission(disabledSysChildPkg, 10039 perm)) { 10040 allowed = true; 10041 break; 10042 } 10043 } 10044 } 10045 } 10046 } 10047 } 10048 } else { 10049 allowed = isPrivilegedApp(pkg); 10050 } 10051 } 10052 } 10053 if (!allowed) { 10054 if (!allowed && (bp.protectionLevel 10055 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 10056 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 10057 // If this was a previously normal/dangerous permission that got moved 10058 // to a system permission as part of the runtime permission redesign, then 10059 // we still want to blindly grant it to old apps. 10060 allowed = true; 10061 } 10062 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 10063 && pkg.packageName.equals(mRequiredInstallerPackage)) { 10064 // If this permission is to be granted to the system installer and 10065 // this app is an installer, then it gets the permission. 10066 allowed = true; 10067 } 10068 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 10069 && pkg.packageName.equals(mRequiredVerifierPackage)) { 10070 // If this permission is to be granted to the system verifier and 10071 // this app is a verifier, then it gets the permission. 10072 allowed = true; 10073 } 10074 if (!allowed && (bp.protectionLevel 10075 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 10076 && isSystemApp(pkg)) { 10077 // Any pre-installed system app is allowed to get this permission. 10078 allowed = true; 10079 } 10080 if (!allowed && (bp.protectionLevel 10081 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 10082 // For development permissions, a development permission 10083 // is granted only if it was already granted. 10084 allowed = origPermissions.hasInstallPermission(perm); 10085 } 10086 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 10087 && pkg.packageName.equals(mSetupWizardPackage)) { 10088 // If this permission is to be granted to the system setup wizard and 10089 // this app is a setup wizard, then it gets the permission. 10090 allowed = true; 10091 } 10092 } 10093 return allowed; 10094 } 10095 10096 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 10097 final int permCount = pkg.requestedPermissions.size(); 10098 for (int j = 0; j < permCount; j++) { 10099 String requestedPermission = pkg.requestedPermissions.get(j); 10100 if (permission.equals(requestedPermission)) { 10101 return true; 10102 } 10103 } 10104 return false; 10105 } 10106 10107 final class ActivityIntentResolver 10108 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 10109 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10110 boolean defaultOnly, int userId) { 10111 if (!sUserManager.exists(userId)) return null; 10112 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10113 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10114 } 10115 10116 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10117 int userId) { 10118 if (!sUserManager.exists(userId)) return null; 10119 mFlags = flags; 10120 return super.queryIntent(intent, resolvedType, 10121 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10122 } 10123 10124 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10125 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 10126 if (!sUserManager.exists(userId)) return null; 10127 if (packageActivities == null) { 10128 return null; 10129 } 10130 mFlags = flags; 10131 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10132 final int N = packageActivities.size(); 10133 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 10134 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 10135 10136 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 10137 for (int i = 0; i < N; ++i) { 10138 intentFilters = packageActivities.get(i).intents; 10139 if (intentFilters != null && intentFilters.size() > 0) { 10140 PackageParser.ActivityIntentInfo[] array = 10141 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 10142 intentFilters.toArray(array); 10143 listCut.add(array); 10144 } 10145 } 10146 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10147 } 10148 10149 /** 10150 * Finds a privileged activity that matches the specified activity names. 10151 */ 10152 private PackageParser.Activity findMatchingActivity( 10153 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 10154 for (PackageParser.Activity sysActivity : activityList) { 10155 if (sysActivity.info.name.equals(activityInfo.name)) { 10156 return sysActivity; 10157 } 10158 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 10159 return sysActivity; 10160 } 10161 if (sysActivity.info.targetActivity != null) { 10162 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 10163 return sysActivity; 10164 } 10165 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 10166 return sysActivity; 10167 } 10168 } 10169 } 10170 return null; 10171 } 10172 10173 public class IterGenerator<E> { 10174 public Iterator<E> generate(ActivityIntentInfo info) { 10175 return null; 10176 } 10177 } 10178 10179 public class ActionIterGenerator extends IterGenerator<String> { 10180 @Override 10181 public Iterator<String> generate(ActivityIntentInfo info) { 10182 return info.actionsIterator(); 10183 } 10184 } 10185 10186 public class CategoriesIterGenerator extends IterGenerator<String> { 10187 @Override 10188 public Iterator<String> generate(ActivityIntentInfo info) { 10189 return info.categoriesIterator(); 10190 } 10191 } 10192 10193 public class SchemesIterGenerator extends IterGenerator<String> { 10194 @Override 10195 public Iterator<String> generate(ActivityIntentInfo info) { 10196 return info.schemesIterator(); 10197 } 10198 } 10199 10200 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 10201 @Override 10202 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 10203 return info.authoritiesIterator(); 10204 } 10205 } 10206 10207 /** 10208 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 10209 * MODIFIED. Do not pass in a list that should not be changed. 10210 */ 10211 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 10212 IterGenerator<T> generator, Iterator<T> searchIterator) { 10213 // loop through the set of actions; every one must be found in the intent filter 10214 while (searchIterator.hasNext()) { 10215 // we must have at least one filter in the list to consider a match 10216 if (intentList.size() == 0) { 10217 break; 10218 } 10219 10220 final T searchAction = searchIterator.next(); 10221 10222 // loop through the set of intent filters 10223 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 10224 while (intentIter.hasNext()) { 10225 final ActivityIntentInfo intentInfo = intentIter.next(); 10226 boolean selectionFound = false; 10227 10228 // loop through the intent filter's selection criteria; at least one 10229 // of them must match the searched criteria 10230 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 10231 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 10232 final T intentSelection = intentSelectionIter.next(); 10233 if (intentSelection != null && intentSelection.equals(searchAction)) { 10234 selectionFound = true; 10235 break; 10236 } 10237 } 10238 10239 // the selection criteria wasn't found in this filter's set; this filter 10240 // is not a potential match 10241 if (!selectionFound) { 10242 intentIter.remove(); 10243 } 10244 } 10245 } 10246 } 10247 10248 private boolean isProtectedAction(ActivityIntentInfo filter) { 10249 final Iterator<String> actionsIter = filter.actionsIterator(); 10250 while (actionsIter != null && actionsIter.hasNext()) { 10251 final String filterAction = actionsIter.next(); 10252 if (PROTECTED_ACTIONS.contains(filterAction)) { 10253 return true; 10254 } 10255 } 10256 return false; 10257 } 10258 10259 /** 10260 * Adjusts the priority of the given intent filter according to policy. 10261 * <p> 10262 * <ul> 10263 * <li>The priority for non privileged applications is capped to '0'</li> 10264 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 10265 * <li>The priority for unbundled updates to privileged applications is capped to the 10266 * priority defined on the system partition</li> 10267 * </ul> 10268 * <p> 10269 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 10270 * allowed to obtain any priority on any action. 10271 */ 10272 private void adjustPriority( 10273 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 10274 // nothing to do; priority is fine as-is 10275 if (intent.getPriority() <= 0) { 10276 return; 10277 } 10278 10279 final ActivityInfo activityInfo = intent.activity.info; 10280 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 10281 10282 final boolean privilegedApp = 10283 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 10284 if (!privilegedApp) { 10285 // non-privileged applications can never define a priority >0 10286 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 10287 + " package: " + applicationInfo.packageName 10288 + " activity: " + intent.activity.className 10289 + " origPrio: " + intent.getPriority()); 10290 intent.setPriority(0); 10291 return; 10292 } 10293 10294 if (systemActivities == null) { 10295 // the system package is not disabled; we're parsing the system partition 10296 if (isProtectedAction(intent)) { 10297 if (mDeferProtectedFilters) { 10298 // We can't deal with these just yet. No component should ever obtain a 10299 // >0 priority for a protected actions, with ONE exception -- the setup 10300 // wizard. The setup wizard, however, cannot be known until we're able to 10301 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 10302 // until all intent filters have been processed. Chicken, meet egg. 10303 // Let the filter temporarily have a high priority and rectify the 10304 // priorities after all system packages have been scanned. 10305 mProtectedFilters.add(intent); 10306 if (DEBUG_FILTERS) { 10307 Slog.i(TAG, "Protected action; save for later;" 10308 + " package: " + applicationInfo.packageName 10309 + " activity: " + intent.activity.className 10310 + " origPrio: " + intent.getPriority()); 10311 } 10312 return; 10313 } else { 10314 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 10315 Slog.i(TAG, "No setup wizard;" 10316 + " All protected intents capped to priority 0"); 10317 } 10318 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 10319 if (DEBUG_FILTERS) { 10320 Slog.i(TAG, "Found setup wizard;" 10321 + " allow priority " + intent.getPriority() + ";" 10322 + " package: " + intent.activity.info.packageName 10323 + " activity: " + intent.activity.className 10324 + " priority: " + intent.getPriority()); 10325 } 10326 // setup wizard gets whatever it wants 10327 return; 10328 } 10329 Slog.w(TAG, "Protected action; cap priority to 0;" 10330 + " package: " + intent.activity.info.packageName 10331 + " activity: " + intent.activity.className 10332 + " origPrio: " + intent.getPriority()); 10333 intent.setPriority(0); 10334 return; 10335 } 10336 } 10337 // privileged apps on the system image get whatever priority they request 10338 return; 10339 } 10340 10341 // privileged app unbundled update ... try to find the same activity 10342 final PackageParser.Activity foundActivity = 10343 findMatchingActivity(systemActivities, activityInfo); 10344 if (foundActivity == null) { 10345 // this is a new activity; it cannot obtain >0 priority 10346 if (DEBUG_FILTERS) { 10347 Slog.i(TAG, "New activity; cap priority to 0;" 10348 + " package: " + applicationInfo.packageName 10349 + " activity: " + intent.activity.className 10350 + " origPrio: " + intent.getPriority()); 10351 } 10352 intent.setPriority(0); 10353 return; 10354 } 10355 10356 // found activity, now check for filter equivalence 10357 10358 // a shallow copy is enough; we modify the list, not its contents 10359 final List<ActivityIntentInfo> intentListCopy = 10360 new ArrayList<>(foundActivity.intents); 10361 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 10362 10363 // find matching action subsets 10364 final Iterator<String> actionsIterator = intent.actionsIterator(); 10365 if (actionsIterator != null) { 10366 getIntentListSubset( 10367 intentListCopy, new ActionIterGenerator(), actionsIterator); 10368 if (intentListCopy.size() == 0) { 10369 // no more intents to match; we're not equivalent 10370 if (DEBUG_FILTERS) { 10371 Slog.i(TAG, "Mismatched action; cap priority to 0;" 10372 + " package: " + applicationInfo.packageName 10373 + " activity: " + intent.activity.className 10374 + " origPrio: " + intent.getPriority()); 10375 } 10376 intent.setPriority(0); 10377 return; 10378 } 10379 } 10380 10381 // find matching category subsets 10382 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 10383 if (categoriesIterator != null) { 10384 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 10385 categoriesIterator); 10386 if (intentListCopy.size() == 0) { 10387 // no more intents to match; we're not equivalent 10388 if (DEBUG_FILTERS) { 10389 Slog.i(TAG, "Mismatched category; cap priority to 0;" 10390 + " package: " + applicationInfo.packageName 10391 + " activity: " + intent.activity.className 10392 + " origPrio: " + intent.getPriority()); 10393 } 10394 intent.setPriority(0); 10395 return; 10396 } 10397 } 10398 10399 // find matching schemes subsets 10400 final Iterator<String> schemesIterator = intent.schemesIterator(); 10401 if (schemesIterator != null) { 10402 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 10403 schemesIterator); 10404 if (intentListCopy.size() == 0) { 10405 // no more intents to match; we're not equivalent 10406 if (DEBUG_FILTERS) { 10407 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 10408 + " package: " + applicationInfo.packageName 10409 + " activity: " + intent.activity.className 10410 + " origPrio: " + intent.getPriority()); 10411 } 10412 intent.setPriority(0); 10413 return; 10414 } 10415 } 10416 10417 // find matching authorities subsets 10418 final Iterator<IntentFilter.AuthorityEntry> 10419 authoritiesIterator = intent.authoritiesIterator(); 10420 if (authoritiesIterator != null) { 10421 getIntentListSubset(intentListCopy, 10422 new AuthoritiesIterGenerator(), 10423 authoritiesIterator); 10424 if (intentListCopy.size() == 0) { 10425 // no more intents to match; we're not equivalent 10426 if (DEBUG_FILTERS) { 10427 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 10428 + " package: " + applicationInfo.packageName 10429 + " activity: " + intent.activity.className 10430 + " origPrio: " + intent.getPriority()); 10431 } 10432 intent.setPriority(0); 10433 return; 10434 } 10435 } 10436 10437 // we found matching filter(s); app gets the max priority of all intents 10438 int cappedPriority = 0; 10439 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 10440 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 10441 } 10442 if (intent.getPriority() > cappedPriority) { 10443 if (DEBUG_FILTERS) { 10444 Slog.i(TAG, "Found matching filter(s);" 10445 + " cap priority to " + cappedPriority + ";" 10446 + " package: " + applicationInfo.packageName 10447 + " activity: " + intent.activity.className 10448 + " origPrio: " + intent.getPriority()); 10449 } 10450 intent.setPriority(cappedPriority); 10451 return; 10452 } 10453 // all this for nothing; the requested priority was <= what was on the system 10454 } 10455 10456 public final void addActivity(PackageParser.Activity a, String type) { 10457 mActivities.put(a.getComponentName(), a); 10458 if (DEBUG_SHOW_INFO) 10459 Log.v( 10460 TAG, " " + type + " " + 10461 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 10462 if (DEBUG_SHOW_INFO) 10463 Log.v(TAG, " Class=" + a.info.name); 10464 final int NI = a.intents.size(); 10465 for (int j=0; j<NI; j++) { 10466 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10467 if ("activity".equals(type)) { 10468 final PackageSetting ps = 10469 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 10470 final List<PackageParser.Activity> systemActivities = 10471 ps != null && ps.pkg != null ? ps.pkg.activities : null; 10472 adjustPriority(systemActivities, intent); 10473 } 10474 if (DEBUG_SHOW_INFO) { 10475 Log.v(TAG, " IntentFilter:"); 10476 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10477 } 10478 if (!intent.debugCheck()) { 10479 Log.w(TAG, "==> For Activity " + a.info.name); 10480 } 10481 addFilter(intent); 10482 } 10483 } 10484 10485 public final void removeActivity(PackageParser.Activity a, String type) { 10486 mActivities.remove(a.getComponentName()); 10487 if (DEBUG_SHOW_INFO) { 10488 Log.v(TAG, " " + type + " " 10489 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 10490 : a.info.name) + ":"); 10491 Log.v(TAG, " Class=" + a.info.name); 10492 } 10493 final int NI = a.intents.size(); 10494 for (int j=0; j<NI; j++) { 10495 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10496 if (DEBUG_SHOW_INFO) { 10497 Log.v(TAG, " IntentFilter:"); 10498 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10499 } 10500 removeFilter(intent); 10501 } 10502 } 10503 10504 @Override 10505 protected boolean allowFilterResult( 10506 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 10507 ActivityInfo filterAi = filter.activity.info; 10508 for (int i=dest.size()-1; i>=0; i--) { 10509 ActivityInfo destAi = dest.get(i).activityInfo; 10510 if (destAi.name == filterAi.name 10511 && destAi.packageName == filterAi.packageName) { 10512 return false; 10513 } 10514 } 10515 return true; 10516 } 10517 10518 @Override 10519 protected ActivityIntentInfo[] newArray(int size) { 10520 return new ActivityIntentInfo[size]; 10521 } 10522 10523 @Override 10524 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 10525 if (!sUserManager.exists(userId)) return true; 10526 PackageParser.Package p = filter.activity.owner; 10527 if (p != null) { 10528 PackageSetting ps = (PackageSetting)p.mExtras; 10529 if (ps != null) { 10530 // System apps are never considered stopped for purposes of 10531 // filtering, because there may be no way for the user to 10532 // actually re-launch them. 10533 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 10534 && ps.getStopped(userId); 10535 } 10536 } 10537 return false; 10538 } 10539 10540 @Override 10541 protected boolean isPackageForFilter(String packageName, 10542 PackageParser.ActivityIntentInfo info) { 10543 return packageName.equals(info.activity.owner.packageName); 10544 } 10545 10546 @Override 10547 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 10548 int match, int userId) { 10549 if (!sUserManager.exists(userId)) return null; 10550 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 10551 return null; 10552 } 10553 final PackageParser.Activity activity = info.activity; 10554 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 10555 if (ps == null) { 10556 return null; 10557 } 10558 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 10559 ps.readUserState(userId), userId); 10560 if (ai == null) { 10561 return null; 10562 } 10563 final ResolveInfo res = new ResolveInfo(); 10564 res.activityInfo = ai; 10565 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10566 res.filter = info; 10567 } 10568 if (info != null) { 10569 res.handleAllWebDataURI = info.handleAllWebDataURI(); 10570 } 10571 res.priority = info.getPriority(); 10572 res.preferredOrder = activity.owner.mPreferredOrder; 10573 //System.out.println("Result: " + res.activityInfo.className + 10574 // " = " + res.priority); 10575 res.match = match; 10576 res.isDefault = info.hasDefault; 10577 res.labelRes = info.labelRes; 10578 res.nonLocalizedLabel = info.nonLocalizedLabel; 10579 if (userNeedsBadging(userId)) { 10580 res.noResourceId = true; 10581 } else { 10582 res.icon = info.icon; 10583 } 10584 res.iconResourceId = info.icon; 10585 res.system = res.activityInfo.applicationInfo.isSystemApp(); 10586 return res; 10587 } 10588 10589 @Override 10590 protected void sortResults(List<ResolveInfo> results) { 10591 Collections.sort(results, mResolvePrioritySorter); 10592 } 10593 10594 @Override 10595 protected void dumpFilter(PrintWriter out, String prefix, 10596 PackageParser.ActivityIntentInfo filter) { 10597 out.print(prefix); out.print( 10598 Integer.toHexString(System.identityHashCode(filter.activity))); 10599 out.print(' '); 10600 filter.activity.printComponentShortName(out); 10601 out.print(" filter "); 10602 out.println(Integer.toHexString(System.identityHashCode(filter))); 10603 } 10604 10605 @Override 10606 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 10607 return filter.activity; 10608 } 10609 10610 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10611 PackageParser.Activity activity = (PackageParser.Activity)label; 10612 out.print(prefix); out.print( 10613 Integer.toHexString(System.identityHashCode(activity))); 10614 out.print(' '); 10615 activity.printComponentShortName(out); 10616 if (count > 1) { 10617 out.print(" ("); out.print(count); out.print(" filters)"); 10618 } 10619 out.println(); 10620 } 10621 10622 // Keys are String (activity class name), values are Activity. 10623 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 10624 = new ArrayMap<ComponentName, PackageParser.Activity>(); 10625 private int mFlags; 10626 } 10627 10628 private final class ServiceIntentResolver 10629 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 10630 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10631 boolean defaultOnly, int userId) { 10632 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10633 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10634 } 10635 10636 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10637 int userId) { 10638 if (!sUserManager.exists(userId)) return null; 10639 mFlags = flags; 10640 return super.queryIntent(intent, resolvedType, 10641 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10642 } 10643 10644 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10645 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 10646 if (!sUserManager.exists(userId)) return null; 10647 if (packageServices == null) { 10648 return null; 10649 } 10650 mFlags = flags; 10651 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10652 final int N = packageServices.size(); 10653 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 10654 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 10655 10656 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 10657 for (int i = 0; i < N; ++i) { 10658 intentFilters = packageServices.get(i).intents; 10659 if (intentFilters != null && intentFilters.size() > 0) { 10660 PackageParser.ServiceIntentInfo[] array = 10661 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 10662 intentFilters.toArray(array); 10663 listCut.add(array); 10664 } 10665 } 10666 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10667 } 10668 10669 public final void addService(PackageParser.Service s) { 10670 mServices.put(s.getComponentName(), s); 10671 if (DEBUG_SHOW_INFO) { 10672 Log.v(TAG, " " 10673 + (s.info.nonLocalizedLabel != null 10674 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10675 Log.v(TAG, " Class=" + s.info.name); 10676 } 10677 final int NI = s.intents.size(); 10678 int j; 10679 for (j=0; j<NI; j++) { 10680 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10681 if (DEBUG_SHOW_INFO) { 10682 Log.v(TAG, " IntentFilter:"); 10683 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10684 } 10685 if (!intent.debugCheck()) { 10686 Log.w(TAG, "==> For Service " + s.info.name); 10687 } 10688 addFilter(intent); 10689 } 10690 } 10691 10692 public final void removeService(PackageParser.Service s) { 10693 mServices.remove(s.getComponentName()); 10694 if (DEBUG_SHOW_INFO) { 10695 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 10696 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10697 Log.v(TAG, " Class=" + s.info.name); 10698 } 10699 final int NI = s.intents.size(); 10700 int j; 10701 for (j=0; j<NI; j++) { 10702 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10703 if (DEBUG_SHOW_INFO) { 10704 Log.v(TAG, " IntentFilter:"); 10705 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10706 } 10707 removeFilter(intent); 10708 } 10709 } 10710 10711 @Override 10712 protected boolean allowFilterResult( 10713 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 10714 ServiceInfo filterSi = filter.service.info; 10715 for (int i=dest.size()-1; i>=0; i--) { 10716 ServiceInfo destAi = dest.get(i).serviceInfo; 10717 if (destAi.name == filterSi.name 10718 && destAi.packageName == filterSi.packageName) { 10719 return false; 10720 } 10721 } 10722 return true; 10723 } 10724 10725 @Override 10726 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 10727 return new PackageParser.ServiceIntentInfo[size]; 10728 } 10729 10730 @Override 10731 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 10732 if (!sUserManager.exists(userId)) return true; 10733 PackageParser.Package p = filter.service.owner; 10734 if (p != null) { 10735 PackageSetting ps = (PackageSetting)p.mExtras; 10736 if (ps != null) { 10737 // System apps are never considered stopped for purposes of 10738 // filtering, because there may be no way for the user to 10739 // actually re-launch them. 10740 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10741 && ps.getStopped(userId); 10742 } 10743 } 10744 return false; 10745 } 10746 10747 @Override 10748 protected boolean isPackageForFilter(String packageName, 10749 PackageParser.ServiceIntentInfo info) { 10750 return packageName.equals(info.service.owner.packageName); 10751 } 10752 10753 @Override 10754 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 10755 int match, int userId) { 10756 if (!sUserManager.exists(userId)) return null; 10757 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 10758 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 10759 return null; 10760 } 10761 final PackageParser.Service service = info.service; 10762 PackageSetting ps = (PackageSetting) service.owner.mExtras; 10763 if (ps == null) { 10764 return null; 10765 } 10766 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 10767 ps.readUserState(userId), userId); 10768 if (si == null) { 10769 return null; 10770 } 10771 final ResolveInfo res = new ResolveInfo(); 10772 res.serviceInfo = si; 10773 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10774 res.filter = filter; 10775 } 10776 res.priority = info.getPriority(); 10777 res.preferredOrder = service.owner.mPreferredOrder; 10778 res.match = match; 10779 res.isDefault = info.hasDefault; 10780 res.labelRes = info.labelRes; 10781 res.nonLocalizedLabel = info.nonLocalizedLabel; 10782 res.icon = info.icon; 10783 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 10784 return res; 10785 } 10786 10787 @Override 10788 protected void sortResults(List<ResolveInfo> results) { 10789 Collections.sort(results, mResolvePrioritySorter); 10790 } 10791 10792 @Override 10793 protected void dumpFilter(PrintWriter out, String prefix, 10794 PackageParser.ServiceIntentInfo filter) { 10795 out.print(prefix); out.print( 10796 Integer.toHexString(System.identityHashCode(filter.service))); 10797 out.print(' '); 10798 filter.service.printComponentShortName(out); 10799 out.print(" filter "); 10800 out.println(Integer.toHexString(System.identityHashCode(filter))); 10801 } 10802 10803 @Override 10804 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 10805 return filter.service; 10806 } 10807 10808 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10809 PackageParser.Service service = (PackageParser.Service)label; 10810 out.print(prefix); out.print( 10811 Integer.toHexString(System.identityHashCode(service))); 10812 out.print(' '); 10813 service.printComponentShortName(out); 10814 if (count > 1) { 10815 out.print(" ("); out.print(count); out.print(" filters)"); 10816 } 10817 out.println(); 10818 } 10819 10820// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 10821// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 10822// final List<ResolveInfo> retList = Lists.newArrayList(); 10823// while (i.hasNext()) { 10824// final ResolveInfo resolveInfo = (ResolveInfo) i; 10825// if (isEnabledLP(resolveInfo.serviceInfo)) { 10826// retList.add(resolveInfo); 10827// } 10828// } 10829// return retList; 10830// } 10831 10832 // Keys are String (activity class name), values are Activity. 10833 private final ArrayMap<ComponentName, PackageParser.Service> mServices 10834 = new ArrayMap<ComponentName, PackageParser.Service>(); 10835 private int mFlags; 10836 }; 10837 10838 private final class ProviderIntentResolver 10839 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 10840 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10841 boolean defaultOnly, int userId) { 10842 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10843 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10844 } 10845 10846 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10847 int userId) { 10848 if (!sUserManager.exists(userId)) 10849 return null; 10850 mFlags = flags; 10851 return super.queryIntent(intent, resolvedType, 10852 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10853 } 10854 10855 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10856 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 10857 if (!sUserManager.exists(userId)) 10858 return null; 10859 if (packageProviders == null) { 10860 return null; 10861 } 10862 mFlags = flags; 10863 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 10864 final int N = packageProviders.size(); 10865 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 10866 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 10867 10868 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 10869 for (int i = 0; i < N; ++i) { 10870 intentFilters = packageProviders.get(i).intents; 10871 if (intentFilters != null && intentFilters.size() > 0) { 10872 PackageParser.ProviderIntentInfo[] array = 10873 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 10874 intentFilters.toArray(array); 10875 listCut.add(array); 10876 } 10877 } 10878 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10879 } 10880 10881 public final void addProvider(PackageParser.Provider p) { 10882 if (mProviders.containsKey(p.getComponentName())) { 10883 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 10884 return; 10885 } 10886 10887 mProviders.put(p.getComponentName(), p); 10888 if (DEBUG_SHOW_INFO) { 10889 Log.v(TAG, " " 10890 + (p.info.nonLocalizedLabel != null 10891 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10892 Log.v(TAG, " Class=" + p.info.name); 10893 } 10894 final int NI = p.intents.size(); 10895 int j; 10896 for (j = 0; j < NI; j++) { 10897 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10898 if (DEBUG_SHOW_INFO) { 10899 Log.v(TAG, " IntentFilter:"); 10900 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10901 } 10902 if (!intent.debugCheck()) { 10903 Log.w(TAG, "==> For Provider " + p.info.name); 10904 } 10905 addFilter(intent); 10906 } 10907 } 10908 10909 public final void removeProvider(PackageParser.Provider p) { 10910 mProviders.remove(p.getComponentName()); 10911 if (DEBUG_SHOW_INFO) { 10912 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 10913 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10914 Log.v(TAG, " Class=" + p.info.name); 10915 } 10916 final int NI = p.intents.size(); 10917 int j; 10918 for (j = 0; j < NI; j++) { 10919 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10920 if (DEBUG_SHOW_INFO) { 10921 Log.v(TAG, " IntentFilter:"); 10922 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10923 } 10924 removeFilter(intent); 10925 } 10926 } 10927 10928 @Override 10929 protected boolean allowFilterResult( 10930 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 10931 ProviderInfo filterPi = filter.provider.info; 10932 for (int i = dest.size() - 1; i >= 0; i--) { 10933 ProviderInfo destPi = dest.get(i).providerInfo; 10934 if (destPi.name == filterPi.name 10935 && destPi.packageName == filterPi.packageName) { 10936 return false; 10937 } 10938 } 10939 return true; 10940 } 10941 10942 @Override 10943 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 10944 return new PackageParser.ProviderIntentInfo[size]; 10945 } 10946 10947 @Override 10948 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 10949 if (!sUserManager.exists(userId)) 10950 return true; 10951 PackageParser.Package p = filter.provider.owner; 10952 if (p != null) { 10953 PackageSetting ps = (PackageSetting) p.mExtras; 10954 if (ps != null) { 10955 // System apps are never considered stopped for purposes of 10956 // filtering, because there may be no way for the user to 10957 // actually re-launch them. 10958 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10959 && ps.getStopped(userId); 10960 } 10961 } 10962 return false; 10963 } 10964 10965 @Override 10966 protected boolean isPackageForFilter(String packageName, 10967 PackageParser.ProviderIntentInfo info) { 10968 return packageName.equals(info.provider.owner.packageName); 10969 } 10970 10971 @Override 10972 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 10973 int match, int userId) { 10974 if (!sUserManager.exists(userId)) 10975 return null; 10976 final PackageParser.ProviderIntentInfo info = filter; 10977 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 10978 return null; 10979 } 10980 final PackageParser.Provider provider = info.provider; 10981 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 10982 if (ps == null) { 10983 return null; 10984 } 10985 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 10986 ps.readUserState(userId), userId); 10987 if (pi == null) { 10988 return null; 10989 } 10990 final ResolveInfo res = new ResolveInfo(); 10991 res.providerInfo = pi; 10992 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 10993 res.filter = filter; 10994 } 10995 res.priority = info.getPriority(); 10996 res.preferredOrder = provider.owner.mPreferredOrder; 10997 res.match = match; 10998 res.isDefault = info.hasDefault; 10999 res.labelRes = info.labelRes; 11000 res.nonLocalizedLabel = info.nonLocalizedLabel; 11001 res.icon = info.icon; 11002 res.system = res.providerInfo.applicationInfo.isSystemApp(); 11003 return res; 11004 } 11005 11006 @Override 11007 protected void sortResults(List<ResolveInfo> results) { 11008 Collections.sort(results, mResolvePrioritySorter); 11009 } 11010 11011 @Override 11012 protected void dumpFilter(PrintWriter out, String prefix, 11013 PackageParser.ProviderIntentInfo filter) { 11014 out.print(prefix); 11015 out.print( 11016 Integer.toHexString(System.identityHashCode(filter.provider))); 11017 out.print(' '); 11018 filter.provider.printComponentShortName(out); 11019 out.print(" filter "); 11020 out.println(Integer.toHexString(System.identityHashCode(filter))); 11021 } 11022 11023 @Override 11024 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 11025 return filter.provider; 11026 } 11027 11028 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11029 PackageParser.Provider provider = (PackageParser.Provider)label; 11030 out.print(prefix); out.print( 11031 Integer.toHexString(System.identityHashCode(provider))); 11032 out.print(' '); 11033 provider.printComponentShortName(out); 11034 if (count > 1) { 11035 out.print(" ("); out.print(count); out.print(" filters)"); 11036 } 11037 out.println(); 11038 } 11039 11040 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 11041 = new ArrayMap<ComponentName, PackageParser.Provider>(); 11042 private int mFlags; 11043 } 11044 11045 private static final class EphemeralIntentResolver 11046 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 11047 @Override 11048 protected EphemeralResolveIntentInfo[] newArray(int size) { 11049 return new EphemeralResolveIntentInfo[size]; 11050 } 11051 11052 @Override 11053 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 11054 return true; 11055 } 11056 11057 @Override 11058 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 11059 int userId) { 11060 if (!sUserManager.exists(userId)) { 11061 return null; 11062 } 11063 return info.getEphemeralResolveInfo(); 11064 } 11065 } 11066 11067 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 11068 new Comparator<ResolveInfo>() { 11069 public int compare(ResolveInfo r1, ResolveInfo r2) { 11070 int v1 = r1.priority; 11071 int v2 = r2.priority; 11072 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 11073 if (v1 != v2) { 11074 return (v1 > v2) ? -1 : 1; 11075 } 11076 v1 = r1.preferredOrder; 11077 v2 = r2.preferredOrder; 11078 if (v1 != v2) { 11079 return (v1 > v2) ? -1 : 1; 11080 } 11081 if (r1.isDefault != r2.isDefault) { 11082 return r1.isDefault ? -1 : 1; 11083 } 11084 v1 = r1.match; 11085 v2 = r2.match; 11086 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 11087 if (v1 != v2) { 11088 return (v1 > v2) ? -1 : 1; 11089 } 11090 if (r1.system != r2.system) { 11091 return r1.system ? -1 : 1; 11092 } 11093 if (r1.activityInfo != null) { 11094 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 11095 } 11096 if (r1.serviceInfo != null) { 11097 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 11098 } 11099 if (r1.providerInfo != null) { 11100 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 11101 } 11102 return 0; 11103 } 11104 }; 11105 11106 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 11107 new Comparator<ProviderInfo>() { 11108 public int compare(ProviderInfo p1, ProviderInfo p2) { 11109 final int v1 = p1.initOrder; 11110 final int v2 = p2.initOrder; 11111 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 11112 } 11113 }; 11114 11115 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 11116 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 11117 final int[] userIds) { 11118 mHandler.post(new Runnable() { 11119 @Override 11120 public void run() { 11121 try { 11122 final IActivityManager am = ActivityManagerNative.getDefault(); 11123 if (am == null) return; 11124 final int[] resolvedUserIds; 11125 if (userIds == null) { 11126 resolvedUserIds = am.getRunningUserIds(); 11127 } else { 11128 resolvedUserIds = userIds; 11129 } 11130 for (int id : resolvedUserIds) { 11131 final Intent intent = new Intent(action, 11132 pkg != null ? Uri.fromParts("package", pkg, null) : null); 11133 if (extras != null) { 11134 intent.putExtras(extras); 11135 } 11136 if (targetPkg != null) { 11137 intent.setPackage(targetPkg); 11138 } 11139 // Modify the UID when posting to other users 11140 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 11141 if (uid > 0 && UserHandle.getUserId(uid) != id) { 11142 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 11143 intent.putExtra(Intent.EXTRA_UID, uid); 11144 } 11145 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 11146 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 11147 if (DEBUG_BROADCASTS) { 11148 RuntimeException here = new RuntimeException("here"); 11149 here.fillInStackTrace(); 11150 Slog.d(TAG, "Sending to user " + id + ": " 11151 + intent.toShortString(false, true, false, false) 11152 + " " + intent.getExtras(), here); 11153 } 11154 am.broadcastIntent(null, intent, null, finishedReceiver, 11155 0, null, null, null, android.app.AppOpsManager.OP_NONE, 11156 null, finishedReceiver != null, false, id); 11157 } 11158 } catch (RemoteException ex) { 11159 } 11160 } 11161 }); 11162 } 11163 11164 /** 11165 * Check if the external storage media is available. This is true if there 11166 * is a mounted external storage medium or if the external storage is 11167 * emulated. 11168 */ 11169 private boolean isExternalMediaAvailable() { 11170 return mMediaMounted || Environment.isExternalStorageEmulated(); 11171 } 11172 11173 @Override 11174 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 11175 // writer 11176 synchronized (mPackages) { 11177 if (!isExternalMediaAvailable()) { 11178 // If the external storage is no longer mounted at this point, 11179 // the caller may not have been able to delete all of this 11180 // packages files and can not delete any more. Bail. 11181 return null; 11182 } 11183 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 11184 if (lastPackage != null) { 11185 pkgs.remove(lastPackage); 11186 } 11187 if (pkgs.size() > 0) { 11188 return pkgs.get(0); 11189 } 11190 } 11191 return null; 11192 } 11193 11194 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 11195 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 11196 userId, andCode ? 1 : 0, packageName); 11197 if (mSystemReady) { 11198 msg.sendToTarget(); 11199 } else { 11200 if (mPostSystemReadyMessages == null) { 11201 mPostSystemReadyMessages = new ArrayList<>(); 11202 } 11203 mPostSystemReadyMessages.add(msg); 11204 } 11205 } 11206 11207 void startCleaningPackages() { 11208 // reader 11209 if (!isExternalMediaAvailable()) { 11210 return; 11211 } 11212 synchronized (mPackages) { 11213 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 11214 return; 11215 } 11216 } 11217 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 11218 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 11219 IActivityManager am = ActivityManagerNative.getDefault(); 11220 if (am != null) { 11221 try { 11222 am.startService(null, intent, null, mContext.getOpPackageName(), 11223 UserHandle.USER_SYSTEM); 11224 } catch (RemoteException e) { 11225 } 11226 } 11227 } 11228 11229 @Override 11230 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 11231 int installFlags, String installerPackageName, int userId) { 11232 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 11233 11234 final int callingUid = Binder.getCallingUid(); 11235 enforceCrossUserPermission(callingUid, userId, 11236 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 11237 11238 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11239 try { 11240 if (observer != null) { 11241 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 11242 } 11243 } catch (RemoteException re) { 11244 } 11245 return; 11246 } 11247 11248 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 11249 installFlags |= PackageManager.INSTALL_FROM_ADB; 11250 11251 } else { 11252 // Caller holds INSTALL_PACKAGES permission, so we're less strict 11253 // about installerPackageName. 11254 11255 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 11256 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 11257 } 11258 11259 UserHandle user; 11260 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 11261 user = UserHandle.ALL; 11262 } else { 11263 user = new UserHandle(userId); 11264 } 11265 11266 // Only system components can circumvent runtime permissions when installing. 11267 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 11268 && mContext.checkCallingOrSelfPermission(Manifest.permission 11269 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 11270 throw new SecurityException("You need the " 11271 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 11272 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 11273 } 11274 11275 final File originFile = new File(originPath); 11276 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 11277 11278 final Message msg = mHandler.obtainMessage(INIT_COPY); 11279 final VerificationInfo verificationInfo = new VerificationInfo( 11280 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 11281 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 11282 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 11283 null /*packageAbiOverride*/, null /*grantedPermissions*/, 11284 null /*certificates*/); 11285 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 11286 msg.obj = params; 11287 11288 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 11289 System.identityHashCode(msg.obj)); 11290 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11291 System.identityHashCode(msg.obj)); 11292 11293 mHandler.sendMessage(msg); 11294 } 11295 11296 void installStage(String packageName, File stagedDir, String stagedCid, 11297 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 11298 String installerPackageName, int installerUid, UserHandle user, 11299 Certificate[][] certificates) { 11300 if (DEBUG_EPHEMERAL) { 11301 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11302 Slog.d(TAG, "Ephemeral install of " + packageName); 11303 } 11304 } 11305 final VerificationInfo verificationInfo = new VerificationInfo( 11306 sessionParams.originatingUri, sessionParams.referrerUri, 11307 sessionParams.originatingUid, installerUid); 11308 11309 final OriginInfo origin; 11310 if (stagedDir != null) { 11311 origin = OriginInfo.fromStagedFile(stagedDir); 11312 } else { 11313 origin = OriginInfo.fromStagedContainer(stagedCid); 11314 } 11315 11316 final Message msg = mHandler.obtainMessage(INIT_COPY); 11317 final InstallParams params = new InstallParams(origin, null, observer, 11318 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 11319 verificationInfo, user, sessionParams.abiOverride, 11320 sessionParams.grantedRuntimePermissions, certificates); 11321 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 11322 msg.obj = params; 11323 11324 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 11325 System.identityHashCode(msg.obj)); 11326 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11327 System.identityHashCode(msg.obj)); 11328 11329 mHandler.sendMessage(msg); 11330 } 11331 11332 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 11333 int userId) { 11334 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 11335 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId); 11336 } 11337 11338 private void sendPackageAddedForUser(String packageName, boolean isSystem, 11339 int appId, int userId) { 11340 Bundle extras = new Bundle(1); 11341 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId)); 11342 11343 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 11344 packageName, extras, 0, null, null, new int[] {userId}); 11345 try { 11346 IActivityManager am = ActivityManagerNative.getDefault(); 11347 if (isSystem && am.isUserRunning(userId, 0)) { 11348 // The just-installed/enabled app is bundled on the system, so presumed 11349 // to be able to run automatically without needing an explicit launch. 11350 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 11351 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 11352 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 11353 .setPackage(packageName); 11354 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 11355 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 11356 } 11357 } catch (RemoteException e) { 11358 // shouldn't happen 11359 Slog.w(TAG, "Unable to bootstrap installed package", e); 11360 } 11361 } 11362 11363 @Override 11364 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 11365 int userId) { 11366 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11367 PackageSetting pkgSetting; 11368 final int uid = Binder.getCallingUid(); 11369 enforceCrossUserPermission(uid, userId, 11370 true /* requireFullPermission */, true /* checkShell */, 11371 "setApplicationHiddenSetting for user " + userId); 11372 11373 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 11374 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 11375 return false; 11376 } 11377 11378 long callingId = Binder.clearCallingIdentity(); 11379 try { 11380 boolean sendAdded = false; 11381 boolean sendRemoved = false; 11382 // writer 11383 synchronized (mPackages) { 11384 pkgSetting = mSettings.mPackages.get(packageName); 11385 if (pkgSetting == null) { 11386 return false; 11387 } 11388 if (pkgSetting.getHidden(userId) != hidden) { 11389 pkgSetting.setHidden(hidden, userId); 11390 mSettings.writePackageRestrictionsLPr(userId); 11391 if (hidden) { 11392 sendRemoved = true; 11393 } else { 11394 sendAdded = true; 11395 } 11396 } 11397 } 11398 if (sendAdded) { 11399 sendPackageAddedForUser(packageName, pkgSetting, userId); 11400 return true; 11401 } 11402 if (sendRemoved) { 11403 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 11404 "hiding pkg"); 11405 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 11406 return true; 11407 } 11408 } finally { 11409 Binder.restoreCallingIdentity(callingId); 11410 } 11411 return false; 11412 } 11413 11414 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 11415 int userId) { 11416 final PackageRemovedInfo info = new PackageRemovedInfo(); 11417 info.removedPackage = packageName; 11418 info.removedUsers = new int[] {userId}; 11419 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 11420 info.sendPackageRemovedBroadcasts(true /*killApp*/); 11421 } 11422 11423 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 11424 if (pkgList.length > 0) { 11425 Bundle extras = new Bundle(1); 11426 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 11427 11428 sendPackageBroadcast( 11429 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 11430 : Intent.ACTION_PACKAGES_UNSUSPENDED, 11431 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 11432 new int[] {userId}); 11433 } 11434 } 11435 11436 /** 11437 * Returns true if application is not found or there was an error. Otherwise it returns 11438 * the hidden state of the package for the given user. 11439 */ 11440 @Override 11441 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 11442 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11443 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11444 true /* requireFullPermission */, false /* checkShell */, 11445 "getApplicationHidden for user " + userId); 11446 PackageSetting pkgSetting; 11447 long callingId = Binder.clearCallingIdentity(); 11448 try { 11449 // writer 11450 synchronized (mPackages) { 11451 pkgSetting = mSettings.mPackages.get(packageName); 11452 if (pkgSetting == null) { 11453 return true; 11454 } 11455 return pkgSetting.getHidden(userId); 11456 } 11457 } finally { 11458 Binder.restoreCallingIdentity(callingId); 11459 } 11460 } 11461 11462 /** 11463 * @hide 11464 */ 11465 @Override 11466 public int installExistingPackageAsUser(String packageName, int userId) { 11467 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 11468 null); 11469 PackageSetting pkgSetting; 11470 final int uid = Binder.getCallingUid(); 11471 enforceCrossUserPermission(uid, userId, 11472 true /* requireFullPermission */, true /* checkShell */, 11473 "installExistingPackage for user " + userId); 11474 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11475 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 11476 } 11477 11478 long callingId = Binder.clearCallingIdentity(); 11479 try { 11480 boolean installed = false; 11481 11482 // writer 11483 synchronized (mPackages) { 11484 pkgSetting = mSettings.mPackages.get(packageName); 11485 if (pkgSetting == null) { 11486 return PackageManager.INSTALL_FAILED_INVALID_URI; 11487 } 11488 if (!pkgSetting.getInstalled(userId)) { 11489 pkgSetting.setInstalled(true, userId); 11490 pkgSetting.setHidden(false, userId); 11491 mSettings.writePackageRestrictionsLPr(userId); 11492 installed = true; 11493 } 11494 } 11495 11496 if (installed) { 11497 if (pkgSetting.pkg != null) { 11498 synchronized (mInstallLock) { 11499 // We don't need to freeze for a brand new install 11500 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 11501 } 11502 } 11503 sendPackageAddedForUser(packageName, pkgSetting, userId); 11504 } 11505 } finally { 11506 Binder.restoreCallingIdentity(callingId); 11507 } 11508 11509 return PackageManager.INSTALL_SUCCEEDED; 11510 } 11511 11512 boolean isUserRestricted(int userId, String restrictionKey) { 11513 Bundle restrictions = sUserManager.getUserRestrictions(userId); 11514 if (restrictions.getBoolean(restrictionKey, false)) { 11515 Log.w(TAG, "User is restricted: " + restrictionKey); 11516 return true; 11517 } 11518 return false; 11519 } 11520 11521 @Override 11522 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 11523 int userId) { 11524 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11525 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11526 true /* requireFullPermission */, true /* checkShell */, 11527 "setPackagesSuspended for user " + userId); 11528 11529 if (ArrayUtils.isEmpty(packageNames)) { 11530 return packageNames; 11531 } 11532 11533 // List of package names for whom the suspended state has changed. 11534 List<String> changedPackages = new ArrayList<>(packageNames.length); 11535 // List of package names for whom the suspended state is not set as requested in this 11536 // method. 11537 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 11538 long callingId = Binder.clearCallingIdentity(); 11539 try { 11540 for (int i = 0; i < packageNames.length; i++) { 11541 String packageName = packageNames[i]; 11542 boolean changed = false; 11543 final int appId; 11544 synchronized (mPackages) { 11545 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11546 if (pkgSetting == null) { 11547 Slog.w(TAG, "Could not find package setting for package \"" + packageName 11548 + "\". Skipping suspending/un-suspending."); 11549 unactionedPackages.add(packageName); 11550 continue; 11551 } 11552 appId = pkgSetting.appId; 11553 if (pkgSetting.getSuspended(userId) != suspended) { 11554 if (!canSuspendPackageForUserLocked(packageName, userId)) { 11555 unactionedPackages.add(packageName); 11556 continue; 11557 } 11558 pkgSetting.setSuspended(suspended, userId); 11559 mSettings.writePackageRestrictionsLPr(userId); 11560 changed = true; 11561 changedPackages.add(packageName); 11562 } 11563 } 11564 11565 if (changed && suspended) { 11566 killApplication(packageName, UserHandle.getUid(userId, appId), 11567 "suspending package"); 11568 } 11569 } 11570 } finally { 11571 Binder.restoreCallingIdentity(callingId); 11572 } 11573 11574 if (!changedPackages.isEmpty()) { 11575 sendPackagesSuspendedForUser(changedPackages.toArray( 11576 new String[changedPackages.size()]), userId, suspended); 11577 } 11578 11579 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 11580 } 11581 11582 @Override 11583 public boolean isPackageSuspendedForUser(String packageName, int userId) { 11584 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11585 true /* requireFullPermission */, false /* checkShell */, 11586 "isPackageSuspendedForUser for user " + userId); 11587 synchronized (mPackages) { 11588 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11589 if (pkgSetting == null) { 11590 throw new IllegalArgumentException("Unknown target package: " + packageName); 11591 } 11592 return pkgSetting.getSuspended(userId); 11593 } 11594 } 11595 11596 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 11597 if (isPackageDeviceAdmin(packageName, userId)) { 11598 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11599 + "\": has an active device admin"); 11600 return false; 11601 } 11602 11603 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 11604 if (packageName.equals(activeLauncherPackageName)) { 11605 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11606 + "\": contains the active launcher"); 11607 return false; 11608 } 11609 11610 if (packageName.equals(mRequiredInstallerPackage)) { 11611 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11612 + "\": required for package installation"); 11613 return false; 11614 } 11615 11616 if (packageName.equals(mRequiredVerifierPackage)) { 11617 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11618 + "\": required for package verification"); 11619 return false; 11620 } 11621 11622 if (packageName.equals(getDefaultDialerPackageName(userId))) { 11623 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11624 + "\": is the default dialer"); 11625 return false; 11626 } 11627 11628 return true; 11629 } 11630 11631 private String getActiveLauncherPackageName(int userId) { 11632 Intent intent = new Intent(Intent.ACTION_MAIN); 11633 intent.addCategory(Intent.CATEGORY_HOME); 11634 ResolveInfo resolveInfo = resolveIntent( 11635 intent, 11636 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 11637 PackageManager.MATCH_DEFAULT_ONLY, 11638 userId); 11639 11640 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 11641 } 11642 11643 private String getDefaultDialerPackageName(int userId) { 11644 synchronized (mPackages) { 11645 return mSettings.getDefaultDialerPackageNameLPw(userId); 11646 } 11647 } 11648 11649 @Override 11650 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 11651 mContext.enforceCallingOrSelfPermission( 11652 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11653 "Only package verification agents can verify applications"); 11654 11655 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11656 final PackageVerificationResponse response = new PackageVerificationResponse( 11657 verificationCode, Binder.getCallingUid()); 11658 msg.arg1 = id; 11659 msg.obj = response; 11660 mHandler.sendMessage(msg); 11661 } 11662 11663 @Override 11664 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 11665 long millisecondsToDelay) { 11666 mContext.enforceCallingOrSelfPermission( 11667 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11668 "Only package verification agents can extend verification timeouts"); 11669 11670 final PackageVerificationState state = mPendingVerification.get(id); 11671 final PackageVerificationResponse response = new PackageVerificationResponse( 11672 verificationCodeAtTimeout, Binder.getCallingUid()); 11673 11674 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 11675 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 11676 } 11677 if (millisecondsToDelay < 0) { 11678 millisecondsToDelay = 0; 11679 } 11680 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 11681 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 11682 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 11683 } 11684 11685 if ((state != null) && !state.timeoutExtended()) { 11686 state.extendTimeout(); 11687 11688 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11689 msg.arg1 = id; 11690 msg.obj = response; 11691 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 11692 } 11693 } 11694 11695 private void broadcastPackageVerified(int verificationId, Uri packageUri, 11696 int verificationCode, UserHandle user) { 11697 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 11698 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 11699 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11700 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11701 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 11702 11703 mContext.sendBroadcastAsUser(intent, user, 11704 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 11705 } 11706 11707 private ComponentName matchComponentForVerifier(String packageName, 11708 List<ResolveInfo> receivers) { 11709 ActivityInfo targetReceiver = null; 11710 11711 final int NR = receivers.size(); 11712 for (int i = 0; i < NR; i++) { 11713 final ResolveInfo info = receivers.get(i); 11714 if (info.activityInfo == null) { 11715 continue; 11716 } 11717 11718 if (packageName.equals(info.activityInfo.packageName)) { 11719 targetReceiver = info.activityInfo; 11720 break; 11721 } 11722 } 11723 11724 if (targetReceiver == null) { 11725 return null; 11726 } 11727 11728 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 11729 } 11730 11731 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 11732 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 11733 if (pkgInfo.verifiers.length == 0) { 11734 return null; 11735 } 11736 11737 final int N = pkgInfo.verifiers.length; 11738 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 11739 for (int i = 0; i < N; i++) { 11740 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 11741 11742 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 11743 receivers); 11744 if (comp == null) { 11745 continue; 11746 } 11747 11748 final int verifierUid = getUidForVerifier(verifierInfo); 11749 if (verifierUid == -1) { 11750 continue; 11751 } 11752 11753 if (DEBUG_VERIFY) { 11754 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 11755 + " with the correct signature"); 11756 } 11757 sufficientVerifiers.add(comp); 11758 verificationState.addSufficientVerifier(verifierUid); 11759 } 11760 11761 return sufficientVerifiers; 11762 } 11763 11764 private int getUidForVerifier(VerifierInfo verifierInfo) { 11765 synchronized (mPackages) { 11766 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 11767 if (pkg == null) { 11768 return -1; 11769 } else if (pkg.mSignatures.length != 1) { 11770 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11771 + " has more than one signature; ignoring"); 11772 return -1; 11773 } 11774 11775 /* 11776 * If the public key of the package's signature does not match 11777 * our expected public key, then this is a different package and 11778 * we should skip. 11779 */ 11780 11781 final byte[] expectedPublicKey; 11782 try { 11783 final Signature verifierSig = pkg.mSignatures[0]; 11784 final PublicKey publicKey = verifierSig.getPublicKey(); 11785 expectedPublicKey = publicKey.getEncoded(); 11786 } catch (CertificateException e) { 11787 return -1; 11788 } 11789 11790 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 11791 11792 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 11793 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11794 + " does not have the expected public key; ignoring"); 11795 return -1; 11796 } 11797 11798 return pkg.applicationInfo.uid; 11799 } 11800 } 11801 11802 @Override 11803 public void finishPackageInstall(int token, boolean didLaunch) { 11804 enforceSystemOrRoot("Only the system is allowed to finish installs"); 11805 11806 if (DEBUG_INSTALL) { 11807 Slog.v(TAG, "BM finishing package install for " + token); 11808 } 11809 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 11810 11811 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 11812 mHandler.sendMessage(msg); 11813 } 11814 11815 /** 11816 * Get the verification agent timeout. 11817 * 11818 * @return verification timeout in milliseconds 11819 */ 11820 private long getVerificationTimeout() { 11821 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 11822 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 11823 DEFAULT_VERIFICATION_TIMEOUT); 11824 } 11825 11826 /** 11827 * Get the default verification agent response code. 11828 * 11829 * @return default verification response code 11830 */ 11831 private int getDefaultVerificationResponse() { 11832 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11833 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 11834 DEFAULT_VERIFICATION_RESPONSE); 11835 } 11836 11837 /** 11838 * Check whether or not package verification has been enabled. 11839 * 11840 * @return true if verification should be performed 11841 */ 11842 private boolean isVerificationEnabled(int userId, int installFlags) { 11843 if (!DEFAULT_VERIFY_ENABLE) { 11844 return false; 11845 } 11846 // Ephemeral apps don't get the full verification treatment 11847 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11848 if (DEBUG_EPHEMERAL) { 11849 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 11850 } 11851 return false; 11852 } 11853 11854 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 11855 11856 // Check if installing from ADB 11857 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 11858 // Do not run verification in a test harness environment 11859 if (ActivityManager.isRunningInTestHarness()) { 11860 return false; 11861 } 11862 if (ensureVerifyAppsEnabled) { 11863 return true; 11864 } 11865 // Check if the developer does not want package verification for ADB installs 11866 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11867 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 11868 return false; 11869 } 11870 } 11871 11872 if (ensureVerifyAppsEnabled) { 11873 return true; 11874 } 11875 11876 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11877 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 11878 } 11879 11880 @Override 11881 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 11882 throws RemoteException { 11883 mContext.enforceCallingOrSelfPermission( 11884 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 11885 "Only intentfilter verification agents can verify applications"); 11886 11887 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 11888 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 11889 Binder.getCallingUid(), verificationCode, failedDomains); 11890 msg.arg1 = id; 11891 msg.obj = response; 11892 mHandler.sendMessage(msg); 11893 } 11894 11895 @Override 11896 public int getIntentVerificationStatus(String packageName, int userId) { 11897 synchronized (mPackages) { 11898 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 11899 } 11900 } 11901 11902 @Override 11903 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 11904 mContext.enforceCallingOrSelfPermission( 11905 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11906 11907 boolean result = false; 11908 synchronized (mPackages) { 11909 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 11910 } 11911 if (result) { 11912 scheduleWritePackageRestrictionsLocked(userId); 11913 } 11914 return result; 11915 } 11916 11917 @Override 11918 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 11919 String packageName) { 11920 synchronized (mPackages) { 11921 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 11922 } 11923 } 11924 11925 @Override 11926 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 11927 if (TextUtils.isEmpty(packageName)) { 11928 return ParceledListSlice.emptyList(); 11929 } 11930 synchronized (mPackages) { 11931 PackageParser.Package pkg = mPackages.get(packageName); 11932 if (pkg == null || pkg.activities == null) { 11933 return ParceledListSlice.emptyList(); 11934 } 11935 final int count = pkg.activities.size(); 11936 ArrayList<IntentFilter> result = new ArrayList<>(); 11937 for (int n=0; n<count; n++) { 11938 PackageParser.Activity activity = pkg.activities.get(n); 11939 if (activity.intents != null && activity.intents.size() > 0) { 11940 result.addAll(activity.intents); 11941 } 11942 } 11943 return new ParceledListSlice<>(result); 11944 } 11945 } 11946 11947 @Override 11948 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 11949 mContext.enforceCallingOrSelfPermission( 11950 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11951 11952 synchronized (mPackages) { 11953 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 11954 if (packageName != null) { 11955 result |= updateIntentVerificationStatus(packageName, 11956 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 11957 userId); 11958 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 11959 packageName, userId); 11960 } 11961 return result; 11962 } 11963 } 11964 11965 @Override 11966 public String getDefaultBrowserPackageName(int userId) { 11967 synchronized (mPackages) { 11968 return mSettings.getDefaultBrowserPackageNameLPw(userId); 11969 } 11970 } 11971 11972 /** 11973 * Get the "allow unknown sources" setting. 11974 * 11975 * @return the current "allow unknown sources" setting 11976 */ 11977 private int getUnknownSourcesSettings() { 11978 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 11979 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 11980 -1); 11981 } 11982 11983 @Override 11984 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 11985 final int uid = Binder.getCallingUid(); 11986 // writer 11987 synchronized (mPackages) { 11988 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 11989 if (targetPackageSetting == null) { 11990 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 11991 } 11992 11993 PackageSetting installerPackageSetting; 11994 if (installerPackageName != null) { 11995 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 11996 if (installerPackageSetting == null) { 11997 throw new IllegalArgumentException("Unknown installer package: " 11998 + installerPackageName); 11999 } 12000 } else { 12001 installerPackageSetting = null; 12002 } 12003 12004 Signature[] callerSignature; 12005 Object obj = mSettings.getUserIdLPr(uid); 12006 if (obj != null) { 12007 if (obj instanceof SharedUserSetting) { 12008 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 12009 } else if (obj instanceof PackageSetting) { 12010 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 12011 } else { 12012 throw new SecurityException("Bad object " + obj + " for uid " + uid); 12013 } 12014 } else { 12015 throw new SecurityException("Unknown calling UID: " + uid); 12016 } 12017 12018 // Verify: can't set installerPackageName to a package that is 12019 // not signed with the same cert as the caller. 12020 if (installerPackageSetting != null) { 12021 if (compareSignatures(callerSignature, 12022 installerPackageSetting.signatures.mSignatures) 12023 != PackageManager.SIGNATURE_MATCH) { 12024 throw new SecurityException( 12025 "Caller does not have same cert as new installer package " 12026 + installerPackageName); 12027 } 12028 } 12029 12030 // Verify: if target already has an installer package, it must 12031 // be signed with the same cert as the caller. 12032 if (targetPackageSetting.installerPackageName != null) { 12033 PackageSetting setting = mSettings.mPackages.get( 12034 targetPackageSetting.installerPackageName); 12035 // If the currently set package isn't valid, then it's always 12036 // okay to change it. 12037 if (setting != null) { 12038 if (compareSignatures(callerSignature, 12039 setting.signatures.mSignatures) 12040 != PackageManager.SIGNATURE_MATCH) { 12041 throw new SecurityException( 12042 "Caller does not have same cert as old installer package " 12043 + targetPackageSetting.installerPackageName); 12044 } 12045 } 12046 } 12047 12048 // Okay! 12049 targetPackageSetting.installerPackageName = installerPackageName; 12050 if (installerPackageName != null) { 12051 mSettings.mInstallerPackages.add(installerPackageName); 12052 } 12053 scheduleWriteSettingsLocked(); 12054 } 12055 } 12056 12057 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 12058 // Queue up an async operation since the package installation may take a little while. 12059 mHandler.post(new Runnable() { 12060 public void run() { 12061 mHandler.removeCallbacks(this); 12062 // Result object to be returned 12063 PackageInstalledInfo res = new PackageInstalledInfo(); 12064 res.setReturnCode(currentStatus); 12065 res.uid = -1; 12066 res.pkg = null; 12067 res.removedInfo = null; 12068 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12069 args.doPreInstall(res.returnCode); 12070 synchronized (mInstallLock) { 12071 installPackageTracedLI(args, res); 12072 } 12073 args.doPostInstall(res.returnCode, res.uid); 12074 } 12075 12076 // A restore should be performed at this point if (a) the install 12077 // succeeded, (b) the operation is not an update, and (c) the new 12078 // package has not opted out of backup participation. 12079 final boolean update = res.removedInfo != null 12080 && res.removedInfo.removedPackage != null; 12081 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 12082 boolean doRestore = !update 12083 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 12084 12085 // Set up the post-install work request bookkeeping. This will be used 12086 // and cleaned up by the post-install event handling regardless of whether 12087 // there's a restore pass performed. Token values are >= 1. 12088 int token; 12089 if (mNextInstallToken < 0) mNextInstallToken = 1; 12090 token = mNextInstallToken++; 12091 12092 PostInstallData data = new PostInstallData(args, res); 12093 mRunningInstalls.put(token, data); 12094 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 12095 12096 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 12097 // Pass responsibility to the Backup Manager. It will perform a 12098 // restore if appropriate, then pass responsibility back to the 12099 // Package Manager to run the post-install observer callbacks 12100 // and broadcasts. 12101 IBackupManager bm = IBackupManager.Stub.asInterface( 12102 ServiceManager.getService(Context.BACKUP_SERVICE)); 12103 if (bm != null) { 12104 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 12105 + " to BM for possible restore"); 12106 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12107 try { 12108 // TODO: http://b/22388012 12109 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 12110 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 12111 } else { 12112 doRestore = false; 12113 } 12114 } catch (RemoteException e) { 12115 // can't happen; the backup manager is local 12116 } catch (Exception e) { 12117 Slog.e(TAG, "Exception trying to enqueue restore", e); 12118 doRestore = false; 12119 } 12120 } else { 12121 Slog.e(TAG, "Backup Manager not found!"); 12122 doRestore = false; 12123 } 12124 } 12125 12126 if (!doRestore) { 12127 // No restore possible, or the Backup Manager was mysteriously not 12128 // available -- just fire the post-install work request directly. 12129 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 12130 12131 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 12132 12133 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 12134 mHandler.sendMessage(msg); 12135 } 12136 } 12137 }); 12138 } 12139 12140 /** 12141 * Callback from PackageSettings whenever an app is first transitioned out of the 12142 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 12143 * the app was "launched" for a restoreAtInstall operation. Therefore we check 12144 * here whether the app is the target of an ongoing install, and only send the 12145 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 12146 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 12147 * handling. 12148 */ 12149 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 12150 // Serialize this with the rest of the install-process message chain. In the 12151 // restore-at-install case, this Runnable will necessarily run before the 12152 // POST_INSTALL message is processed, so the contents of mRunningInstalls 12153 // are coherent. In the non-restore case, the app has already completed install 12154 // and been launched through some other means, so it is not in a problematic 12155 // state for observers to see the FIRST_LAUNCH signal. 12156 mHandler.post(new Runnable() { 12157 @Override 12158 public void run() { 12159 for (int i = 0; i < mRunningInstalls.size(); i++) { 12160 final PostInstallData data = mRunningInstalls.valueAt(i); 12161 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 12162 // right package; but is it for the right user? 12163 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 12164 if (userId == data.res.newUsers[uIndex]) { 12165 if (DEBUG_BACKUP) { 12166 Slog.i(TAG, "Package " + pkgName 12167 + " being restored so deferring FIRST_LAUNCH"); 12168 } 12169 return; 12170 } 12171 } 12172 } 12173 } 12174 // didn't find it, so not being restored 12175 if (DEBUG_BACKUP) { 12176 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 12177 } 12178 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 12179 } 12180 }); 12181 } 12182 12183 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 12184 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 12185 installerPkg, null, userIds); 12186 } 12187 12188 private abstract class HandlerParams { 12189 private static final int MAX_RETRIES = 4; 12190 12191 /** 12192 * Number of times startCopy() has been attempted and had a non-fatal 12193 * error. 12194 */ 12195 private int mRetries = 0; 12196 12197 /** User handle for the user requesting the information or installation. */ 12198 private final UserHandle mUser; 12199 String traceMethod; 12200 int traceCookie; 12201 12202 HandlerParams(UserHandle user) { 12203 mUser = user; 12204 } 12205 12206 UserHandle getUser() { 12207 return mUser; 12208 } 12209 12210 HandlerParams setTraceMethod(String traceMethod) { 12211 this.traceMethod = traceMethod; 12212 return this; 12213 } 12214 12215 HandlerParams setTraceCookie(int traceCookie) { 12216 this.traceCookie = traceCookie; 12217 return this; 12218 } 12219 12220 final boolean startCopy() { 12221 boolean res; 12222 try { 12223 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 12224 12225 if (++mRetries > MAX_RETRIES) { 12226 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 12227 mHandler.sendEmptyMessage(MCS_GIVE_UP); 12228 handleServiceError(); 12229 return false; 12230 } else { 12231 handleStartCopy(); 12232 res = true; 12233 } 12234 } catch (RemoteException e) { 12235 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 12236 mHandler.sendEmptyMessage(MCS_RECONNECT); 12237 res = false; 12238 } 12239 handleReturnCode(); 12240 return res; 12241 } 12242 12243 final void serviceError() { 12244 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 12245 handleServiceError(); 12246 handleReturnCode(); 12247 } 12248 12249 abstract void handleStartCopy() throws RemoteException; 12250 abstract void handleServiceError(); 12251 abstract void handleReturnCode(); 12252 } 12253 12254 class MeasureParams extends HandlerParams { 12255 private final PackageStats mStats; 12256 private boolean mSuccess; 12257 12258 private final IPackageStatsObserver mObserver; 12259 12260 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 12261 super(new UserHandle(stats.userHandle)); 12262 mObserver = observer; 12263 mStats = stats; 12264 } 12265 12266 @Override 12267 public String toString() { 12268 return "MeasureParams{" 12269 + Integer.toHexString(System.identityHashCode(this)) 12270 + " " + mStats.packageName + "}"; 12271 } 12272 12273 @Override 12274 void handleStartCopy() throws RemoteException { 12275 synchronized (mInstallLock) { 12276 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 12277 } 12278 12279 if (mSuccess) { 12280 final boolean mounted; 12281 if (Environment.isExternalStorageEmulated()) { 12282 mounted = true; 12283 } else { 12284 final String status = Environment.getExternalStorageState(); 12285 mounted = (Environment.MEDIA_MOUNTED.equals(status) 12286 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 12287 } 12288 12289 if (mounted) { 12290 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 12291 12292 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 12293 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 12294 12295 mStats.externalDataSize = calculateDirectorySize(mContainerService, 12296 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 12297 12298 // Always subtract cache size, since it's a subdirectory 12299 mStats.externalDataSize -= mStats.externalCacheSize; 12300 12301 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 12302 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 12303 12304 mStats.externalObbSize = calculateDirectorySize(mContainerService, 12305 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 12306 } 12307 } 12308 } 12309 12310 @Override 12311 void handleReturnCode() { 12312 if (mObserver != null) { 12313 try { 12314 mObserver.onGetStatsCompleted(mStats, mSuccess); 12315 } catch (RemoteException e) { 12316 Slog.i(TAG, "Observer no longer exists."); 12317 } 12318 } 12319 } 12320 12321 @Override 12322 void handleServiceError() { 12323 Slog.e(TAG, "Could not measure application " + mStats.packageName 12324 + " external storage"); 12325 } 12326 } 12327 12328 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 12329 throws RemoteException { 12330 long result = 0; 12331 for (File path : paths) { 12332 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 12333 } 12334 return result; 12335 } 12336 12337 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 12338 for (File path : paths) { 12339 try { 12340 mcs.clearDirectory(path.getAbsolutePath()); 12341 } catch (RemoteException e) { 12342 } 12343 } 12344 } 12345 12346 static class OriginInfo { 12347 /** 12348 * Location where install is coming from, before it has been 12349 * copied/renamed into place. This could be a single monolithic APK 12350 * file, or a cluster directory. This location may be untrusted. 12351 */ 12352 final File file; 12353 final String cid; 12354 12355 /** 12356 * Flag indicating that {@link #file} or {@link #cid} has already been 12357 * staged, meaning downstream users don't need to defensively copy the 12358 * contents. 12359 */ 12360 final boolean staged; 12361 12362 /** 12363 * Flag indicating that {@link #file} or {@link #cid} is an already 12364 * installed app that is being moved. 12365 */ 12366 final boolean existing; 12367 12368 final String resolvedPath; 12369 final File resolvedFile; 12370 12371 static OriginInfo fromNothing() { 12372 return new OriginInfo(null, null, false, false); 12373 } 12374 12375 static OriginInfo fromUntrustedFile(File file) { 12376 return new OriginInfo(file, null, false, false); 12377 } 12378 12379 static OriginInfo fromExistingFile(File file) { 12380 return new OriginInfo(file, null, false, true); 12381 } 12382 12383 static OriginInfo fromStagedFile(File file) { 12384 return new OriginInfo(file, null, true, false); 12385 } 12386 12387 static OriginInfo fromStagedContainer(String cid) { 12388 return new OriginInfo(null, cid, true, false); 12389 } 12390 12391 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 12392 this.file = file; 12393 this.cid = cid; 12394 this.staged = staged; 12395 this.existing = existing; 12396 12397 if (cid != null) { 12398 resolvedPath = PackageHelper.getSdDir(cid); 12399 resolvedFile = new File(resolvedPath); 12400 } else if (file != null) { 12401 resolvedPath = file.getAbsolutePath(); 12402 resolvedFile = file; 12403 } else { 12404 resolvedPath = null; 12405 resolvedFile = null; 12406 } 12407 } 12408 } 12409 12410 static class MoveInfo { 12411 final int moveId; 12412 final String fromUuid; 12413 final String toUuid; 12414 final String packageName; 12415 final String dataAppName; 12416 final int appId; 12417 final String seinfo; 12418 final int targetSdkVersion; 12419 12420 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 12421 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 12422 this.moveId = moveId; 12423 this.fromUuid = fromUuid; 12424 this.toUuid = toUuid; 12425 this.packageName = packageName; 12426 this.dataAppName = dataAppName; 12427 this.appId = appId; 12428 this.seinfo = seinfo; 12429 this.targetSdkVersion = targetSdkVersion; 12430 } 12431 } 12432 12433 static class VerificationInfo { 12434 /** A constant used to indicate that a uid value is not present. */ 12435 public static final int NO_UID = -1; 12436 12437 /** URI referencing where the package was downloaded from. */ 12438 final Uri originatingUri; 12439 12440 /** HTTP referrer URI associated with the originatingURI. */ 12441 final Uri referrer; 12442 12443 /** UID of the application that the install request originated from. */ 12444 final int originatingUid; 12445 12446 /** UID of application requesting the install */ 12447 final int installerUid; 12448 12449 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 12450 this.originatingUri = originatingUri; 12451 this.referrer = referrer; 12452 this.originatingUid = originatingUid; 12453 this.installerUid = installerUid; 12454 } 12455 } 12456 12457 class InstallParams extends HandlerParams { 12458 final OriginInfo origin; 12459 final MoveInfo move; 12460 final IPackageInstallObserver2 observer; 12461 int installFlags; 12462 final String installerPackageName; 12463 final String volumeUuid; 12464 private InstallArgs mArgs; 12465 private int mRet; 12466 final String packageAbiOverride; 12467 final String[] grantedRuntimePermissions; 12468 final VerificationInfo verificationInfo; 12469 final Certificate[][] certificates; 12470 12471 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12472 int installFlags, String installerPackageName, String volumeUuid, 12473 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 12474 String[] grantedPermissions, Certificate[][] certificates) { 12475 super(user); 12476 this.origin = origin; 12477 this.move = move; 12478 this.observer = observer; 12479 this.installFlags = installFlags; 12480 this.installerPackageName = installerPackageName; 12481 this.volumeUuid = volumeUuid; 12482 this.verificationInfo = verificationInfo; 12483 this.packageAbiOverride = packageAbiOverride; 12484 this.grantedRuntimePermissions = grantedPermissions; 12485 this.certificates = certificates; 12486 } 12487 12488 @Override 12489 public String toString() { 12490 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 12491 + " file=" + origin.file + " cid=" + origin.cid + "}"; 12492 } 12493 12494 private int installLocationPolicy(PackageInfoLite pkgLite) { 12495 String packageName = pkgLite.packageName; 12496 int installLocation = pkgLite.installLocation; 12497 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12498 // reader 12499 synchronized (mPackages) { 12500 // Currently installed package which the new package is attempting to replace or 12501 // null if no such package is installed. 12502 PackageParser.Package installedPkg = mPackages.get(packageName); 12503 // Package which currently owns the data which the new package will own if installed. 12504 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 12505 // will be null whereas dataOwnerPkg will contain information about the package 12506 // which was uninstalled while keeping its data. 12507 PackageParser.Package dataOwnerPkg = installedPkg; 12508 if (dataOwnerPkg == null) { 12509 PackageSetting ps = mSettings.mPackages.get(packageName); 12510 if (ps != null) { 12511 dataOwnerPkg = ps.pkg; 12512 } 12513 } 12514 12515 if (dataOwnerPkg != null) { 12516 // If installed, the package will get access to data left on the device by its 12517 // predecessor. As a security measure, this is permited only if this is not a 12518 // version downgrade or if the predecessor package is marked as debuggable and 12519 // a downgrade is explicitly requested. 12520 // 12521 // On debuggable platform builds, downgrades are permitted even for 12522 // non-debuggable packages to make testing easier. Debuggable platform builds do 12523 // not offer security guarantees and thus it's OK to disable some security 12524 // mechanisms to make debugging/testing easier on those builds. However, even on 12525 // debuggable builds downgrades of packages are permitted only if requested via 12526 // installFlags. This is because we aim to keep the behavior of debuggable 12527 // platform builds as close as possible to the behavior of non-debuggable 12528 // platform builds. 12529 final boolean downgradeRequested = 12530 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 12531 final boolean packageDebuggable = 12532 (dataOwnerPkg.applicationInfo.flags 12533 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 12534 final boolean downgradePermitted = 12535 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 12536 if (!downgradePermitted) { 12537 try { 12538 checkDowngrade(dataOwnerPkg, pkgLite); 12539 } catch (PackageManagerException e) { 12540 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 12541 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 12542 } 12543 } 12544 } 12545 12546 if (installedPkg != null) { 12547 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12548 // Check for updated system application. 12549 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 12550 if (onSd) { 12551 Slog.w(TAG, "Cannot install update to system app on sdcard"); 12552 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 12553 } 12554 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12555 } else { 12556 if (onSd) { 12557 // Install flag overrides everything. 12558 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12559 } 12560 // If current upgrade specifies particular preference 12561 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 12562 // Application explicitly specified internal. 12563 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12564 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 12565 // App explictly prefers external. Let policy decide 12566 } else { 12567 // Prefer previous location 12568 if (isExternal(installedPkg)) { 12569 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12570 } 12571 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12572 } 12573 } 12574 } else { 12575 // Invalid install. Return error code 12576 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 12577 } 12578 } 12579 } 12580 // All the special cases have been taken care of. 12581 // Return result based on recommended install location. 12582 if (onSd) { 12583 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12584 } 12585 return pkgLite.recommendedInstallLocation; 12586 } 12587 12588 /* 12589 * Invoke remote method to get package information and install 12590 * location values. Override install location based on default 12591 * policy if needed and then create install arguments based 12592 * on the install location. 12593 */ 12594 public void handleStartCopy() throws RemoteException { 12595 int ret = PackageManager.INSTALL_SUCCEEDED; 12596 12597 // If we're already staged, we've firmly committed to an install location 12598 if (origin.staged) { 12599 if (origin.file != null) { 12600 installFlags |= PackageManager.INSTALL_INTERNAL; 12601 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12602 } else if (origin.cid != null) { 12603 installFlags |= PackageManager.INSTALL_EXTERNAL; 12604 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12605 } else { 12606 throw new IllegalStateException("Invalid stage location"); 12607 } 12608 } 12609 12610 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12611 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 12612 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12613 PackageInfoLite pkgLite = null; 12614 12615 if (onInt && onSd) { 12616 // Check if both bits are set. 12617 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 12618 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12619 } else if (onSd && ephemeral) { 12620 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 12621 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12622 } else { 12623 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 12624 packageAbiOverride); 12625 12626 if (DEBUG_EPHEMERAL && ephemeral) { 12627 Slog.v(TAG, "pkgLite for install: " + pkgLite); 12628 } 12629 12630 /* 12631 * If we have too little free space, try to free cache 12632 * before giving up. 12633 */ 12634 if (!origin.staged && pkgLite.recommendedInstallLocation 12635 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12636 // TODO: focus freeing disk space on the target device 12637 final StorageManager storage = StorageManager.from(mContext); 12638 final long lowThreshold = storage.getStorageLowBytes( 12639 Environment.getDataDirectory()); 12640 12641 final long sizeBytes = mContainerService.calculateInstalledSize( 12642 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 12643 12644 try { 12645 mInstaller.freeCache(null, sizeBytes + lowThreshold); 12646 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 12647 installFlags, packageAbiOverride); 12648 } catch (InstallerException e) { 12649 Slog.w(TAG, "Failed to free cache", e); 12650 } 12651 12652 /* 12653 * The cache free must have deleted the file we 12654 * downloaded to install. 12655 * 12656 * TODO: fix the "freeCache" call to not delete 12657 * the file we care about. 12658 */ 12659 if (pkgLite.recommendedInstallLocation 12660 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12661 pkgLite.recommendedInstallLocation 12662 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 12663 } 12664 } 12665 } 12666 12667 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12668 int loc = pkgLite.recommendedInstallLocation; 12669 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 12670 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12671 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 12672 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 12673 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12674 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12675 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 12676 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 12677 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12678 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 12679 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 12680 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 12681 } else { 12682 // Override with defaults if needed. 12683 loc = installLocationPolicy(pkgLite); 12684 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 12685 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 12686 } else if (!onSd && !onInt) { 12687 // Override install location with flags 12688 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 12689 // Set the flag to install on external media. 12690 installFlags |= PackageManager.INSTALL_EXTERNAL; 12691 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12692 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 12693 if (DEBUG_EPHEMERAL) { 12694 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 12695 } 12696 installFlags |= PackageManager.INSTALL_EPHEMERAL; 12697 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 12698 |PackageManager.INSTALL_INTERNAL); 12699 } else { 12700 // Make sure the flag for installing on external 12701 // media is unset 12702 installFlags |= PackageManager.INSTALL_INTERNAL; 12703 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12704 } 12705 } 12706 } 12707 } 12708 12709 final InstallArgs args = createInstallArgs(this); 12710 mArgs = args; 12711 12712 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12713 // TODO: http://b/22976637 12714 // Apps installed for "all" users use the device owner to verify the app 12715 UserHandle verifierUser = getUser(); 12716 if (verifierUser == UserHandle.ALL) { 12717 verifierUser = UserHandle.SYSTEM; 12718 } 12719 12720 /* 12721 * Determine if we have any installed package verifiers. If we 12722 * do, then we'll defer to them to verify the packages. 12723 */ 12724 final int requiredUid = mRequiredVerifierPackage == null ? -1 12725 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 12726 verifierUser.getIdentifier()); 12727 if (!origin.existing && requiredUid != -1 12728 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 12729 final Intent verification = new Intent( 12730 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 12731 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 12732 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 12733 PACKAGE_MIME_TYPE); 12734 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 12735 12736 // Query all live verifiers based on current user state 12737 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 12738 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 12739 12740 if (DEBUG_VERIFY) { 12741 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 12742 + verification.toString() + " with " + pkgLite.verifiers.length 12743 + " optional verifiers"); 12744 } 12745 12746 final int verificationId = mPendingVerificationToken++; 12747 12748 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 12749 12750 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 12751 installerPackageName); 12752 12753 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 12754 installFlags); 12755 12756 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 12757 pkgLite.packageName); 12758 12759 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 12760 pkgLite.versionCode); 12761 12762 if (verificationInfo != null) { 12763 if (verificationInfo.originatingUri != null) { 12764 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 12765 verificationInfo.originatingUri); 12766 } 12767 if (verificationInfo.referrer != null) { 12768 verification.putExtra(Intent.EXTRA_REFERRER, 12769 verificationInfo.referrer); 12770 } 12771 if (verificationInfo.originatingUid >= 0) { 12772 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 12773 verificationInfo.originatingUid); 12774 } 12775 if (verificationInfo.installerUid >= 0) { 12776 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 12777 verificationInfo.installerUid); 12778 } 12779 } 12780 12781 final PackageVerificationState verificationState = new PackageVerificationState( 12782 requiredUid, args); 12783 12784 mPendingVerification.append(verificationId, verificationState); 12785 12786 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 12787 receivers, verificationState); 12788 12789 /* 12790 * If any sufficient verifiers were listed in the package 12791 * manifest, attempt to ask them. 12792 */ 12793 if (sufficientVerifiers != null) { 12794 final int N = sufficientVerifiers.size(); 12795 if (N == 0) { 12796 Slog.i(TAG, "Additional verifiers required, but none installed."); 12797 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 12798 } else { 12799 for (int i = 0; i < N; i++) { 12800 final ComponentName verifierComponent = sufficientVerifiers.get(i); 12801 12802 final Intent sufficientIntent = new Intent(verification); 12803 sufficientIntent.setComponent(verifierComponent); 12804 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 12805 } 12806 } 12807 } 12808 12809 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 12810 mRequiredVerifierPackage, receivers); 12811 if (ret == PackageManager.INSTALL_SUCCEEDED 12812 && mRequiredVerifierPackage != null) { 12813 Trace.asyncTraceBegin( 12814 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 12815 /* 12816 * Send the intent to the required verification agent, 12817 * but only start the verification timeout after the 12818 * target BroadcastReceivers have run. 12819 */ 12820 verification.setComponent(requiredVerifierComponent); 12821 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 12822 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12823 new BroadcastReceiver() { 12824 @Override 12825 public void onReceive(Context context, Intent intent) { 12826 final Message msg = mHandler 12827 .obtainMessage(CHECK_PENDING_VERIFICATION); 12828 msg.arg1 = verificationId; 12829 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 12830 } 12831 }, null, 0, null, null); 12832 12833 /* 12834 * We don't want the copy to proceed until verification 12835 * succeeds, so null out this field. 12836 */ 12837 mArgs = null; 12838 } 12839 } else { 12840 /* 12841 * No package verification is enabled, so immediately start 12842 * the remote call to initiate copy using temporary file. 12843 */ 12844 ret = args.copyApk(mContainerService, true); 12845 } 12846 } 12847 12848 mRet = ret; 12849 } 12850 12851 @Override 12852 void handleReturnCode() { 12853 // If mArgs is null, then MCS couldn't be reached. When it 12854 // reconnects, it will try again to install. At that point, this 12855 // will succeed. 12856 if (mArgs != null) { 12857 processPendingInstall(mArgs, mRet); 12858 } 12859 } 12860 12861 @Override 12862 void handleServiceError() { 12863 mArgs = createInstallArgs(this); 12864 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12865 } 12866 12867 public boolean isForwardLocked() { 12868 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12869 } 12870 } 12871 12872 /** 12873 * Used during creation of InstallArgs 12874 * 12875 * @param installFlags package installation flags 12876 * @return true if should be installed on external storage 12877 */ 12878 private static boolean installOnExternalAsec(int installFlags) { 12879 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 12880 return false; 12881 } 12882 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 12883 return true; 12884 } 12885 return false; 12886 } 12887 12888 /** 12889 * Used during creation of InstallArgs 12890 * 12891 * @param installFlags package installation flags 12892 * @return true if should be installed as forward locked 12893 */ 12894 private static boolean installForwardLocked(int installFlags) { 12895 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12896 } 12897 12898 private InstallArgs createInstallArgs(InstallParams params) { 12899 if (params.move != null) { 12900 return new MoveInstallArgs(params); 12901 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 12902 return new AsecInstallArgs(params); 12903 } else { 12904 return new FileInstallArgs(params); 12905 } 12906 } 12907 12908 /** 12909 * Create args that describe an existing installed package. Typically used 12910 * when cleaning up old installs, or used as a move source. 12911 */ 12912 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 12913 String resourcePath, String[] instructionSets) { 12914 final boolean isInAsec; 12915 if (installOnExternalAsec(installFlags)) { 12916 /* Apps on SD card are always in ASEC containers. */ 12917 isInAsec = true; 12918 } else if (installForwardLocked(installFlags) 12919 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 12920 /* 12921 * Forward-locked apps are only in ASEC containers if they're the 12922 * new style 12923 */ 12924 isInAsec = true; 12925 } else { 12926 isInAsec = false; 12927 } 12928 12929 if (isInAsec) { 12930 return new AsecInstallArgs(codePath, instructionSets, 12931 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 12932 } else { 12933 return new FileInstallArgs(codePath, resourcePath, instructionSets); 12934 } 12935 } 12936 12937 static abstract class InstallArgs { 12938 /** @see InstallParams#origin */ 12939 final OriginInfo origin; 12940 /** @see InstallParams#move */ 12941 final MoveInfo move; 12942 12943 final IPackageInstallObserver2 observer; 12944 // Always refers to PackageManager flags only 12945 final int installFlags; 12946 final String installerPackageName; 12947 final String volumeUuid; 12948 final UserHandle user; 12949 final String abiOverride; 12950 final String[] installGrantPermissions; 12951 /** If non-null, drop an async trace when the install completes */ 12952 final String traceMethod; 12953 final int traceCookie; 12954 final Certificate[][] certificates; 12955 12956 // The list of instruction sets supported by this app. This is currently 12957 // only used during the rmdex() phase to clean up resources. We can get rid of this 12958 // if we move dex files under the common app path. 12959 /* nullable */ String[] instructionSets; 12960 12961 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12962 int installFlags, String installerPackageName, String volumeUuid, 12963 UserHandle user, String[] instructionSets, 12964 String abiOverride, String[] installGrantPermissions, 12965 String traceMethod, int traceCookie, Certificate[][] certificates) { 12966 this.origin = origin; 12967 this.move = move; 12968 this.installFlags = installFlags; 12969 this.observer = observer; 12970 this.installerPackageName = installerPackageName; 12971 this.volumeUuid = volumeUuid; 12972 this.user = user; 12973 this.instructionSets = instructionSets; 12974 this.abiOverride = abiOverride; 12975 this.installGrantPermissions = installGrantPermissions; 12976 this.traceMethod = traceMethod; 12977 this.traceCookie = traceCookie; 12978 this.certificates = certificates; 12979 } 12980 12981 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 12982 abstract int doPreInstall(int status); 12983 12984 /** 12985 * Rename package into final resting place. All paths on the given 12986 * scanned package should be updated to reflect the rename. 12987 */ 12988 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 12989 abstract int doPostInstall(int status, int uid); 12990 12991 /** @see PackageSettingBase#codePathString */ 12992 abstract String getCodePath(); 12993 /** @see PackageSettingBase#resourcePathString */ 12994 abstract String getResourcePath(); 12995 12996 // Need installer lock especially for dex file removal. 12997 abstract void cleanUpResourcesLI(); 12998 abstract boolean doPostDeleteLI(boolean delete); 12999 13000 /** 13001 * Called before the source arguments are copied. This is used mostly 13002 * for MoveParams when it needs to read the source file to put it in the 13003 * destination. 13004 */ 13005 int doPreCopy() { 13006 return PackageManager.INSTALL_SUCCEEDED; 13007 } 13008 13009 /** 13010 * Called after the source arguments are copied. This is used mostly for 13011 * MoveParams when it needs to read the source file to put it in the 13012 * destination. 13013 */ 13014 int doPostCopy(int uid) { 13015 return PackageManager.INSTALL_SUCCEEDED; 13016 } 13017 13018 protected boolean isFwdLocked() { 13019 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13020 } 13021 13022 protected boolean isExternalAsec() { 13023 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 13024 } 13025 13026 protected boolean isEphemeral() { 13027 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13028 } 13029 13030 UserHandle getUser() { 13031 return user; 13032 } 13033 } 13034 13035 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 13036 if (!allCodePaths.isEmpty()) { 13037 if (instructionSets == null) { 13038 throw new IllegalStateException("instructionSet == null"); 13039 } 13040 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 13041 for (String codePath : allCodePaths) { 13042 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 13043 try { 13044 mInstaller.rmdex(codePath, dexCodeInstructionSet); 13045 } catch (InstallerException ignored) { 13046 } 13047 } 13048 } 13049 } 13050 } 13051 13052 /** 13053 * Logic to handle installation of non-ASEC applications, including copying 13054 * and renaming logic. 13055 */ 13056 class FileInstallArgs extends InstallArgs { 13057 private File codeFile; 13058 private File resourceFile; 13059 13060 // Example topology: 13061 // /data/app/com.example/base.apk 13062 // /data/app/com.example/split_foo.apk 13063 // /data/app/com.example/lib/arm/libfoo.so 13064 // /data/app/com.example/lib/arm64/libfoo.so 13065 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 13066 13067 /** New install */ 13068 FileInstallArgs(InstallParams params) { 13069 super(params.origin, params.move, params.observer, params.installFlags, 13070 params.installerPackageName, params.volumeUuid, 13071 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 13072 params.grantedRuntimePermissions, 13073 params.traceMethod, params.traceCookie, params.certificates); 13074 if (isFwdLocked()) { 13075 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 13076 } 13077 } 13078 13079 /** Existing install */ 13080 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 13081 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 13082 null, null, null, 0, null /*certificates*/); 13083 this.codeFile = (codePath != null) ? new File(codePath) : null; 13084 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 13085 } 13086 13087 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13088 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 13089 try { 13090 return doCopyApk(imcs, temp); 13091 } finally { 13092 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13093 } 13094 } 13095 13096 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13097 if (origin.staged) { 13098 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 13099 codeFile = origin.file; 13100 resourceFile = origin.file; 13101 return PackageManager.INSTALL_SUCCEEDED; 13102 } 13103 13104 try { 13105 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13106 final File tempDir = 13107 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 13108 codeFile = tempDir; 13109 resourceFile = tempDir; 13110 } catch (IOException e) { 13111 Slog.w(TAG, "Failed to create copy file: " + e); 13112 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 13113 } 13114 13115 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 13116 @Override 13117 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 13118 if (!FileUtils.isValidExtFilename(name)) { 13119 throw new IllegalArgumentException("Invalid filename: " + name); 13120 } 13121 try { 13122 final File file = new File(codeFile, name); 13123 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 13124 O_RDWR | O_CREAT, 0644); 13125 Os.chmod(file.getAbsolutePath(), 0644); 13126 return new ParcelFileDescriptor(fd); 13127 } catch (ErrnoException e) { 13128 throw new RemoteException("Failed to open: " + e.getMessage()); 13129 } 13130 } 13131 }; 13132 13133 int ret = PackageManager.INSTALL_SUCCEEDED; 13134 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 13135 if (ret != PackageManager.INSTALL_SUCCEEDED) { 13136 Slog.e(TAG, "Failed to copy package"); 13137 return ret; 13138 } 13139 13140 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 13141 NativeLibraryHelper.Handle handle = null; 13142 try { 13143 handle = NativeLibraryHelper.Handle.create(codeFile); 13144 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 13145 abiOverride); 13146 } catch (IOException e) { 13147 Slog.e(TAG, "Copying native libraries failed", e); 13148 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13149 } finally { 13150 IoUtils.closeQuietly(handle); 13151 } 13152 13153 return ret; 13154 } 13155 13156 int doPreInstall(int status) { 13157 if (status != PackageManager.INSTALL_SUCCEEDED) { 13158 cleanUp(); 13159 } 13160 return status; 13161 } 13162 13163 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13164 if (status != PackageManager.INSTALL_SUCCEEDED) { 13165 cleanUp(); 13166 return false; 13167 } 13168 13169 final File targetDir = codeFile.getParentFile(); 13170 final File beforeCodeFile = codeFile; 13171 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 13172 13173 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 13174 try { 13175 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 13176 } catch (ErrnoException e) { 13177 Slog.w(TAG, "Failed to rename", e); 13178 return false; 13179 } 13180 13181 if (!SELinux.restoreconRecursive(afterCodeFile)) { 13182 Slog.w(TAG, "Failed to restorecon"); 13183 return false; 13184 } 13185 13186 // Reflect the rename internally 13187 codeFile = afterCodeFile; 13188 resourceFile = afterCodeFile; 13189 13190 // Reflect the rename in scanned details 13191 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13192 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13193 afterCodeFile, pkg.baseCodePath)); 13194 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13195 afterCodeFile, pkg.splitCodePaths)); 13196 13197 // Reflect the rename in app info 13198 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13199 pkg.setApplicationInfoCodePath(pkg.codePath); 13200 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13201 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13202 pkg.setApplicationInfoResourcePath(pkg.codePath); 13203 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13204 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13205 13206 return true; 13207 } 13208 13209 int doPostInstall(int status, int uid) { 13210 if (status != PackageManager.INSTALL_SUCCEEDED) { 13211 cleanUp(); 13212 } 13213 return status; 13214 } 13215 13216 @Override 13217 String getCodePath() { 13218 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13219 } 13220 13221 @Override 13222 String getResourcePath() { 13223 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13224 } 13225 13226 private boolean cleanUp() { 13227 if (codeFile == null || !codeFile.exists()) { 13228 return false; 13229 } 13230 13231 removeCodePathLI(codeFile); 13232 13233 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 13234 resourceFile.delete(); 13235 } 13236 13237 return true; 13238 } 13239 13240 void cleanUpResourcesLI() { 13241 // Try enumerating all code paths before deleting 13242 List<String> allCodePaths = Collections.EMPTY_LIST; 13243 if (codeFile != null && codeFile.exists()) { 13244 try { 13245 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13246 allCodePaths = pkg.getAllCodePaths(); 13247 } catch (PackageParserException e) { 13248 // Ignored; we tried our best 13249 } 13250 } 13251 13252 cleanUp(); 13253 removeDexFiles(allCodePaths, instructionSets); 13254 } 13255 13256 boolean doPostDeleteLI(boolean delete) { 13257 // XXX err, shouldn't we respect the delete flag? 13258 cleanUpResourcesLI(); 13259 return true; 13260 } 13261 } 13262 13263 private boolean isAsecExternal(String cid) { 13264 final String asecPath = PackageHelper.getSdFilesystem(cid); 13265 return !asecPath.startsWith(mAsecInternalPath); 13266 } 13267 13268 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 13269 PackageManagerException { 13270 if (copyRet < 0) { 13271 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 13272 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 13273 throw new PackageManagerException(copyRet, message); 13274 } 13275 } 13276 } 13277 13278 /** 13279 * Extract the MountService "container ID" from the full code path of an 13280 * .apk. 13281 */ 13282 static String cidFromCodePath(String fullCodePath) { 13283 int eidx = fullCodePath.lastIndexOf("/"); 13284 String subStr1 = fullCodePath.substring(0, eidx); 13285 int sidx = subStr1.lastIndexOf("/"); 13286 return subStr1.substring(sidx+1, eidx); 13287 } 13288 13289 /** 13290 * Logic to handle installation of ASEC applications, including copying and 13291 * renaming logic. 13292 */ 13293 class AsecInstallArgs extends InstallArgs { 13294 static final String RES_FILE_NAME = "pkg.apk"; 13295 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 13296 13297 String cid; 13298 String packagePath; 13299 String resourcePath; 13300 13301 /** New install */ 13302 AsecInstallArgs(InstallParams params) { 13303 super(params.origin, params.move, params.observer, params.installFlags, 13304 params.installerPackageName, params.volumeUuid, 13305 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13306 params.grantedRuntimePermissions, 13307 params.traceMethod, params.traceCookie, params.certificates); 13308 } 13309 13310 /** Existing install */ 13311 AsecInstallArgs(String fullCodePath, String[] instructionSets, 13312 boolean isExternal, boolean isForwardLocked) { 13313 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 13314 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13315 instructionSets, null, null, null, 0, null /*certificates*/); 13316 // Hackily pretend we're still looking at a full code path 13317 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 13318 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 13319 } 13320 13321 // Extract cid from fullCodePath 13322 int eidx = fullCodePath.lastIndexOf("/"); 13323 String subStr1 = fullCodePath.substring(0, eidx); 13324 int sidx = subStr1.lastIndexOf("/"); 13325 cid = subStr1.substring(sidx+1, eidx); 13326 setMountPath(subStr1); 13327 } 13328 13329 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 13330 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 13331 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13332 instructionSets, null, null, null, 0, null /*certificates*/); 13333 this.cid = cid; 13334 setMountPath(PackageHelper.getSdDir(cid)); 13335 } 13336 13337 void createCopyFile() { 13338 cid = mInstallerService.allocateExternalStageCidLegacy(); 13339 } 13340 13341 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13342 if (origin.staged && origin.cid != null) { 13343 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 13344 cid = origin.cid; 13345 setMountPath(PackageHelper.getSdDir(cid)); 13346 return PackageManager.INSTALL_SUCCEEDED; 13347 } 13348 13349 if (temp) { 13350 createCopyFile(); 13351 } else { 13352 /* 13353 * Pre-emptively destroy the container since it's destroyed if 13354 * copying fails due to it existing anyway. 13355 */ 13356 PackageHelper.destroySdDir(cid); 13357 } 13358 13359 final String newMountPath = imcs.copyPackageToContainer( 13360 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 13361 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 13362 13363 if (newMountPath != null) { 13364 setMountPath(newMountPath); 13365 return PackageManager.INSTALL_SUCCEEDED; 13366 } else { 13367 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13368 } 13369 } 13370 13371 @Override 13372 String getCodePath() { 13373 return packagePath; 13374 } 13375 13376 @Override 13377 String getResourcePath() { 13378 return resourcePath; 13379 } 13380 13381 int doPreInstall(int status) { 13382 if (status != PackageManager.INSTALL_SUCCEEDED) { 13383 // Destroy container 13384 PackageHelper.destroySdDir(cid); 13385 } else { 13386 boolean mounted = PackageHelper.isContainerMounted(cid); 13387 if (!mounted) { 13388 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 13389 Process.SYSTEM_UID); 13390 if (newMountPath != null) { 13391 setMountPath(newMountPath); 13392 } else { 13393 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13394 } 13395 } 13396 } 13397 return status; 13398 } 13399 13400 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13401 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 13402 String newMountPath = null; 13403 if (PackageHelper.isContainerMounted(cid)) { 13404 // Unmount the container 13405 if (!PackageHelper.unMountSdDir(cid)) { 13406 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 13407 return false; 13408 } 13409 } 13410 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13411 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 13412 " which might be stale. Will try to clean up."); 13413 // Clean up the stale container and proceed to recreate. 13414 if (!PackageHelper.destroySdDir(newCacheId)) { 13415 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 13416 return false; 13417 } 13418 // Successfully cleaned up stale container. Try to rename again. 13419 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13420 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 13421 + " inspite of cleaning it up."); 13422 return false; 13423 } 13424 } 13425 if (!PackageHelper.isContainerMounted(newCacheId)) { 13426 Slog.w(TAG, "Mounting container " + newCacheId); 13427 newMountPath = PackageHelper.mountSdDir(newCacheId, 13428 getEncryptKey(), Process.SYSTEM_UID); 13429 } else { 13430 newMountPath = PackageHelper.getSdDir(newCacheId); 13431 } 13432 if (newMountPath == null) { 13433 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 13434 return false; 13435 } 13436 Log.i(TAG, "Succesfully renamed " + cid + 13437 " to " + newCacheId + 13438 " at new path: " + newMountPath); 13439 cid = newCacheId; 13440 13441 final File beforeCodeFile = new File(packagePath); 13442 setMountPath(newMountPath); 13443 final File afterCodeFile = new File(packagePath); 13444 13445 // Reflect the rename in scanned details 13446 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13447 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13448 afterCodeFile, pkg.baseCodePath)); 13449 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13450 afterCodeFile, pkg.splitCodePaths)); 13451 13452 // Reflect the rename in app info 13453 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13454 pkg.setApplicationInfoCodePath(pkg.codePath); 13455 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13456 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13457 pkg.setApplicationInfoResourcePath(pkg.codePath); 13458 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13459 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13460 13461 return true; 13462 } 13463 13464 private void setMountPath(String mountPath) { 13465 final File mountFile = new File(mountPath); 13466 13467 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 13468 if (monolithicFile.exists()) { 13469 packagePath = monolithicFile.getAbsolutePath(); 13470 if (isFwdLocked()) { 13471 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 13472 } else { 13473 resourcePath = packagePath; 13474 } 13475 } else { 13476 packagePath = mountFile.getAbsolutePath(); 13477 resourcePath = packagePath; 13478 } 13479 } 13480 13481 int doPostInstall(int status, int uid) { 13482 if (status != PackageManager.INSTALL_SUCCEEDED) { 13483 cleanUp(); 13484 } else { 13485 final int groupOwner; 13486 final String protectedFile; 13487 if (isFwdLocked()) { 13488 groupOwner = UserHandle.getSharedAppGid(uid); 13489 protectedFile = RES_FILE_NAME; 13490 } else { 13491 groupOwner = -1; 13492 protectedFile = null; 13493 } 13494 13495 if (uid < Process.FIRST_APPLICATION_UID 13496 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 13497 Slog.e(TAG, "Failed to finalize " + cid); 13498 PackageHelper.destroySdDir(cid); 13499 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13500 } 13501 13502 boolean mounted = PackageHelper.isContainerMounted(cid); 13503 if (!mounted) { 13504 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 13505 } 13506 } 13507 return status; 13508 } 13509 13510 private void cleanUp() { 13511 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 13512 13513 // Destroy secure container 13514 PackageHelper.destroySdDir(cid); 13515 } 13516 13517 private List<String> getAllCodePaths() { 13518 final File codeFile = new File(getCodePath()); 13519 if (codeFile != null && codeFile.exists()) { 13520 try { 13521 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13522 return pkg.getAllCodePaths(); 13523 } catch (PackageParserException e) { 13524 // Ignored; we tried our best 13525 } 13526 } 13527 return Collections.EMPTY_LIST; 13528 } 13529 13530 void cleanUpResourcesLI() { 13531 // Enumerate all code paths before deleting 13532 cleanUpResourcesLI(getAllCodePaths()); 13533 } 13534 13535 private void cleanUpResourcesLI(List<String> allCodePaths) { 13536 cleanUp(); 13537 removeDexFiles(allCodePaths, instructionSets); 13538 } 13539 13540 String getPackageName() { 13541 return getAsecPackageName(cid); 13542 } 13543 13544 boolean doPostDeleteLI(boolean delete) { 13545 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 13546 final List<String> allCodePaths = getAllCodePaths(); 13547 boolean mounted = PackageHelper.isContainerMounted(cid); 13548 if (mounted) { 13549 // Unmount first 13550 if (PackageHelper.unMountSdDir(cid)) { 13551 mounted = false; 13552 } 13553 } 13554 if (!mounted && delete) { 13555 cleanUpResourcesLI(allCodePaths); 13556 } 13557 return !mounted; 13558 } 13559 13560 @Override 13561 int doPreCopy() { 13562 if (isFwdLocked()) { 13563 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 13564 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 13565 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13566 } 13567 } 13568 13569 return PackageManager.INSTALL_SUCCEEDED; 13570 } 13571 13572 @Override 13573 int doPostCopy(int uid) { 13574 if (isFwdLocked()) { 13575 if (uid < Process.FIRST_APPLICATION_UID 13576 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 13577 RES_FILE_NAME)) { 13578 Slog.e(TAG, "Failed to finalize " + cid); 13579 PackageHelper.destroySdDir(cid); 13580 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13581 } 13582 } 13583 13584 return PackageManager.INSTALL_SUCCEEDED; 13585 } 13586 } 13587 13588 /** 13589 * Logic to handle movement of existing installed applications. 13590 */ 13591 class MoveInstallArgs extends InstallArgs { 13592 private File codeFile; 13593 private File resourceFile; 13594 13595 /** New install */ 13596 MoveInstallArgs(InstallParams params) { 13597 super(params.origin, params.move, params.observer, params.installFlags, 13598 params.installerPackageName, params.volumeUuid, 13599 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13600 params.grantedRuntimePermissions, 13601 params.traceMethod, params.traceCookie, params.certificates); 13602 } 13603 13604 int copyApk(IMediaContainerService imcs, boolean temp) { 13605 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 13606 + move.fromUuid + " to " + move.toUuid); 13607 synchronized (mInstaller) { 13608 try { 13609 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 13610 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 13611 } catch (InstallerException e) { 13612 Slog.w(TAG, "Failed to move app", e); 13613 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13614 } 13615 } 13616 13617 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 13618 resourceFile = codeFile; 13619 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 13620 13621 return PackageManager.INSTALL_SUCCEEDED; 13622 } 13623 13624 int doPreInstall(int status) { 13625 if (status != PackageManager.INSTALL_SUCCEEDED) { 13626 cleanUp(move.toUuid); 13627 } 13628 return status; 13629 } 13630 13631 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13632 if (status != PackageManager.INSTALL_SUCCEEDED) { 13633 cleanUp(move.toUuid); 13634 return false; 13635 } 13636 13637 // Reflect the move in app info 13638 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13639 pkg.setApplicationInfoCodePath(pkg.codePath); 13640 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13641 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13642 pkg.setApplicationInfoResourcePath(pkg.codePath); 13643 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13644 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13645 13646 return true; 13647 } 13648 13649 int doPostInstall(int status, int uid) { 13650 if (status == PackageManager.INSTALL_SUCCEEDED) { 13651 cleanUp(move.fromUuid); 13652 } else { 13653 cleanUp(move.toUuid); 13654 } 13655 return status; 13656 } 13657 13658 @Override 13659 String getCodePath() { 13660 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13661 } 13662 13663 @Override 13664 String getResourcePath() { 13665 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13666 } 13667 13668 private boolean cleanUp(String volumeUuid) { 13669 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 13670 move.dataAppName); 13671 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 13672 final int[] userIds = sUserManager.getUserIds(); 13673 synchronized (mInstallLock) { 13674 // Clean up both app data and code 13675 // All package moves are frozen until finished 13676 for (int userId : userIds) { 13677 try { 13678 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 13679 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 13680 } catch (InstallerException e) { 13681 Slog.w(TAG, String.valueOf(e)); 13682 } 13683 } 13684 removeCodePathLI(codeFile); 13685 } 13686 return true; 13687 } 13688 13689 void cleanUpResourcesLI() { 13690 throw new UnsupportedOperationException(); 13691 } 13692 13693 boolean doPostDeleteLI(boolean delete) { 13694 throw new UnsupportedOperationException(); 13695 } 13696 } 13697 13698 static String getAsecPackageName(String packageCid) { 13699 int idx = packageCid.lastIndexOf("-"); 13700 if (idx == -1) { 13701 return packageCid; 13702 } 13703 return packageCid.substring(0, idx); 13704 } 13705 13706 // Utility method used to create code paths based on package name and available index. 13707 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 13708 String idxStr = ""; 13709 int idx = 1; 13710 // Fall back to default value of idx=1 if prefix is not 13711 // part of oldCodePath 13712 if (oldCodePath != null) { 13713 String subStr = oldCodePath; 13714 // Drop the suffix right away 13715 if (suffix != null && subStr.endsWith(suffix)) { 13716 subStr = subStr.substring(0, subStr.length() - suffix.length()); 13717 } 13718 // If oldCodePath already contains prefix find out the 13719 // ending index to either increment or decrement. 13720 int sidx = subStr.lastIndexOf(prefix); 13721 if (sidx != -1) { 13722 subStr = subStr.substring(sidx + prefix.length()); 13723 if (subStr != null) { 13724 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 13725 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 13726 } 13727 try { 13728 idx = Integer.parseInt(subStr); 13729 if (idx <= 1) { 13730 idx++; 13731 } else { 13732 idx--; 13733 } 13734 } catch(NumberFormatException e) { 13735 } 13736 } 13737 } 13738 } 13739 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 13740 return prefix + idxStr; 13741 } 13742 13743 private File getNextCodePath(File targetDir, String packageName) { 13744 int suffix = 1; 13745 File result; 13746 do { 13747 result = new File(targetDir, packageName + "-" + suffix); 13748 suffix++; 13749 } while (result.exists()); 13750 return result; 13751 } 13752 13753 // Utility method that returns the relative package path with respect 13754 // to the installation directory. Like say for /data/data/com.test-1.apk 13755 // string com.test-1 is returned. 13756 static String deriveCodePathName(String codePath) { 13757 if (codePath == null) { 13758 return null; 13759 } 13760 final File codeFile = new File(codePath); 13761 final String name = codeFile.getName(); 13762 if (codeFile.isDirectory()) { 13763 return name; 13764 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 13765 final int lastDot = name.lastIndexOf('.'); 13766 return name.substring(0, lastDot); 13767 } else { 13768 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 13769 return null; 13770 } 13771 } 13772 13773 static class PackageInstalledInfo { 13774 String name; 13775 int uid; 13776 // The set of users that originally had this package installed. 13777 int[] origUsers; 13778 // The set of users that now have this package installed. 13779 int[] newUsers; 13780 PackageParser.Package pkg; 13781 int returnCode; 13782 String returnMsg; 13783 PackageRemovedInfo removedInfo; 13784 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 13785 13786 public void setError(int code, String msg) { 13787 setReturnCode(code); 13788 setReturnMessage(msg); 13789 Slog.w(TAG, msg); 13790 } 13791 13792 public void setError(String msg, PackageParserException e) { 13793 setReturnCode(e.error); 13794 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13795 Slog.w(TAG, msg, e); 13796 } 13797 13798 public void setError(String msg, PackageManagerException e) { 13799 returnCode = e.error; 13800 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13801 Slog.w(TAG, msg, e); 13802 } 13803 13804 public void setReturnCode(int returnCode) { 13805 this.returnCode = returnCode; 13806 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13807 for (int i = 0; i < childCount; i++) { 13808 addedChildPackages.valueAt(i).returnCode = returnCode; 13809 } 13810 } 13811 13812 private void setReturnMessage(String returnMsg) { 13813 this.returnMsg = returnMsg; 13814 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13815 for (int i = 0; i < childCount; i++) { 13816 addedChildPackages.valueAt(i).returnMsg = returnMsg; 13817 } 13818 } 13819 13820 // In some error cases we want to convey more info back to the observer 13821 String origPackage; 13822 String origPermission; 13823 } 13824 13825 /* 13826 * Install a non-existing package. 13827 */ 13828 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 13829 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 13830 PackageInstalledInfo res) { 13831 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 13832 13833 // Remember this for later, in case we need to rollback this install 13834 String pkgName = pkg.packageName; 13835 13836 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 13837 13838 synchronized(mPackages) { 13839 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 13840 // A package with the same name is already installed, though 13841 // it has been renamed to an older name. The package we 13842 // are trying to install should be installed as an update to 13843 // the existing one, but that has not been requested, so bail. 13844 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13845 + " without first uninstalling package running as " 13846 + mSettings.mRenamedPackages.get(pkgName)); 13847 return; 13848 } 13849 if (mPackages.containsKey(pkgName)) { 13850 // Don't allow installation over an existing package with the same name. 13851 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13852 + " without first uninstalling."); 13853 return; 13854 } 13855 } 13856 13857 try { 13858 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 13859 System.currentTimeMillis(), user); 13860 13861 updateSettingsLI(newPackage, installerPackageName, null, res, user); 13862 13863 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13864 prepareAppDataAfterInstallLIF(newPackage); 13865 13866 } else { 13867 // Remove package from internal structures, but keep around any 13868 // data that might have already existed 13869 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 13870 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 13871 } 13872 } catch (PackageManagerException e) { 13873 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13874 } 13875 13876 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13877 } 13878 13879 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 13880 // Can't rotate keys during boot or if sharedUser. 13881 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 13882 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 13883 return false; 13884 } 13885 // app is using upgradeKeySets; make sure all are valid 13886 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13887 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 13888 for (int i = 0; i < upgradeKeySets.length; i++) { 13889 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 13890 Slog.wtf(TAG, "Package " 13891 + (oldPs.name != null ? oldPs.name : "<null>") 13892 + " contains upgrade-key-set reference to unknown key-set: " 13893 + upgradeKeySets[i] 13894 + " reverting to signatures check."); 13895 return false; 13896 } 13897 } 13898 return true; 13899 } 13900 13901 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 13902 // Upgrade keysets are being used. Determine if new package has a superset of the 13903 // required keys. 13904 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 13905 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13906 for (int i = 0; i < upgradeKeySets.length; i++) { 13907 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 13908 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 13909 return true; 13910 } 13911 } 13912 return false; 13913 } 13914 13915 private static void updateDigest(MessageDigest digest, File file) throws IOException { 13916 try (DigestInputStream digestStream = 13917 new DigestInputStream(new FileInputStream(file), digest)) { 13918 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 13919 } 13920 } 13921 13922 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 13923 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 13924 final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 13925 13926 final PackageParser.Package oldPackage; 13927 final String pkgName = pkg.packageName; 13928 final int[] allUsers; 13929 final int[] installedUsers; 13930 13931 synchronized(mPackages) { 13932 oldPackage = mPackages.get(pkgName); 13933 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 13934 13935 // don't allow upgrade to target a release SDK from a pre-release SDK 13936 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 13937 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 13938 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 13939 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 13940 if (oldTargetsPreRelease 13941 && !newTargetsPreRelease 13942 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 13943 Slog.w(TAG, "Can't install package targeting released sdk"); 13944 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 13945 return; 13946 } 13947 13948 // don't allow an upgrade from full to ephemeral 13949 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 13950 if (isEphemeral && !oldIsEphemeral) { 13951 // can't downgrade from full to ephemeral 13952 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 13953 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 13954 return; 13955 } 13956 13957 // verify signatures are valid 13958 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13959 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 13960 if (!checkUpgradeKeySetLP(ps, pkg)) { 13961 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13962 "New package not signed by keys specified by upgrade-keysets: " 13963 + pkgName); 13964 return; 13965 } 13966 } else { 13967 // default to original signature matching 13968 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 13969 != PackageManager.SIGNATURE_MATCH) { 13970 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13971 "New package has a different signature: " + pkgName); 13972 return; 13973 } 13974 } 13975 13976 // don't allow a system upgrade unless the upgrade hash matches 13977 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 13978 byte[] digestBytes = null; 13979 try { 13980 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 13981 updateDigest(digest, new File(pkg.baseCodePath)); 13982 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 13983 for (String path : pkg.splitCodePaths) { 13984 updateDigest(digest, new File(path)); 13985 } 13986 } 13987 digestBytes = digest.digest(); 13988 } catch (NoSuchAlgorithmException | IOException e) { 13989 res.setError(INSTALL_FAILED_INVALID_APK, 13990 "Could not compute hash: " + pkgName); 13991 return; 13992 } 13993 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 13994 res.setError(INSTALL_FAILED_INVALID_APK, 13995 "New package fails restrict-update check: " + pkgName); 13996 return; 13997 } 13998 // retain upgrade restriction 13999 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 14000 } 14001 14002 // Check for shared user id changes 14003 String invalidPackageName = 14004 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 14005 if (invalidPackageName != null) { 14006 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 14007 "Package " + invalidPackageName + " tried to change user " 14008 + oldPackage.mSharedUserId); 14009 return; 14010 } 14011 14012 // In case of rollback, remember per-user/profile install state 14013 allUsers = sUserManager.getUserIds(); 14014 installedUsers = ps.queryInstalledUsers(allUsers, true); 14015 } 14016 14017 // Update what is removed 14018 res.removedInfo = new PackageRemovedInfo(); 14019 res.removedInfo.uid = oldPackage.applicationInfo.uid; 14020 res.removedInfo.removedPackage = oldPackage.packageName; 14021 res.removedInfo.isUpdate = true; 14022 res.removedInfo.origUsers = installedUsers; 14023 final int childCount = (oldPackage.childPackages != null) 14024 ? oldPackage.childPackages.size() : 0; 14025 for (int i = 0; i < childCount; i++) { 14026 boolean childPackageUpdated = false; 14027 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 14028 if (res.addedChildPackages != null) { 14029 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14030 if (childRes != null) { 14031 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 14032 childRes.removedInfo.removedPackage = childPkg.packageName; 14033 childRes.removedInfo.isUpdate = true; 14034 childPackageUpdated = true; 14035 } 14036 } 14037 if (!childPackageUpdated) { 14038 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 14039 childRemovedRes.removedPackage = childPkg.packageName; 14040 childRemovedRes.isUpdate = false; 14041 childRemovedRes.dataRemoved = true; 14042 synchronized (mPackages) { 14043 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14044 if (childPs != null) { 14045 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 14046 } 14047 } 14048 if (res.removedInfo.removedChildPackages == null) { 14049 res.removedInfo.removedChildPackages = new ArrayMap<>(); 14050 } 14051 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 14052 } 14053 } 14054 14055 boolean sysPkg = (isSystemApp(oldPackage)); 14056 if (sysPkg) { 14057 // Set the system/privileged flags as needed 14058 final boolean privileged = 14059 (oldPackage.applicationInfo.privateFlags 14060 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14061 final int systemPolicyFlags = policyFlags 14062 | PackageParser.PARSE_IS_SYSTEM 14063 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 14064 14065 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 14066 user, allUsers, installerPackageName, res); 14067 } else { 14068 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 14069 user, allUsers, installerPackageName, res); 14070 } 14071 } 14072 14073 public List<String> getPreviousCodePaths(String packageName) { 14074 final PackageSetting ps = mSettings.mPackages.get(packageName); 14075 final List<String> result = new ArrayList<String>(); 14076 if (ps != null && ps.oldCodePaths != null) { 14077 result.addAll(ps.oldCodePaths); 14078 } 14079 return result; 14080 } 14081 14082 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 14083 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14084 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14085 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 14086 + deletedPackage); 14087 14088 String pkgName = deletedPackage.packageName; 14089 boolean deletedPkg = true; 14090 boolean addedPkg = false; 14091 boolean updatedSettings = false; 14092 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 14093 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 14094 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 14095 14096 final long origUpdateTime = (pkg.mExtras != null) 14097 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 14098 14099 // First delete the existing package while retaining the data directory 14100 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14101 res.removedInfo, true, pkg)) { 14102 // If the existing package wasn't successfully deleted 14103 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 14104 deletedPkg = false; 14105 } else { 14106 // Successfully deleted the old package; proceed with replace. 14107 14108 // If deleted package lived in a container, give users a chance to 14109 // relinquish resources before killing. 14110 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 14111 if (DEBUG_INSTALL) { 14112 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 14113 } 14114 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 14115 final ArrayList<String> pkgList = new ArrayList<String>(1); 14116 pkgList.add(deletedPackage.applicationInfo.packageName); 14117 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 14118 } 14119 14120 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14121 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14122 clearAppProfilesLIF(pkg); 14123 14124 try { 14125 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 14126 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 14127 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14128 14129 // Update the in-memory copy of the previous code paths. 14130 PackageSetting ps = mSettings.mPackages.get(pkgName); 14131 if (!killApp) { 14132 if (ps.oldCodePaths == null) { 14133 ps.oldCodePaths = new ArraySet<>(); 14134 } 14135 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 14136 if (deletedPackage.splitCodePaths != null) { 14137 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 14138 } 14139 } else { 14140 ps.oldCodePaths = null; 14141 } 14142 if (ps.childPackageNames != null) { 14143 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 14144 final String childPkgName = ps.childPackageNames.get(i); 14145 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 14146 childPs.oldCodePaths = ps.oldCodePaths; 14147 } 14148 } 14149 prepareAppDataAfterInstallLIF(newPackage); 14150 addedPkg = true; 14151 } catch (PackageManagerException e) { 14152 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14153 } 14154 } 14155 14156 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14157 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 14158 14159 // Revert all internal state mutations and added folders for the failed install 14160 if (addedPkg) { 14161 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14162 res.removedInfo, true, null); 14163 } 14164 14165 // Restore the old package 14166 if (deletedPkg) { 14167 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 14168 File restoreFile = new File(deletedPackage.codePath); 14169 // Parse old package 14170 boolean oldExternal = isExternal(deletedPackage); 14171 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 14172 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 14173 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 14174 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 14175 try { 14176 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 14177 null); 14178 } catch (PackageManagerException e) { 14179 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 14180 + e.getMessage()); 14181 return; 14182 } 14183 14184 synchronized (mPackages) { 14185 // Ensure the installer package name up to date 14186 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14187 14188 // Update permissions for restored package 14189 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14190 14191 mSettings.writeLPr(); 14192 } 14193 14194 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 14195 } 14196 } else { 14197 synchronized (mPackages) { 14198 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 14199 if (ps != null) { 14200 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 14201 if (res.removedInfo.removedChildPackages != null) { 14202 final int childCount = res.removedInfo.removedChildPackages.size(); 14203 // Iterate in reverse as we may modify the collection 14204 for (int i = childCount - 1; i >= 0; i--) { 14205 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 14206 if (res.addedChildPackages.containsKey(childPackageName)) { 14207 res.removedInfo.removedChildPackages.removeAt(i); 14208 } else { 14209 PackageRemovedInfo childInfo = res.removedInfo 14210 .removedChildPackages.valueAt(i); 14211 childInfo.removedForAllUsers = mPackages.get( 14212 childInfo.removedPackage) == null; 14213 } 14214 } 14215 } 14216 } 14217 } 14218 } 14219 } 14220 14221 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 14222 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14223 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14224 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 14225 + ", old=" + deletedPackage); 14226 14227 final boolean disabledSystem; 14228 14229 // Remove existing system package 14230 removePackageLI(deletedPackage, true); 14231 14232 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 14233 if (!disabledSystem) { 14234 // We didn't need to disable the .apk as a current system package, 14235 // which means we are replacing another update that is already 14236 // installed. We need to make sure to delete the older one's .apk. 14237 res.removedInfo.args = createInstallArgsForExisting(0, 14238 deletedPackage.applicationInfo.getCodePath(), 14239 deletedPackage.applicationInfo.getResourcePath(), 14240 getAppDexInstructionSets(deletedPackage.applicationInfo)); 14241 } else { 14242 res.removedInfo.args = null; 14243 } 14244 14245 // Successfully disabled the old package. Now proceed with re-installation 14246 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14247 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14248 clearAppProfilesLIF(pkg); 14249 14250 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14251 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 14252 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 14253 14254 PackageParser.Package newPackage = null; 14255 try { 14256 // Add the package to the internal data structures 14257 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 14258 14259 // Set the update and install times 14260 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 14261 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 14262 System.currentTimeMillis()); 14263 14264 // Update the package dynamic state if succeeded 14265 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14266 // Now that the install succeeded make sure we remove data 14267 // directories for any child package the update removed. 14268 final int deletedChildCount = (deletedPackage.childPackages != null) 14269 ? deletedPackage.childPackages.size() : 0; 14270 final int newChildCount = (newPackage.childPackages != null) 14271 ? newPackage.childPackages.size() : 0; 14272 for (int i = 0; i < deletedChildCount; i++) { 14273 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 14274 boolean childPackageDeleted = true; 14275 for (int j = 0; j < newChildCount; j++) { 14276 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 14277 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 14278 childPackageDeleted = false; 14279 break; 14280 } 14281 } 14282 if (childPackageDeleted) { 14283 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 14284 deletedChildPkg.packageName); 14285 if (ps != null && res.removedInfo.removedChildPackages != null) { 14286 PackageRemovedInfo removedChildRes = res.removedInfo 14287 .removedChildPackages.get(deletedChildPkg.packageName); 14288 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 14289 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 14290 } 14291 } 14292 } 14293 14294 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14295 prepareAppDataAfterInstallLIF(newPackage); 14296 } 14297 } catch (PackageManagerException e) { 14298 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 14299 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14300 } 14301 14302 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14303 // Re installation failed. Restore old information 14304 // Remove new pkg information 14305 if (newPackage != null) { 14306 removeInstalledPackageLI(newPackage, true); 14307 } 14308 // Add back the old system package 14309 try { 14310 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 14311 } catch (PackageManagerException e) { 14312 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 14313 } 14314 14315 synchronized (mPackages) { 14316 if (disabledSystem) { 14317 enableSystemPackageLPw(deletedPackage); 14318 } 14319 14320 // Ensure the installer package name up to date 14321 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14322 14323 // Update permissions for restored package 14324 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14325 14326 mSettings.writeLPr(); 14327 } 14328 14329 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 14330 + " after failed upgrade"); 14331 } 14332 } 14333 14334 /** 14335 * Checks whether the parent or any of the child packages have a change shared 14336 * user. For a package to be a valid update the shred users of the parent and 14337 * the children should match. We may later support changing child shared users. 14338 * @param oldPkg The updated package. 14339 * @param newPkg The update package. 14340 * @return The shared user that change between the versions. 14341 */ 14342 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 14343 PackageParser.Package newPkg) { 14344 // Check parent shared user 14345 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 14346 return newPkg.packageName; 14347 } 14348 // Check child shared users 14349 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14350 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 14351 for (int i = 0; i < newChildCount; i++) { 14352 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 14353 // If this child was present, did it have the same shared user? 14354 for (int j = 0; j < oldChildCount; j++) { 14355 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 14356 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 14357 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 14358 return newChildPkg.packageName; 14359 } 14360 } 14361 } 14362 return null; 14363 } 14364 14365 private void removeNativeBinariesLI(PackageSetting ps) { 14366 // Remove the lib path for the parent package 14367 if (ps != null) { 14368 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 14369 // Remove the lib path for the child packages 14370 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 14371 for (int i = 0; i < childCount; i++) { 14372 PackageSetting childPs = null; 14373 synchronized (mPackages) { 14374 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 14375 } 14376 if (childPs != null) { 14377 NativeLibraryHelper.removeNativeBinariesLI(childPs 14378 .legacyNativeLibraryPathString); 14379 } 14380 } 14381 } 14382 } 14383 14384 private void enableSystemPackageLPw(PackageParser.Package pkg) { 14385 // Enable the parent package 14386 mSettings.enableSystemPackageLPw(pkg.packageName); 14387 // Enable the child packages 14388 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14389 for (int i = 0; i < childCount; i++) { 14390 PackageParser.Package childPkg = pkg.childPackages.get(i); 14391 mSettings.enableSystemPackageLPw(childPkg.packageName); 14392 } 14393 } 14394 14395 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 14396 PackageParser.Package newPkg) { 14397 // Disable the parent package (parent always replaced) 14398 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 14399 // Disable the child packages 14400 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14401 for (int i = 0; i < childCount; i++) { 14402 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 14403 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 14404 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 14405 } 14406 return disabled; 14407 } 14408 14409 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 14410 String installerPackageName) { 14411 // Enable the parent package 14412 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 14413 // Enable the child packages 14414 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14415 for (int i = 0; i < childCount; i++) { 14416 PackageParser.Package childPkg = pkg.childPackages.get(i); 14417 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 14418 } 14419 } 14420 14421 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 14422 // Collect all used permissions in the UID 14423 ArraySet<String> usedPermissions = new ArraySet<>(); 14424 final int packageCount = su.packages.size(); 14425 for (int i = 0; i < packageCount; i++) { 14426 PackageSetting ps = su.packages.valueAt(i); 14427 if (ps.pkg == null) { 14428 continue; 14429 } 14430 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 14431 for (int j = 0; j < requestedPermCount; j++) { 14432 String permission = ps.pkg.requestedPermissions.get(j); 14433 BasePermission bp = mSettings.mPermissions.get(permission); 14434 if (bp != null) { 14435 usedPermissions.add(permission); 14436 } 14437 } 14438 } 14439 14440 PermissionsState permissionsState = su.getPermissionsState(); 14441 // Prune install permissions 14442 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 14443 final int installPermCount = installPermStates.size(); 14444 for (int i = installPermCount - 1; i >= 0; i--) { 14445 PermissionState permissionState = installPermStates.get(i); 14446 if (!usedPermissions.contains(permissionState.getName())) { 14447 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14448 if (bp != null) { 14449 permissionsState.revokeInstallPermission(bp); 14450 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 14451 PackageManager.MASK_PERMISSION_FLAGS, 0); 14452 } 14453 } 14454 } 14455 14456 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 14457 14458 // Prune runtime permissions 14459 for (int userId : allUserIds) { 14460 List<PermissionState> runtimePermStates = permissionsState 14461 .getRuntimePermissionStates(userId); 14462 final int runtimePermCount = runtimePermStates.size(); 14463 for (int i = runtimePermCount - 1; i >= 0; i--) { 14464 PermissionState permissionState = runtimePermStates.get(i); 14465 if (!usedPermissions.contains(permissionState.getName())) { 14466 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14467 if (bp != null) { 14468 permissionsState.revokeRuntimePermission(bp, userId); 14469 permissionsState.updatePermissionFlags(bp, userId, 14470 PackageManager.MASK_PERMISSION_FLAGS, 0); 14471 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 14472 runtimePermissionChangedUserIds, userId); 14473 } 14474 } 14475 } 14476 } 14477 14478 return runtimePermissionChangedUserIds; 14479 } 14480 14481 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 14482 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 14483 // Update the parent package setting 14484 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 14485 res, user); 14486 // Update the child packages setting 14487 final int childCount = (newPackage.childPackages != null) 14488 ? newPackage.childPackages.size() : 0; 14489 for (int i = 0; i < childCount; i++) { 14490 PackageParser.Package childPackage = newPackage.childPackages.get(i); 14491 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 14492 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 14493 childRes.origUsers, childRes, user); 14494 } 14495 } 14496 14497 private void updateSettingsInternalLI(PackageParser.Package newPackage, 14498 String installerPackageName, int[] allUsers, int[] installedForUsers, 14499 PackageInstalledInfo res, UserHandle user) { 14500 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 14501 14502 String pkgName = newPackage.packageName; 14503 synchronized (mPackages) { 14504 //write settings. the installStatus will be incomplete at this stage. 14505 //note that the new package setting would have already been 14506 //added to mPackages. It hasn't been persisted yet. 14507 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 14508 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14509 mSettings.writeLPr(); 14510 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14511 } 14512 14513 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 14514 synchronized (mPackages) { 14515 updatePermissionsLPw(newPackage.packageName, newPackage, 14516 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 14517 ? UPDATE_PERMISSIONS_ALL : 0)); 14518 // For system-bundled packages, we assume that installing an upgraded version 14519 // of the package implies that the user actually wants to run that new code, 14520 // so we enable the package. 14521 PackageSetting ps = mSettings.mPackages.get(pkgName); 14522 final int userId = user.getIdentifier(); 14523 if (ps != null) { 14524 if (isSystemApp(newPackage)) { 14525 if (DEBUG_INSTALL) { 14526 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 14527 } 14528 // Enable system package for requested users 14529 if (res.origUsers != null) { 14530 for (int origUserId : res.origUsers) { 14531 if (userId == UserHandle.USER_ALL || userId == origUserId) { 14532 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 14533 origUserId, installerPackageName); 14534 } 14535 } 14536 } 14537 // Also convey the prior install/uninstall state 14538 if (allUsers != null && installedForUsers != null) { 14539 for (int currentUserId : allUsers) { 14540 final boolean installed = ArrayUtils.contains( 14541 installedForUsers, currentUserId); 14542 if (DEBUG_INSTALL) { 14543 Slog.d(TAG, " user " + currentUserId + " => " + installed); 14544 } 14545 ps.setInstalled(installed, currentUserId); 14546 } 14547 // these install state changes will be persisted in the 14548 // upcoming call to mSettings.writeLPr(). 14549 } 14550 } 14551 // It's implied that when a user requests installation, they want the app to be 14552 // installed and enabled. 14553 if (userId != UserHandle.USER_ALL) { 14554 ps.setInstalled(true, userId); 14555 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 14556 } 14557 } 14558 res.name = pkgName; 14559 res.uid = newPackage.applicationInfo.uid; 14560 res.pkg = newPackage; 14561 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 14562 mSettings.setInstallerPackageName(pkgName, installerPackageName); 14563 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14564 //to update install status 14565 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14566 mSettings.writeLPr(); 14567 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14568 } 14569 14570 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14571 } 14572 14573 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 14574 try { 14575 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 14576 installPackageLI(args, res); 14577 } finally { 14578 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14579 } 14580 } 14581 14582 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 14583 final int installFlags = args.installFlags; 14584 final String installerPackageName = args.installerPackageName; 14585 final String volumeUuid = args.volumeUuid; 14586 final File tmpPackageFile = new File(args.getCodePath()); 14587 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 14588 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 14589 || (args.volumeUuid != null)); 14590 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 14591 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 14592 boolean replace = false; 14593 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 14594 if (args.move != null) { 14595 // moving a complete application; perform an initial scan on the new install location 14596 scanFlags |= SCAN_INITIAL; 14597 } 14598 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 14599 scanFlags |= SCAN_DONT_KILL_APP; 14600 } 14601 14602 // Result object to be returned 14603 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14604 14605 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 14606 14607 // Sanity check 14608 if (ephemeral && (forwardLocked || onExternal)) { 14609 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 14610 + " external=" + onExternal); 14611 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14612 return; 14613 } 14614 14615 // Retrieve PackageSettings and parse package 14616 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 14617 | PackageParser.PARSE_ENFORCE_CODE 14618 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 14619 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 14620 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0) 14621 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 14622 PackageParser pp = new PackageParser(); 14623 pp.setSeparateProcesses(mSeparateProcesses); 14624 pp.setDisplayMetrics(mMetrics); 14625 14626 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 14627 final PackageParser.Package pkg; 14628 try { 14629 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 14630 } catch (PackageParserException e) { 14631 res.setError("Failed parse during installPackageLI", e); 14632 return; 14633 } finally { 14634 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14635 } 14636 14637 // If we are installing a clustered package add results for the children 14638 if (pkg.childPackages != null) { 14639 synchronized (mPackages) { 14640 final int childCount = pkg.childPackages.size(); 14641 for (int i = 0; i < childCount; i++) { 14642 PackageParser.Package childPkg = pkg.childPackages.get(i); 14643 PackageInstalledInfo childRes = new PackageInstalledInfo(); 14644 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14645 childRes.pkg = childPkg; 14646 childRes.name = childPkg.packageName; 14647 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14648 if (childPs != null) { 14649 childRes.origUsers = childPs.queryInstalledUsers( 14650 sUserManager.getUserIds(), true); 14651 } 14652 if ((mPackages.containsKey(childPkg.packageName))) { 14653 childRes.removedInfo = new PackageRemovedInfo(); 14654 childRes.removedInfo.removedPackage = childPkg.packageName; 14655 } 14656 if (res.addedChildPackages == null) { 14657 res.addedChildPackages = new ArrayMap<>(); 14658 } 14659 res.addedChildPackages.put(childPkg.packageName, childRes); 14660 } 14661 } 14662 } 14663 14664 // If package doesn't declare API override, mark that we have an install 14665 // time CPU ABI override. 14666 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 14667 pkg.cpuAbiOverride = args.abiOverride; 14668 } 14669 14670 String pkgName = res.name = pkg.packageName; 14671 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 14672 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 14673 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 14674 return; 14675 } 14676 } 14677 14678 try { 14679 // either use what we've been given or parse directly from the APK 14680 if (args.certificates != null) { 14681 try { 14682 PackageParser.populateCertificates(pkg, args.certificates); 14683 } catch (PackageParserException e) { 14684 // there was something wrong with the certificates we were given; 14685 // try to pull them from the APK 14686 PackageParser.collectCertificates(pkg, parseFlags); 14687 } 14688 } else { 14689 PackageParser.collectCertificates(pkg, parseFlags); 14690 } 14691 } catch (PackageParserException e) { 14692 res.setError("Failed collect during installPackageLI", e); 14693 return; 14694 } 14695 14696 // Get rid of all references to package scan path via parser. 14697 pp = null; 14698 String oldCodePath = null; 14699 boolean systemApp = false; 14700 synchronized (mPackages) { 14701 // Check if installing already existing package 14702 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14703 String oldName = mSettings.mRenamedPackages.get(pkgName); 14704 if (pkg.mOriginalPackages != null 14705 && pkg.mOriginalPackages.contains(oldName) 14706 && mPackages.containsKey(oldName)) { 14707 // This package is derived from an original package, 14708 // and this device has been updating from that original 14709 // name. We must continue using the original name, so 14710 // rename the new package here. 14711 pkg.setPackageName(oldName); 14712 pkgName = pkg.packageName; 14713 replace = true; 14714 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 14715 + oldName + " pkgName=" + pkgName); 14716 } else if (mPackages.containsKey(pkgName)) { 14717 // This package, under its official name, already exists 14718 // on the device; we should replace it. 14719 replace = true; 14720 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 14721 } 14722 14723 // Child packages are installed through the parent package 14724 if (pkg.parentPackage != null) { 14725 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14726 "Package " + pkg.packageName + " is child of package " 14727 + pkg.parentPackage.parentPackage + ". Child packages " 14728 + "can be updated only through the parent package."); 14729 return; 14730 } 14731 14732 if (replace) { 14733 // Prevent apps opting out from runtime permissions 14734 PackageParser.Package oldPackage = mPackages.get(pkgName); 14735 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 14736 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 14737 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 14738 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 14739 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 14740 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 14741 + " doesn't support runtime permissions but the old" 14742 + " target SDK " + oldTargetSdk + " does."); 14743 return; 14744 } 14745 14746 // Prevent installing of child packages 14747 if (oldPackage.parentPackage != null) { 14748 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14749 "Package " + pkg.packageName + " is child of package " 14750 + oldPackage.parentPackage + ". Child packages " 14751 + "can be updated only through the parent package."); 14752 return; 14753 } 14754 } 14755 } 14756 14757 PackageSetting ps = mSettings.mPackages.get(pkgName); 14758 if (ps != null) { 14759 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 14760 14761 // Quick sanity check that we're signed correctly if updating; 14762 // we'll check this again later when scanning, but we want to 14763 // bail early here before tripping over redefined permissions. 14764 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14765 if (!checkUpgradeKeySetLP(ps, pkg)) { 14766 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 14767 + pkg.packageName + " upgrade keys do not match the " 14768 + "previously installed version"); 14769 return; 14770 } 14771 } else { 14772 try { 14773 verifySignaturesLP(ps, pkg); 14774 } catch (PackageManagerException e) { 14775 res.setError(e.error, e.getMessage()); 14776 return; 14777 } 14778 } 14779 14780 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 14781 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 14782 systemApp = (ps.pkg.applicationInfo.flags & 14783 ApplicationInfo.FLAG_SYSTEM) != 0; 14784 } 14785 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14786 } 14787 14788 // Check whether the newly-scanned package wants to define an already-defined perm 14789 int N = pkg.permissions.size(); 14790 for (int i = N-1; i >= 0; i--) { 14791 PackageParser.Permission perm = pkg.permissions.get(i); 14792 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 14793 if (bp != null) { 14794 // If the defining package is signed with our cert, it's okay. This 14795 // also includes the "updating the same package" case, of course. 14796 // "updating same package" could also involve key-rotation. 14797 final boolean sigsOk; 14798 if (bp.sourcePackage.equals(pkg.packageName) 14799 && (bp.packageSetting instanceof PackageSetting) 14800 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 14801 scanFlags))) { 14802 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 14803 } else { 14804 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 14805 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 14806 } 14807 if (!sigsOk) { 14808 // If the owning package is the system itself, we log but allow 14809 // install to proceed; we fail the install on all other permission 14810 // redefinitions. 14811 if (!bp.sourcePackage.equals("android")) { 14812 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 14813 + pkg.packageName + " attempting to redeclare permission " 14814 + perm.info.name + " already owned by " + bp.sourcePackage); 14815 res.origPermission = perm.info.name; 14816 res.origPackage = bp.sourcePackage; 14817 return; 14818 } else { 14819 Slog.w(TAG, "Package " + pkg.packageName 14820 + " attempting to redeclare system permission " 14821 + perm.info.name + "; ignoring new declaration"); 14822 pkg.permissions.remove(i); 14823 } 14824 } 14825 } 14826 } 14827 } 14828 14829 if (systemApp) { 14830 if (onExternal) { 14831 // Abort update; system app can't be replaced with app on sdcard 14832 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 14833 "Cannot install updates to system apps on sdcard"); 14834 return; 14835 } else if (ephemeral) { 14836 // Abort update; system app can't be replaced with an ephemeral app 14837 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 14838 "Cannot update a system app with an ephemeral app"); 14839 return; 14840 } 14841 } 14842 14843 if (args.move != null) { 14844 // We did an in-place move, so dex is ready to roll 14845 scanFlags |= SCAN_NO_DEX; 14846 scanFlags |= SCAN_MOVE; 14847 14848 synchronized (mPackages) { 14849 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14850 if (ps == null) { 14851 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 14852 "Missing settings for moved package " + pkgName); 14853 } 14854 14855 // We moved the entire application as-is, so bring over the 14856 // previously derived ABI information. 14857 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 14858 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 14859 } 14860 14861 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 14862 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 14863 scanFlags |= SCAN_NO_DEX; 14864 14865 try { 14866 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 14867 args.abiOverride : pkg.cpuAbiOverride); 14868 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 14869 true /* extract libs */); 14870 } catch (PackageManagerException pme) { 14871 Slog.e(TAG, "Error deriving application ABI", pme); 14872 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 14873 return; 14874 } 14875 14876 // Shared libraries for the package need to be updated. 14877 synchronized (mPackages) { 14878 try { 14879 updateSharedLibrariesLPw(pkg, null); 14880 } catch (PackageManagerException e) { 14881 Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage()); 14882 } 14883 } 14884 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 14885 // Do not run PackageDexOptimizer through the local performDexOpt 14886 // method because `pkg` is not in `mPackages` yet. 14887 int result = mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 14888 null /* instructionSets */, false /* checkProfiles */, 14889 getCompilerFilterForReason(REASON_INSTALL)); 14890 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14891 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 14892 String msg = "Extracting package failed for " + pkgName; 14893 res.setError(INSTALL_FAILED_DEXOPT, msg); 14894 return; 14895 } 14896 14897 // Notify BackgroundDexOptService that the package has been changed. 14898 // If this is an update of a package which used to fail to compile, 14899 // BDOS will remove it from its blacklist. 14900 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 14901 } 14902 14903 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 14904 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 14905 return; 14906 } 14907 14908 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 14909 14910 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 14911 "installPackageLI")) { 14912 if (replace) { 14913 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 14914 installerPackageName, res); 14915 } else { 14916 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 14917 args.user, installerPackageName, volumeUuid, res); 14918 } 14919 } 14920 synchronized (mPackages) { 14921 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14922 if (ps != null) { 14923 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14924 } 14925 14926 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14927 for (int i = 0; i < childCount; i++) { 14928 PackageParser.Package childPkg = pkg.childPackages.get(i); 14929 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14930 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14931 if (childPs != null) { 14932 childRes.newUsers = childPs.queryInstalledUsers( 14933 sUserManager.getUserIds(), true); 14934 } 14935 } 14936 } 14937 } 14938 14939 private void startIntentFilterVerifications(int userId, boolean replacing, 14940 PackageParser.Package pkg) { 14941 if (mIntentFilterVerifierComponent == null) { 14942 Slog.w(TAG, "No IntentFilter verification will not be done as " 14943 + "there is no IntentFilterVerifier available!"); 14944 return; 14945 } 14946 14947 final int verifierUid = getPackageUid( 14948 mIntentFilterVerifierComponent.getPackageName(), 14949 MATCH_DEBUG_TRIAGED_MISSING, 14950 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 14951 14952 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14953 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 14954 mHandler.sendMessage(msg); 14955 14956 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14957 for (int i = 0; i < childCount; i++) { 14958 PackageParser.Package childPkg = pkg.childPackages.get(i); 14959 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14960 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 14961 mHandler.sendMessage(msg); 14962 } 14963 } 14964 14965 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 14966 PackageParser.Package pkg) { 14967 int size = pkg.activities.size(); 14968 if (size == 0) { 14969 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14970 "No activity, so no need to verify any IntentFilter!"); 14971 return; 14972 } 14973 14974 final boolean hasDomainURLs = hasDomainURLs(pkg); 14975 if (!hasDomainURLs) { 14976 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14977 "No domain URLs, so no need to verify any IntentFilter!"); 14978 return; 14979 } 14980 14981 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 14982 + " if any IntentFilter from the " + size 14983 + " Activities needs verification ..."); 14984 14985 int count = 0; 14986 final String packageName = pkg.packageName; 14987 14988 synchronized (mPackages) { 14989 // If this is a new install and we see that we've already run verification for this 14990 // package, we have nothing to do: it means the state was restored from backup. 14991 if (!replacing) { 14992 IntentFilterVerificationInfo ivi = 14993 mSettings.getIntentFilterVerificationLPr(packageName); 14994 if (ivi != null) { 14995 if (DEBUG_DOMAIN_VERIFICATION) { 14996 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 14997 + ivi.getStatusString()); 14998 } 14999 return; 15000 } 15001 } 15002 15003 // If any filters need to be verified, then all need to be. 15004 boolean needToVerify = false; 15005 for (PackageParser.Activity a : pkg.activities) { 15006 for (ActivityIntentInfo filter : a.intents) { 15007 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 15008 if (DEBUG_DOMAIN_VERIFICATION) { 15009 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 15010 } 15011 needToVerify = true; 15012 break; 15013 } 15014 } 15015 } 15016 15017 if (needToVerify) { 15018 final int verificationId = mIntentFilterVerificationToken++; 15019 for (PackageParser.Activity a : pkg.activities) { 15020 for (ActivityIntentInfo filter : a.intents) { 15021 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 15022 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15023 "Verification needed for IntentFilter:" + filter.toString()); 15024 mIntentFilterVerifier.addOneIntentFilterVerification( 15025 verifierUid, userId, verificationId, filter, packageName); 15026 count++; 15027 } 15028 } 15029 } 15030 } 15031 } 15032 15033 if (count > 0) { 15034 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 15035 + " IntentFilter verification" + (count > 1 ? "s" : "") 15036 + " for userId:" + userId); 15037 mIntentFilterVerifier.startVerifications(userId); 15038 } else { 15039 if (DEBUG_DOMAIN_VERIFICATION) { 15040 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 15041 } 15042 } 15043 } 15044 15045 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 15046 final ComponentName cn = filter.activity.getComponentName(); 15047 final String packageName = cn.getPackageName(); 15048 15049 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 15050 packageName); 15051 if (ivi == null) { 15052 return true; 15053 } 15054 int status = ivi.getStatus(); 15055 switch (status) { 15056 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 15057 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 15058 return true; 15059 15060 default: 15061 // Nothing to do 15062 return false; 15063 } 15064 } 15065 15066 private static boolean isMultiArch(ApplicationInfo info) { 15067 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 15068 } 15069 15070 private static boolean isExternal(PackageParser.Package pkg) { 15071 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15072 } 15073 15074 private static boolean isExternal(PackageSetting ps) { 15075 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15076 } 15077 15078 private static boolean isEphemeral(PackageParser.Package pkg) { 15079 return pkg.applicationInfo.isEphemeralApp(); 15080 } 15081 15082 private static boolean isEphemeral(PackageSetting ps) { 15083 return ps.pkg != null && isEphemeral(ps.pkg); 15084 } 15085 15086 private static boolean isSystemApp(PackageParser.Package pkg) { 15087 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 15088 } 15089 15090 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 15091 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 15092 } 15093 15094 private static boolean hasDomainURLs(PackageParser.Package pkg) { 15095 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 15096 } 15097 15098 private static boolean isSystemApp(PackageSetting ps) { 15099 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 15100 } 15101 15102 private static boolean isUpdatedSystemApp(PackageSetting ps) { 15103 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 15104 } 15105 15106 private int packageFlagsToInstallFlags(PackageSetting ps) { 15107 int installFlags = 0; 15108 if (isEphemeral(ps)) { 15109 installFlags |= PackageManager.INSTALL_EPHEMERAL; 15110 } 15111 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 15112 // This existing package was an external ASEC install when we have 15113 // the external flag without a UUID 15114 installFlags |= PackageManager.INSTALL_EXTERNAL; 15115 } 15116 if (ps.isForwardLocked()) { 15117 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 15118 } 15119 return installFlags; 15120 } 15121 15122 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 15123 if (isExternal(pkg)) { 15124 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15125 return StorageManager.UUID_PRIMARY_PHYSICAL; 15126 } else { 15127 return pkg.volumeUuid; 15128 } 15129 } else { 15130 return StorageManager.UUID_PRIVATE_INTERNAL; 15131 } 15132 } 15133 15134 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 15135 if (isExternal(pkg)) { 15136 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15137 return mSettings.getExternalVersion(); 15138 } else { 15139 return mSettings.findOrCreateVersion(pkg.volumeUuid); 15140 } 15141 } else { 15142 return mSettings.getInternalVersion(); 15143 } 15144 } 15145 15146 private void deleteTempPackageFiles() { 15147 final FilenameFilter filter = new FilenameFilter() { 15148 public boolean accept(File dir, String name) { 15149 return name.startsWith("vmdl") && name.endsWith(".tmp"); 15150 } 15151 }; 15152 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 15153 file.delete(); 15154 } 15155 } 15156 15157 @Override 15158 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 15159 int flags) { 15160 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 15161 flags); 15162 } 15163 15164 @Override 15165 public void deletePackage(final String packageName, 15166 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 15167 mContext.enforceCallingOrSelfPermission( 15168 android.Manifest.permission.DELETE_PACKAGES, null); 15169 Preconditions.checkNotNull(packageName); 15170 Preconditions.checkNotNull(observer); 15171 final int uid = Binder.getCallingUid(); 15172 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 15173 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 15174 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 15175 mContext.enforceCallingOrSelfPermission( 15176 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 15177 "deletePackage for user " + userId); 15178 } 15179 15180 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 15181 try { 15182 observer.onPackageDeleted(packageName, 15183 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 15184 } catch (RemoteException re) { 15185 } 15186 return; 15187 } 15188 15189 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 15190 try { 15191 observer.onPackageDeleted(packageName, 15192 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 15193 } catch (RemoteException re) { 15194 } 15195 return; 15196 } 15197 15198 if (DEBUG_REMOVE) { 15199 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 15200 + " deleteAllUsers: " + deleteAllUsers ); 15201 } 15202 // Queue up an async operation since the package deletion may take a little while. 15203 mHandler.post(new Runnable() { 15204 public void run() { 15205 mHandler.removeCallbacks(this); 15206 int returnCode; 15207 if (!deleteAllUsers) { 15208 returnCode = deletePackageX(packageName, userId, deleteFlags); 15209 } else { 15210 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 15211 // If nobody is blocking uninstall, proceed with delete for all users 15212 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 15213 returnCode = deletePackageX(packageName, userId, deleteFlags); 15214 } else { 15215 // Otherwise uninstall individually for users with blockUninstalls=false 15216 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 15217 for (int userId : users) { 15218 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 15219 returnCode = deletePackageX(packageName, userId, userFlags); 15220 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 15221 Slog.w(TAG, "Package delete failed for user " + userId 15222 + ", returnCode " + returnCode); 15223 } 15224 } 15225 } 15226 // The app has only been marked uninstalled for certain users. 15227 // We still need to report that delete was blocked 15228 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 15229 } 15230 } 15231 try { 15232 observer.onPackageDeleted(packageName, returnCode, null); 15233 } catch (RemoteException e) { 15234 Log.i(TAG, "Observer no longer exists."); 15235 } //end catch 15236 } //end run 15237 }); 15238 } 15239 15240 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 15241 int[] result = EMPTY_INT_ARRAY; 15242 for (int userId : userIds) { 15243 if (getBlockUninstallForUser(packageName, userId)) { 15244 result = ArrayUtils.appendInt(result, userId); 15245 } 15246 } 15247 return result; 15248 } 15249 15250 @Override 15251 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 15252 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 15253 } 15254 15255 private boolean isPackageDeviceAdmin(String packageName, int userId) { 15256 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 15257 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 15258 try { 15259 if (dpm != null) { 15260 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 15261 /* callingUserOnly =*/ false); 15262 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 15263 : deviceOwnerComponentName.getPackageName(); 15264 // Does the package contains the device owner? 15265 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 15266 // this check is probably not needed, since DO should be registered as a device 15267 // admin on some user too. (Original bug for this: b/17657954) 15268 if (packageName.equals(deviceOwnerPackageName)) { 15269 return true; 15270 } 15271 // Does it contain a device admin for any user? 15272 int[] users; 15273 if (userId == UserHandle.USER_ALL) { 15274 users = sUserManager.getUserIds(); 15275 } else { 15276 users = new int[]{userId}; 15277 } 15278 for (int i = 0; i < users.length; ++i) { 15279 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 15280 return true; 15281 } 15282 } 15283 } 15284 } catch (RemoteException e) { 15285 } 15286 return false; 15287 } 15288 15289 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 15290 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 15291 } 15292 15293 /** 15294 * This method is an internal method that could be get invoked either 15295 * to delete an installed package or to clean up a failed installation. 15296 * After deleting an installed package, a broadcast is sent to notify any 15297 * listeners that the package has been removed. For cleaning up a failed 15298 * installation, the broadcast is not necessary since the package's 15299 * installation wouldn't have sent the initial broadcast either 15300 * The key steps in deleting a package are 15301 * deleting the package information in internal structures like mPackages, 15302 * deleting the packages base directories through installd 15303 * updating mSettings to reflect current status 15304 * persisting settings for later use 15305 * sending a broadcast if necessary 15306 */ 15307 private int deletePackageX(String packageName, int userId, int deleteFlags) { 15308 final PackageRemovedInfo info = new PackageRemovedInfo(); 15309 final boolean res; 15310 15311 final UserHandle removeForUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 15312 ? UserHandle.ALL : new UserHandle(userId); 15313 15314 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 15315 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 15316 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 15317 } 15318 15319 PackageSetting uninstalledPs = null; 15320 15321 // for the uninstall-updates case and restricted profiles, remember the per- 15322 // user handle installed state 15323 int[] allUsers; 15324 synchronized (mPackages) { 15325 uninstalledPs = mSettings.mPackages.get(packageName); 15326 if (uninstalledPs == null) { 15327 Slog.w(TAG, "Not removing non-existent package " + packageName); 15328 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15329 } 15330 allUsers = sUserManager.getUserIds(); 15331 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 15332 } 15333 15334 synchronized (mInstallLock) { 15335 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 15336 try (PackageFreezer freezer = freezePackageForDelete(packageName, deleteFlags, 15337 "deletePackageX")) { 15338 res = deletePackageLIF(packageName, removeForUser, true, allUsers, 15339 deleteFlags | REMOVE_CHATTY, info, true, null); 15340 } 15341 synchronized (mPackages) { 15342 if (res) { 15343 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 15344 } 15345 } 15346 } 15347 15348 if (res) { 15349 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 15350 info.sendPackageRemovedBroadcasts(killApp); 15351 info.sendSystemPackageUpdatedBroadcasts(); 15352 info.sendSystemPackageAppearedBroadcasts(); 15353 } 15354 // Force a gc here. 15355 Runtime.getRuntime().gc(); 15356 // Delete the resources here after sending the broadcast to let 15357 // other processes clean up before deleting resources. 15358 if (info.args != null) { 15359 synchronized (mInstallLock) { 15360 info.args.doPostDeleteLI(true); 15361 } 15362 } 15363 15364 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15365 } 15366 15367 class PackageRemovedInfo { 15368 String removedPackage; 15369 int uid = -1; 15370 int removedAppId = -1; 15371 int[] origUsers; 15372 int[] removedUsers = null; 15373 boolean isRemovedPackageSystemUpdate = false; 15374 boolean isUpdate; 15375 boolean dataRemoved; 15376 boolean removedForAllUsers; 15377 // Clean up resources deleted packages. 15378 InstallArgs args = null; 15379 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 15380 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 15381 15382 void sendPackageRemovedBroadcasts(boolean killApp) { 15383 sendPackageRemovedBroadcastInternal(killApp); 15384 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 15385 for (int i = 0; i < childCount; i++) { 15386 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15387 childInfo.sendPackageRemovedBroadcastInternal(killApp); 15388 } 15389 } 15390 15391 void sendSystemPackageUpdatedBroadcasts() { 15392 if (isRemovedPackageSystemUpdate) { 15393 sendSystemPackageUpdatedBroadcastsInternal(); 15394 final int childCount = (removedChildPackages != null) 15395 ? removedChildPackages.size() : 0; 15396 for (int i = 0; i < childCount; i++) { 15397 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15398 if (childInfo.isRemovedPackageSystemUpdate) { 15399 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 15400 } 15401 } 15402 } 15403 } 15404 15405 void sendSystemPackageAppearedBroadcasts() { 15406 final int packageCount = (appearedChildPackages != null) 15407 ? appearedChildPackages.size() : 0; 15408 for (int i = 0; i < packageCount; i++) { 15409 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 15410 for (int userId : installedInfo.newUsers) { 15411 sendPackageAddedForUser(installedInfo.name, true, 15412 UserHandle.getAppId(installedInfo.uid), userId); 15413 } 15414 } 15415 } 15416 15417 private void sendSystemPackageUpdatedBroadcastsInternal() { 15418 Bundle extras = new Bundle(2); 15419 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15420 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15421 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 15422 extras, 0, null, null, null); 15423 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 15424 extras, 0, null, null, null); 15425 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 15426 null, 0, removedPackage, null, null); 15427 } 15428 15429 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 15430 Bundle extras = new Bundle(2); 15431 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15432 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 15433 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 15434 if (isUpdate || isRemovedPackageSystemUpdate) { 15435 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15436 } 15437 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 15438 if (removedPackage != null) { 15439 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 15440 extras, 0, null, null, removedUsers); 15441 if (dataRemoved && !isRemovedPackageSystemUpdate) { 15442 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 15443 removedPackage, extras, 0, null, null, removedUsers); 15444 } 15445 } 15446 if (removedAppId >= 0) { 15447 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 15448 removedUsers); 15449 } 15450 } 15451 } 15452 15453 /* 15454 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 15455 * flag is not set, the data directory is removed as well. 15456 * make sure this flag is set for partially installed apps. If not its meaningless to 15457 * delete a partially installed application. 15458 */ 15459 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 15460 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 15461 String packageName = ps.name; 15462 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 15463 // Retrieve object to delete permissions for shared user later on 15464 final PackageParser.Package deletedPkg; 15465 final PackageSetting deletedPs; 15466 // reader 15467 synchronized (mPackages) { 15468 deletedPkg = mPackages.get(packageName); 15469 deletedPs = mSettings.mPackages.get(packageName); 15470 if (outInfo != null) { 15471 outInfo.removedPackage = packageName; 15472 outInfo.removedUsers = deletedPs != null 15473 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 15474 : null; 15475 } 15476 } 15477 15478 removePackageLI(ps, (flags & REMOVE_CHATTY) != 0); 15479 15480 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 15481 final PackageParser.Package resolvedPkg; 15482 if (deletedPkg != null) { 15483 resolvedPkg = deletedPkg; 15484 } else { 15485 // We don't have a parsed package when it lives on an ejected 15486 // adopted storage device, so fake something together 15487 resolvedPkg = new PackageParser.Package(ps.name); 15488 resolvedPkg.setVolumeUuid(ps.volumeUuid); 15489 } 15490 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 15491 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15492 destroyAppProfilesLIF(resolvedPkg); 15493 if (outInfo != null) { 15494 outInfo.dataRemoved = true; 15495 } 15496 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 15497 } 15498 15499 // writer 15500 synchronized (mPackages) { 15501 if (deletedPs != null) { 15502 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 15503 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 15504 clearDefaultBrowserIfNeeded(packageName); 15505 if (outInfo != null) { 15506 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 15507 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 15508 } 15509 updatePermissionsLPw(deletedPs.name, null, 0); 15510 if (deletedPs.sharedUser != null) { 15511 // Remove permissions associated with package. Since runtime 15512 // permissions are per user we have to kill the removed package 15513 // or packages running under the shared user of the removed 15514 // package if revoking the permissions requested only by the removed 15515 // package is successful and this causes a change in gids. 15516 for (int userId : UserManagerService.getInstance().getUserIds()) { 15517 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 15518 userId); 15519 if (userIdToKill == UserHandle.USER_ALL 15520 || userIdToKill >= UserHandle.USER_SYSTEM) { 15521 // If gids changed for this user, kill all affected packages. 15522 mHandler.post(new Runnable() { 15523 @Override 15524 public void run() { 15525 // This has to happen with no lock held. 15526 killApplication(deletedPs.name, deletedPs.appId, 15527 KILL_APP_REASON_GIDS_CHANGED); 15528 } 15529 }); 15530 break; 15531 } 15532 } 15533 } 15534 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 15535 } 15536 // make sure to preserve per-user disabled state if this removal was just 15537 // a downgrade of a system app to the factory package 15538 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 15539 if (DEBUG_REMOVE) { 15540 Slog.d(TAG, "Propagating install state across downgrade"); 15541 } 15542 for (int userId : allUserHandles) { 15543 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15544 if (DEBUG_REMOVE) { 15545 Slog.d(TAG, " user " + userId + " => " + installed); 15546 } 15547 ps.setInstalled(installed, userId); 15548 } 15549 } 15550 } 15551 // can downgrade to reader 15552 if (writeSettings) { 15553 // Save settings now 15554 mSettings.writeLPr(); 15555 } 15556 } 15557 if (outInfo != null) { 15558 // A user ID was deleted here. Go through all users and remove it 15559 // from KeyStore. 15560 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 15561 } 15562 } 15563 15564 static boolean locationIsPrivileged(File path) { 15565 try { 15566 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 15567 .getCanonicalPath(); 15568 return path.getCanonicalPath().startsWith(privilegedAppDir); 15569 } catch (IOException e) { 15570 Slog.e(TAG, "Unable to access code path " + path); 15571 } 15572 return false; 15573 } 15574 15575 /* 15576 * Tries to delete system package. 15577 */ 15578 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 15579 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 15580 boolean writeSettings) { 15581 if (deletedPs.parentPackageName != null) { 15582 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 15583 return false; 15584 } 15585 15586 final boolean applyUserRestrictions 15587 = (allUserHandles != null) && (outInfo.origUsers != null); 15588 final PackageSetting disabledPs; 15589 // Confirm if the system package has been updated 15590 // An updated system app can be deleted. This will also have to restore 15591 // the system pkg from system partition 15592 // reader 15593 synchronized (mPackages) { 15594 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 15595 } 15596 15597 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 15598 + " disabledPs=" + disabledPs); 15599 15600 if (disabledPs == null) { 15601 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 15602 return false; 15603 } else if (DEBUG_REMOVE) { 15604 Slog.d(TAG, "Deleting system pkg from data partition"); 15605 } 15606 15607 if (DEBUG_REMOVE) { 15608 if (applyUserRestrictions) { 15609 Slog.d(TAG, "Remembering install states:"); 15610 for (int userId : allUserHandles) { 15611 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 15612 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 15613 } 15614 } 15615 } 15616 15617 // Delete the updated package 15618 outInfo.isRemovedPackageSystemUpdate = true; 15619 if (outInfo.removedChildPackages != null) { 15620 final int childCount = (deletedPs.childPackageNames != null) 15621 ? deletedPs.childPackageNames.size() : 0; 15622 for (int i = 0; i < childCount; i++) { 15623 String childPackageName = deletedPs.childPackageNames.get(i); 15624 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 15625 .contains(childPackageName)) { 15626 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15627 childPackageName); 15628 if (childInfo != null) { 15629 childInfo.isRemovedPackageSystemUpdate = true; 15630 } 15631 } 15632 } 15633 } 15634 15635 if (disabledPs.versionCode < deletedPs.versionCode) { 15636 // Delete data for downgrades 15637 flags &= ~PackageManager.DELETE_KEEP_DATA; 15638 } else { 15639 // Preserve data by setting flag 15640 flags |= PackageManager.DELETE_KEEP_DATA; 15641 } 15642 15643 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 15644 outInfo, writeSettings, disabledPs.pkg); 15645 if (!ret) { 15646 return false; 15647 } 15648 15649 // writer 15650 synchronized (mPackages) { 15651 // Reinstate the old system package 15652 enableSystemPackageLPw(disabledPs.pkg); 15653 // Remove any native libraries from the upgraded package. 15654 removeNativeBinariesLI(deletedPs); 15655 } 15656 15657 // Install the system package 15658 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 15659 int parseFlags = mDefParseFlags 15660 | PackageParser.PARSE_MUST_BE_APK 15661 | PackageParser.PARSE_IS_SYSTEM 15662 | PackageParser.PARSE_IS_SYSTEM_DIR; 15663 if (locationIsPrivileged(disabledPs.codePath)) { 15664 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 15665 } 15666 15667 final PackageParser.Package newPkg; 15668 try { 15669 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 15670 } catch (PackageManagerException e) { 15671 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 15672 + e.getMessage()); 15673 return false; 15674 } 15675 15676 prepareAppDataAfterInstallLIF(newPkg); 15677 15678 // writer 15679 synchronized (mPackages) { 15680 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 15681 15682 // Propagate the permissions state as we do not want to drop on the floor 15683 // runtime permissions. The update permissions method below will take 15684 // care of removing obsolete permissions and grant install permissions. 15685 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 15686 updatePermissionsLPw(newPkg.packageName, newPkg, 15687 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 15688 15689 if (applyUserRestrictions) { 15690 if (DEBUG_REMOVE) { 15691 Slog.d(TAG, "Propagating install state across reinstall"); 15692 } 15693 for (int userId : allUserHandles) { 15694 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15695 if (DEBUG_REMOVE) { 15696 Slog.d(TAG, " user " + userId + " => " + installed); 15697 } 15698 ps.setInstalled(installed, userId); 15699 15700 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 15701 } 15702 // Regardless of writeSettings we need to ensure that this restriction 15703 // state propagation is persisted 15704 mSettings.writeAllUsersPackageRestrictionsLPr(); 15705 } 15706 // can downgrade to reader here 15707 if (writeSettings) { 15708 mSettings.writeLPr(); 15709 } 15710 } 15711 return true; 15712 } 15713 15714 private boolean deleteInstalledPackageLIF(PackageSetting ps, 15715 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 15716 PackageRemovedInfo outInfo, boolean writeSettings, 15717 PackageParser.Package replacingPackage) { 15718 synchronized (mPackages) { 15719 if (outInfo != null) { 15720 outInfo.uid = ps.appId; 15721 } 15722 15723 if (outInfo != null && outInfo.removedChildPackages != null) { 15724 final int childCount = (ps.childPackageNames != null) 15725 ? ps.childPackageNames.size() : 0; 15726 for (int i = 0; i < childCount; i++) { 15727 String childPackageName = ps.childPackageNames.get(i); 15728 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 15729 if (childPs == null) { 15730 return false; 15731 } 15732 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15733 childPackageName); 15734 if (childInfo != null) { 15735 childInfo.uid = childPs.appId; 15736 } 15737 } 15738 } 15739 } 15740 15741 // Delete package data from internal structures and also remove data if flag is set 15742 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 15743 15744 // Delete the child packages data 15745 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 15746 for (int i = 0; i < childCount; i++) { 15747 PackageSetting childPs; 15748 synchronized (mPackages) { 15749 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 15750 } 15751 if (childPs != null) { 15752 PackageRemovedInfo childOutInfo = (outInfo != null 15753 && outInfo.removedChildPackages != null) 15754 ? outInfo.removedChildPackages.get(childPs.name) : null; 15755 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 15756 && (replacingPackage != null 15757 && !replacingPackage.hasChildPackage(childPs.name)) 15758 ? flags & ~DELETE_KEEP_DATA : flags; 15759 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 15760 deleteFlags, writeSettings); 15761 } 15762 } 15763 15764 // Delete application code and resources only for parent packages 15765 if (ps.parentPackageName == null) { 15766 if (deleteCodeAndResources && (outInfo != null)) { 15767 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 15768 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 15769 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 15770 } 15771 } 15772 15773 return true; 15774 } 15775 15776 @Override 15777 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 15778 int userId) { 15779 mContext.enforceCallingOrSelfPermission( 15780 android.Manifest.permission.DELETE_PACKAGES, null); 15781 synchronized (mPackages) { 15782 PackageSetting ps = mSettings.mPackages.get(packageName); 15783 if (ps == null) { 15784 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 15785 return false; 15786 } 15787 if (!ps.getInstalled(userId)) { 15788 // Can't block uninstall for an app that is not installed or enabled. 15789 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 15790 return false; 15791 } 15792 ps.setBlockUninstall(blockUninstall, userId); 15793 mSettings.writePackageRestrictionsLPr(userId); 15794 } 15795 return true; 15796 } 15797 15798 @Override 15799 public boolean getBlockUninstallForUser(String packageName, int userId) { 15800 synchronized (mPackages) { 15801 PackageSetting ps = mSettings.mPackages.get(packageName); 15802 if (ps == null) { 15803 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 15804 return false; 15805 } 15806 return ps.getBlockUninstall(userId); 15807 } 15808 } 15809 15810 @Override 15811 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 15812 int callingUid = Binder.getCallingUid(); 15813 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 15814 throw new SecurityException( 15815 "setRequiredForSystemUser can only be run by the system or root"); 15816 } 15817 synchronized (mPackages) { 15818 PackageSetting ps = mSettings.mPackages.get(packageName); 15819 if (ps == null) { 15820 Log.w(TAG, "Package doesn't exist: " + packageName); 15821 return false; 15822 } 15823 if (systemUserApp) { 15824 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15825 } else { 15826 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15827 } 15828 mSettings.writeLPr(); 15829 } 15830 return true; 15831 } 15832 15833 /* 15834 * This method handles package deletion in general 15835 */ 15836 private boolean deletePackageLIF(String packageName, UserHandle user, 15837 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 15838 PackageRemovedInfo outInfo, boolean writeSettings, 15839 PackageParser.Package replacingPackage) { 15840 if (packageName == null) { 15841 Slog.w(TAG, "Attempt to delete null packageName."); 15842 return false; 15843 } 15844 15845 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 15846 15847 PackageSetting ps; 15848 15849 synchronized (mPackages) { 15850 ps = mSettings.mPackages.get(packageName); 15851 if (ps == null) { 15852 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 15853 return false; 15854 } 15855 15856 if (ps.parentPackageName != null && (!isSystemApp(ps) 15857 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 15858 if (DEBUG_REMOVE) { 15859 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 15860 + ((user == null) ? UserHandle.USER_ALL : user)); 15861 } 15862 final int removedUserId = (user != null) ? user.getIdentifier() 15863 : UserHandle.USER_ALL; 15864 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 15865 return false; 15866 } 15867 markPackageUninstalledForUserLPw(ps, user); 15868 scheduleWritePackageRestrictionsLocked(user); 15869 return true; 15870 } 15871 } 15872 15873 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 15874 && user.getIdentifier() != UserHandle.USER_ALL)) { 15875 // The caller is asking that the package only be deleted for a single 15876 // user. To do this, we just mark its uninstalled state and delete 15877 // its data. If this is a system app, we only allow this to happen if 15878 // they have set the special DELETE_SYSTEM_APP which requests different 15879 // semantics than normal for uninstalling system apps. 15880 markPackageUninstalledForUserLPw(ps, user); 15881 15882 if (!isSystemApp(ps)) { 15883 // Do not uninstall the APK if an app should be cached 15884 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 15885 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 15886 // Other user still have this package installed, so all 15887 // we need to do is clear this user's data and save that 15888 // it is uninstalled. 15889 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 15890 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 15891 return false; 15892 } 15893 scheduleWritePackageRestrictionsLocked(user); 15894 return true; 15895 } else { 15896 // We need to set it back to 'installed' so the uninstall 15897 // broadcasts will be sent correctly. 15898 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 15899 ps.setInstalled(true, user.getIdentifier()); 15900 } 15901 } else { 15902 // This is a system app, so we assume that the 15903 // other users still have this package installed, so all 15904 // we need to do is clear this user's data and save that 15905 // it is uninstalled. 15906 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 15907 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 15908 return false; 15909 } 15910 scheduleWritePackageRestrictionsLocked(user); 15911 return true; 15912 } 15913 } 15914 15915 // If we are deleting a composite package for all users, keep track 15916 // of result for each child. 15917 if (ps.childPackageNames != null && outInfo != null) { 15918 synchronized (mPackages) { 15919 final int childCount = ps.childPackageNames.size(); 15920 outInfo.removedChildPackages = new ArrayMap<>(childCount); 15921 for (int i = 0; i < childCount; i++) { 15922 String childPackageName = ps.childPackageNames.get(i); 15923 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 15924 childInfo.removedPackage = childPackageName; 15925 outInfo.removedChildPackages.put(childPackageName, childInfo); 15926 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 15927 if (childPs != null) { 15928 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 15929 } 15930 } 15931 } 15932 } 15933 15934 boolean ret = false; 15935 if (isSystemApp(ps)) { 15936 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 15937 // When an updated system application is deleted we delete the existing resources 15938 // as well and fall back to existing code in system partition 15939 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 15940 } else { 15941 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 15942 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 15943 outInfo, writeSettings, replacingPackage); 15944 } 15945 15946 // Take a note whether we deleted the package for all users 15947 if (outInfo != null) { 15948 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 15949 if (outInfo.removedChildPackages != null) { 15950 synchronized (mPackages) { 15951 final int childCount = outInfo.removedChildPackages.size(); 15952 for (int i = 0; i < childCount; i++) { 15953 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 15954 if (childInfo != null) { 15955 childInfo.removedForAllUsers = mPackages.get( 15956 childInfo.removedPackage) == null; 15957 } 15958 } 15959 } 15960 } 15961 // If we uninstalled an update to a system app there may be some 15962 // child packages that appeared as they are declared in the system 15963 // app but were not declared in the update. 15964 if (isSystemApp(ps)) { 15965 synchronized (mPackages) { 15966 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 15967 final int childCount = (updatedPs.childPackageNames != null) 15968 ? updatedPs.childPackageNames.size() : 0; 15969 for (int i = 0; i < childCount; i++) { 15970 String childPackageName = updatedPs.childPackageNames.get(i); 15971 if (outInfo.removedChildPackages == null 15972 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 15973 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 15974 if (childPs == null) { 15975 continue; 15976 } 15977 PackageInstalledInfo installRes = new PackageInstalledInfo(); 15978 installRes.name = childPackageName; 15979 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 15980 installRes.pkg = mPackages.get(childPackageName); 15981 installRes.uid = childPs.pkg.applicationInfo.uid; 15982 if (outInfo.appearedChildPackages == null) { 15983 outInfo.appearedChildPackages = new ArrayMap<>(); 15984 } 15985 outInfo.appearedChildPackages.put(childPackageName, installRes); 15986 } 15987 } 15988 } 15989 } 15990 } 15991 15992 return ret; 15993 } 15994 15995 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 15996 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 15997 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 15998 for (int nextUserId : userIds) { 15999 if (DEBUG_REMOVE) { 16000 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 16001 } 16002 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 16003 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 16004 false /*hidden*/, false /*suspended*/, null, null, null, 16005 false /*blockUninstall*/, 16006 ps.readUserState(nextUserId).domainVerificationStatus, 0); 16007 } 16008 } 16009 16010 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 16011 PackageRemovedInfo outInfo) { 16012 final PackageParser.Package pkg; 16013 synchronized (mPackages) { 16014 pkg = mPackages.get(ps.name); 16015 } 16016 16017 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 16018 : new int[] {userId}; 16019 for (int nextUserId : userIds) { 16020 if (DEBUG_REMOVE) { 16021 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 16022 + nextUserId); 16023 } 16024 16025 destroyAppDataLIF(pkg, userId, 16026 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16027 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 16028 schedulePackageCleaning(ps.name, nextUserId, false); 16029 synchronized (mPackages) { 16030 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 16031 scheduleWritePackageRestrictionsLocked(nextUserId); 16032 } 16033 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 16034 } 16035 } 16036 16037 if (outInfo != null) { 16038 outInfo.removedPackage = ps.name; 16039 outInfo.removedAppId = ps.appId; 16040 outInfo.removedUsers = userIds; 16041 } 16042 16043 return true; 16044 } 16045 16046 private final class ClearStorageConnection implements ServiceConnection { 16047 IMediaContainerService mContainerService; 16048 16049 @Override 16050 public void onServiceConnected(ComponentName name, IBinder service) { 16051 synchronized (this) { 16052 mContainerService = IMediaContainerService.Stub.asInterface(service); 16053 notifyAll(); 16054 } 16055 } 16056 16057 @Override 16058 public void onServiceDisconnected(ComponentName name) { 16059 } 16060 } 16061 16062 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 16063 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 16064 16065 final boolean mounted; 16066 if (Environment.isExternalStorageEmulated()) { 16067 mounted = true; 16068 } else { 16069 final String status = Environment.getExternalStorageState(); 16070 16071 mounted = status.equals(Environment.MEDIA_MOUNTED) 16072 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 16073 } 16074 16075 if (!mounted) { 16076 return; 16077 } 16078 16079 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 16080 int[] users; 16081 if (userId == UserHandle.USER_ALL) { 16082 users = sUserManager.getUserIds(); 16083 } else { 16084 users = new int[] { userId }; 16085 } 16086 final ClearStorageConnection conn = new ClearStorageConnection(); 16087 if (mContext.bindServiceAsUser( 16088 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 16089 try { 16090 for (int curUser : users) { 16091 long timeout = SystemClock.uptimeMillis() + 5000; 16092 synchronized (conn) { 16093 long now = SystemClock.uptimeMillis(); 16094 while (conn.mContainerService == null && now < timeout) { 16095 try { 16096 conn.wait(timeout - now); 16097 } catch (InterruptedException e) { 16098 } 16099 } 16100 } 16101 if (conn.mContainerService == null) { 16102 return; 16103 } 16104 16105 final UserEnvironment userEnv = new UserEnvironment(curUser); 16106 clearDirectory(conn.mContainerService, 16107 userEnv.buildExternalStorageAppCacheDirs(packageName)); 16108 if (allData) { 16109 clearDirectory(conn.mContainerService, 16110 userEnv.buildExternalStorageAppDataDirs(packageName)); 16111 clearDirectory(conn.mContainerService, 16112 userEnv.buildExternalStorageAppMediaDirs(packageName)); 16113 } 16114 } 16115 } finally { 16116 mContext.unbindService(conn); 16117 } 16118 } 16119 } 16120 16121 @Override 16122 public void clearApplicationProfileData(String packageName) { 16123 enforceSystemOrRoot("Only the system can clear all profile data"); 16124 16125 final PackageParser.Package pkg; 16126 synchronized (mPackages) { 16127 pkg = mPackages.get(packageName); 16128 } 16129 16130 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 16131 synchronized (mInstallLock) { 16132 clearAppProfilesLIF(pkg); 16133 } 16134 } 16135 } 16136 16137 @Override 16138 public void clearApplicationUserData(final String packageName, 16139 final IPackageDataObserver observer, final int userId) { 16140 mContext.enforceCallingOrSelfPermission( 16141 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 16142 16143 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16144 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 16145 16146 final DevicePolicyManagerInternal dpmi = LocalServices 16147 .getService(DevicePolicyManagerInternal.class); 16148 if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) { 16149 throw new SecurityException("Cannot clear data for a device owner or a profile owner"); 16150 } 16151 // Queue up an async operation since the package deletion may take a little while. 16152 mHandler.post(new Runnable() { 16153 public void run() { 16154 mHandler.removeCallbacks(this); 16155 final boolean succeeded; 16156 try (PackageFreezer freezer = freezePackage(packageName, 16157 "clearApplicationUserData")) { 16158 synchronized (mInstallLock) { 16159 succeeded = clearApplicationUserDataLIF(packageName, userId); 16160 } 16161 clearExternalStorageDataSync(packageName, userId, true); 16162 } 16163 if (succeeded) { 16164 // invoke DeviceStorageMonitor's update method to clear any notifications 16165 DeviceStorageMonitorInternal dsm = LocalServices 16166 .getService(DeviceStorageMonitorInternal.class); 16167 if (dsm != null) { 16168 dsm.checkMemory(); 16169 } 16170 } 16171 if(observer != null) { 16172 try { 16173 observer.onRemoveCompleted(packageName, succeeded); 16174 } catch (RemoteException e) { 16175 Log.i(TAG, "Observer no longer exists."); 16176 } 16177 } //end if observer 16178 } //end run 16179 }); 16180 } 16181 16182 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 16183 if (packageName == null) { 16184 Slog.w(TAG, "Attempt to delete null packageName."); 16185 return false; 16186 } 16187 16188 // Try finding details about the requested package 16189 PackageParser.Package pkg; 16190 synchronized (mPackages) { 16191 pkg = mPackages.get(packageName); 16192 if (pkg == null) { 16193 final PackageSetting ps = mSettings.mPackages.get(packageName); 16194 if (ps != null) { 16195 pkg = ps.pkg; 16196 } 16197 } 16198 16199 if (pkg == null) { 16200 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16201 return false; 16202 } 16203 16204 PackageSetting ps = (PackageSetting) pkg.mExtras; 16205 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16206 } 16207 16208 clearAppDataLIF(pkg, userId, 16209 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16210 16211 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16212 removeKeystoreDataIfNeeded(userId, appId); 16213 16214 final UserManager um = mContext.getSystemService(UserManager.class); 16215 final int flags; 16216 if (um.isUserUnlockingOrUnlocked(userId)) { 16217 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 16218 } else if (um.isUserRunning(userId)) { 16219 flags = StorageManager.FLAG_STORAGE_DE; 16220 } else { 16221 flags = 0; 16222 } 16223 prepareAppDataContentsLIF(pkg, userId, flags); 16224 16225 return true; 16226 } 16227 16228 /** 16229 * Reverts user permission state changes (permissions and flags) in 16230 * all packages for a given user. 16231 * 16232 * @param userId The device user for which to do a reset. 16233 */ 16234 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 16235 final int packageCount = mPackages.size(); 16236 for (int i = 0; i < packageCount; i++) { 16237 PackageParser.Package pkg = mPackages.valueAt(i); 16238 PackageSetting ps = (PackageSetting) pkg.mExtras; 16239 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16240 } 16241 } 16242 16243 private void resetNetworkPolicies(int userId) { 16244 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 16245 } 16246 16247 /** 16248 * Reverts user permission state changes (permissions and flags). 16249 * 16250 * @param ps The package for which to reset. 16251 * @param userId The device user for which to do a reset. 16252 */ 16253 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 16254 final PackageSetting ps, final int userId) { 16255 if (ps.pkg == null) { 16256 return; 16257 } 16258 16259 // These are flags that can change base on user actions. 16260 final int userSettableMask = FLAG_PERMISSION_USER_SET 16261 | FLAG_PERMISSION_USER_FIXED 16262 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 16263 | FLAG_PERMISSION_REVIEW_REQUIRED; 16264 16265 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 16266 | FLAG_PERMISSION_POLICY_FIXED; 16267 16268 boolean writeInstallPermissions = false; 16269 boolean writeRuntimePermissions = false; 16270 16271 final int permissionCount = ps.pkg.requestedPermissions.size(); 16272 for (int i = 0; i < permissionCount; i++) { 16273 String permission = ps.pkg.requestedPermissions.get(i); 16274 16275 BasePermission bp = mSettings.mPermissions.get(permission); 16276 if (bp == null) { 16277 continue; 16278 } 16279 16280 // If shared user we just reset the state to which only this app contributed. 16281 if (ps.sharedUser != null) { 16282 boolean used = false; 16283 final int packageCount = ps.sharedUser.packages.size(); 16284 for (int j = 0; j < packageCount; j++) { 16285 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 16286 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 16287 && pkg.pkg.requestedPermissions.contains(permission)) { 16288 used = true; 16289 break; 16290 } 16291 } 16292 if (used) { 16293 continue; 16294 } 16295 } 16296 16297 PermissionsState permissionsState = ps.getPermissionsState(); 16298 16299 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 16300 16301 // Always clear the user settable flags. 16302 final boolean hasInstallState = permissionsState.getInstallPermissionState( 16303 bp.name) != null; 16304 // If permission review is enabled and this is a legacy app, mark the 16305 // permission as requiring a review as this is the initial state. 16306 int flags = 0; 16307 if (Build.PERMISSIONS_REVIEW_REQUIRED 16308 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 16309 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 16310 } 16311 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 16312 if (hasInstallState) { 16313 writeInstallPermissions = true; 16314 } else { 16315 writeRuntimePermissions = true; 16316 } 16317 } 16318 16319 // Below is only runtime permission handling. 16320 if (!bp.isRuntime()) { 16321 continue; 16322 } 16323 16324 // Never clobber system or policy. 16325 if ((oldFlags & policyOrSystemFlags) != 0) { 16326 continue; 16327 } 16328 16329 // If this permission was granted by default, make sure it is. 16330 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 16331 if (permissionsState.grantRuntimePermission(bp, userId) 16332 != PERMISSION_OPERATION_FAILURE) { 16333 writeRuntimePermissions = true; 16334 } 16335 // If permission review is enabled the permissions for a legacy apps 16336 // are represented as constantly granted runtime ones, so don't revoke. 16337 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 16338 // Otherwise, reset the permission. 16339 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 16340 switch (revokeResult) { 16341 case PERMISSION_OPERATION_SUCCESS: 16342 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 16343 writeRuntimePermissions = true; 16344 final int appId = ps.appId; 16345 mHandler.post(new Runnable() { 16346 @Override 16347 public void run() { 16348 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 16349 } 16350 }); 16351 } break; 16352 } 16353 } 16354 } 16355 16356 // Synchronously write as we are taking permissions away. 16357 if (writeRuntimePermissions) { 16358 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 16359 } 16360 16361 // Synchronously write as we are taking permissions away. 16362 if (writeInstallPermissions) { 16363 mSettings.writeLPr(); 16364 } 16365 } 16366 16367 /** 16368 * Remove entries from the keystore daemon. Will only remove it if the 16369 * {@code appId} is valid. 16370 */ 16371 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 16372 if (appId < 0) { 16373 return; 16374 } 16375 16376 final KeyStore keyStore = KeyStore.getInstance(); 16377 if (keyStore != null) { 16378 if (userId == UserHandle.USER_ALL) { 16379 for (final int individual : sUserManager.getUserIds()) { 16380 keyStore.clearUid(UserHandle.getUid(individual, appId)); 16381 } 16382 } else { 16383 keyStore.clearUid(UserHandle.getUid(userId, appId)); 16384 } 16385 } else { 16386 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 16387 } 16388 } 16389 16390 @Override 16391 public void deleteApplicationCacheFiles(final String packageName, 16392 final IPackageDataObserver observer) { 16393 final int userId = UserHandle.getCallingUserId(); 16394 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 16395 } 16396 16397 @Override 16398 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 16399 final IPackageDataObserver observer) { 16400 mContext.enforceCallingOrSelfPermission( 16401 android.Manifest.permission.DELETE_CACHE_FILES, null); 16402 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16403 /* requireFullPermission= */ true, /* checkShell= */ false, 16404 "delete application cache files"); 16405 16406 final PackageParser.Package pkg; 16407 synchronized (mPackages) { 16408 pkg = mPackages.get(packageName); 16409 } 16410 16411 // Queue up an async operation since the package deletion may take a little while. 16412 mHandler.post(new Runnable() { 16413 public void run() { 16414 synchronized (mInstallLock) { 16415 final int flags = StorageManager.FLAG_STORAGE_DE 16416 | StorageManager.FLAG_STORAGE_CE; 16417 // We're only clearing cache files, so we don't care if the 16418 // app is unfrozen and still able to run 16419 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 16420 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16421 } 16422 clearExternalStorageDataSync(packageName, userId, false); 16423 if (observer != null) { 16424 try { 16425 observer.onRemoveCompleted(packageName, true); 16426 } catch (RemoteException e) { 16427 Log.i(TAG, "Observer no longer exists."); 16428 } 16429 } 16430 } 16431 }); 16432 } 16433 16434 @Override 16435 public void getPackageSizeInfo(final String packageName, int userHandle, 16436 final IPackageStatsObserver observer) { 16437 mContext.enforceCallingOrSelfPermission( 16438 android.Manifest.permission.GET_PACKAGE_SIZE, null); 16439 if (packageName == null) { 16440 throw new IllegalArgumentException("Attempt to get size of null packageName"); 16441 } 16442 16443 PackageStats stats = new PackageStats(packageName, userHandle); 16444 16445 /* 16446 * Queue up an async operation since the package measurement may take a 16447 * little while. 16448 */ 16449 Message msg = mHandler.obtainMessage(INIT_COPY); 16450 msg.obj = new MeasureParams(stats, observer); 16451 mHandler.sendMessage(msg); 16452 } 16453 16454 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 16455 final PackageSetting ps; 16456 synchronized (mPackages) { 16457 ps = mSettings.mPackages.get(packageName); 16458 if (ps == null) { 16459 Slog.w(TAG, "Failed to find settings for " + packageName); 16460 return false; 16461 } 16462 } 16463 try { 16464 mInstaller.getAppSize(ps.volumeUuid, packageName, userId, 16465 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 16466 ps.getCeDataInode(userId), ps.codePathString, stats); 16467 } catch (InstallerException e) { 16468 Slog.w(TAG, String.valueOf(e)); 16469 return false; 16470 } 16471 16472 // For now, ignore code size of packages on system partition 16473 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 16474 stats.codeSize = 0; 16475 } 16476 16477 return true; 16478 } 16479 16480 private int getUidTargetSdkVersionLockedLPr(int uid) { 16481 Object obj = mSettings.getUserIdLPr(uid); 16482 if (obj instanceof SharedUserSetting) { 16483 final SharedUserSetting sus = (SharedUserSetting) obj; 16484 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 16485 final Iterator<PackageSetting> it = sus.packages.iterator(); 16486 while (it.hasNext()) { 16487 final PackageSetting ps = it.next(); 16488 if (ps.pkg != null) { 16489 int v = ps.pkg.applicationInfo.targetSdkVersion; 16490 if (v < vers) vers = v; 16491 } 16492 } 16493 return vers; 16494 } else if (obj instanceof PackageSetting) { 16495 final PackageSetting ps = (PackageSetting) obj; 16496 if (ps.pkg != null) { 16497 return ps.pkg.applicationInfo.targetSdkVersion; 16498 } 16499 } 16500 return Build.VERSION_CODES.CUR_DEVELOPMENT; 16501 } 16502 16503 @Override 16504 public void addPreferredActivity(IntentFilter filter, int match, 16505 ComponentName[] set, ComponentName activity, int userId) { 16506 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16507 "Adding preferred"); 16508 } 16509 16510 private void addPreferredActivityInternal(IntentFilter filter, int match, 16511 ComponentName[] set, ComponentName activity, boolean always, int userId, 16512 String opname) { 16513 // writer 16514 int callingUid = Binder.getCallingUid(); 16515 enforceCrossUserPermission(callingUid, userId, 16516 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 16517 if (filter.countActions() == 0) { 16518 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16519 return; 16520 } 16521 synchronized (mPackages) { 16522 if (mContext.checkCallingOrSelfPermission( 16523 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16524 != PackageManager.PERMISSION_GRANTED) { 16525 if (getUidTargetSdkVersionLockedLPr(callingUid) 16526 < Build.VERSION_CODES.FROYO) { 16527 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 16528 + callingUid); 16529 return; 16530 } 16531 mContext.enforceCallingOrSelfPermission( 16532 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16533 } 16534 16535 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 16536 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 16537 + userId + ":"); 16538 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16539 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 16540 scheduleWritePackageRestrictionsLocked(userId); 16541 } 16542 } 16543 16544 @Override 16545 public void replacePreferredActivity(IntentFilter filter, int match, 16546 ComponentName[] set, ComponentName activity, int userId) { 16547 if (filter.countActions() != 1) { 16548 throw new IllegalArgumentException( 16549 "replacePreferredActivity expects filter to have only 1 action."); 16550 } 16551 if (filter.countDataAuthorities() != 0 16552 || filter.countDataPaths() != 0 16553 || filter.countDataSchemes() > 1 16554 || filter.countDataTypes() != 0) { 16555 throw new IllegalArgumentException( 16556 "replacePreferredActivity expects filter to have no data authorities, " + 16557 "paths, or types; and at most one scheme."); 16558 } 16559 16560 final int callingUid = Binder.getCallingUid(); 16561 enforceCrossUserPermission(callingUid, userId, 16562 true /* requireFullPermission */, false /* checkShell */, 16563 "replace preferred activity"); 16564 synchronized (mPackages) { 16565 if (mContext.checkCallingOrSelfPermission( 16566 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16567 != PackageManager.PERMISSION_GRANTED) { 16568 if (getUidTargetSdkVersionLockedLPr(callingUid) 16569 < Build.VERSION_CODES.FROYO) { 16570 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 16571 + Binder.getCallingUid()); 16572 return; 16573 } 16574 mContext.enforceCallingOrSelfPermission( 16575 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16576 } 16577 16578 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16579 if (pir != null) { 16580 // Get all of the existing entries that exactly match this filter. 16581 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 16582 if (existing != null && existing.size() == 1) { 16583 PreferredActivity cur = existing.get(0); 16584 if (DEBUG_PREFERRED) { 16585 Slog.i(TAG, "Checking replace of preferred:"); 16586 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16587 if (!cur.mPref.mAlways) { 16588 Slog.i(TAG, " -- CUR; not mAlways!"); 16589 } else { 16590 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 16591 Slog.i(TAG, " -- CUR: mSet=" 16592 + Arrays.toString(cur.mPref.mSetComponents)); 16593 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 16594 Slog.i(TAG, " -- NEW: mMatch=" 16595 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 16596 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 16597 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 16598 } 16599 } 16600 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 16601 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 16602 && cur.mPref.sameSet(set)) { 16603 // Setting the preferred activity to what it happens to be already 16604 if (DEBUG_PREFERRED) { 16605 Slog.i(TAG, "Replacing with same preferred activity " 16606 + cur.mPref.mShortComponent + " for user " 16607 + userId + ":"); 16608 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16609 } 16610 return; 16611 } 16612 } 16613 16614 if (existing != null) { 16615 if (DEBUG_PREFERRED) { 16616 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 16617 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16618 } 16619 for (int i = 0; i < existing.size(); i++) { 16620 PreferredActivity pa = existing.get(i); 16621 if (DEBUG_PREFERRED) { 16622 Slog.i(TAG, "Removing existing preferred activity " 16623 + pa.mPref.mComponent + ":"); 16624 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 16625 } 16626 pir.removeFilter(pa); 16627 } 16628 } 16629 } 16630 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16631 "Replacing preferred"); 16632 } 16633 } 16634 16635 @Override 16636 public void clearPackagePreferredActivities(String packageName) { 16637 final int uid = Binder.getCallingUid(); 16638 // writer 16639 synchronized (mPackages) { 16640 PackageParser.Package pkg = mPackages.get(packageName); 16641 if (pkg == null || pkg.applicationInfo.uid != uid) { 16642 if (mContext.checkCallingOrSelfPermission( 16643 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16644 != PackageManager.PERMISSION_GRANTED) { 16645 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 16646 < Build.VERSION_CODES.FROYO) { 16647 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 16648 + Binder.getCallingUid()); 16649 return; 16650 } 16651 mContext.enforceCallingOrSelfPermission( 16652 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16653 } 16654 } 16655 16656 int user = UserHandle.getCallingUserId(); 16657 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 16658 scheduleWritePackageRestrictionsLocked(user); 16659 } 16660 } 16661 } 16662 16663 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16664 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 16665 ArrayList<PreferredActivity> removed = null; 16666 boolean changed = false; 16667 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16668 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 16669 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16670 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 16671 continue; 16672 } 16673 Iterator<PreferredActivity> it = pir.filterIterator(); 16674 while (it.hasNext()) { 16675 PreferredActivity pa = it.next(); 16676 // Mark entry for removal only if it matches the package name 16677 // and the entry is of type "always". 16678 if (packageName == null || 16679 (pa.mPref.mComponent.getPackageName().equals(packageName) 16680 && pa.mPref.mAlways)) { 16681 if (removed == null) { 16682 removed = new ArrayList<PreferredActivity>(); 16683 } 16684 removed.add(pa); 16685 } 16686 } 16687 if (removed != null) { 16688 for (int j=0; j<removed.size(); j++) { 16689 PreferredActivity pa = removed.get(j); 16690 pir.removeFilter(pa); 16691 } 16692 changed = true; 16693 } 16694 } 16695 return changed; 16696 } 16697 16698 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16699 private void clearIntentFilterVerificationsLPw(int userId) { 16700 final int packageCount = mPackages.size(); 16701 for (int i = 0; i < packageCount; i++) { 16702 PackageParser.Package pkg = mPackages.valueAt(i); 16703 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 16704 } 16705 } 16706 16707 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16708 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 16709 if (userId == UserHandle.USER_ALL) { 16710 if (mSettings.removeIntentFilterVerificationLPw(packageName, 16711 sUserManager.getUserIds())) { 16712 for (int oneUserId : sUserManager.getUserIds()) { 16713 scheduleWritePackageRestrictionsLocked(oneUserId); 16714 } 16715 } 16716 } else { 16717 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 16718 scheduleWritePackageRestrictionsLocked(userId); 16719 } 16720 } 16721 } 16722 16723 void clearDefaultBrowserIfNeeded(String packageName) { 16724 for (int oneUserId : sUserManager.getUserIds()) { 16725 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 16726 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 16727 if (packageName.equals(defaultBrowserPackageName)) { 16728 setDefaultBrowserPackageName(null, oneUserId); 16729 } 16730 } 16731 } 16732 16733 @Override 16734 public void resetApplicationPreferences(int userId) { 16735 mContext.enforceCallingOrSelfPermission( 16736 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16737 final long identity = Binder.clearCallingIdentity(); 16738 // writer 16739 try { 16740 synchronized (mPackages) { 16741 clearPackagePreferredActivitiesLPw(null, userId); 16742 mSettings.applyDefaultPreferredAppsLPw(this, userId); 16743 // TODO: We have to reset the default SMS and Phone. This requires 16744 // significant refactoring to keep all default apps in the package 16745 // manager (cleaner but more work) or have the services provide 16746 // callbacks to the package manager to request a default app reset. 16747 applyFactoryDefaultBrowserLPw(userId); 16748 clearIntentFilterVerificationsLPw(userId); 16749 primeDomainVerificationsLPw(userId); 16750 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 16751 scheduleWritePackageRestrictionsLocked(userId); 16752 } 16753 resetNetworkPolicies(userId); 16754 } finally { 16755 Binder.restoreCallingIdentity(identity); 16756 } 16757 } 16758 16759 @Override 16760 public int getPreferredActivities(List<IntentFilter> outFilters, 16761 List<ComponentName> outActivities, String packageName) { 16762 16763 int num = 0; 16764 final int userId = UserHandle.getCallingUserId(); 16765 // reader 16766 synchronized (mPackages) { 16767 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16768 if (pir != null) { 16769 final Iterator<PreferredActivity> it = pir.filterIterator(); 16770 while (it.hasNext()) { 16771 final PreferredActivity pa = it.next(); 16772 if (packageName == null 16773 || (pa.mPref.mComponent.getPackageName().equals(packageName) 16774 && pa.mPref.mAlways)) { 16775 if (outFilters != null) { 16776 outFilters.add(new IntentFilter(pa)); 16777 } 16778 if (outActivities != null) { 16779 outActivities.add(pa.mPref.mComponent); 16780 } 16781 } 16782 } 16783 } 16784 } 16785 16786 return num; 16787 } 16788 16789 @Override 16790 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 16791 int userId) { 16792 int callingUid = Binder.getCallingUid(); 16793 if (callingUid != Process.SYSTEM_UID) { 16794 throw new SecurityException( 16795 "addPersistentPreferredActivity can only be run by the system"); 16796 } 16797 if (filter.countActions() == 0) { 16798 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16799 return; 16800 } 16801 synchronized (mPackages) { 16802 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 16803 ":"); 16804 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16805 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 16806 new PersistentPreferredActivity(filter, activity)); 16807 scheduleWritePackageRestrictionsLocked(userId); 16808 } 16809 } 16810 16811 @Override 16812 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 16813 int callingUid = Binder.getCallingUid(); 16814 if (callingUid != Process.SYSTEM_UID) { 16815 throw new SecurityException( 16816 "clearPackagePersistentPreferredActivities can only be run by the system"); 16817 } 16818 ArrayList<PersistentPreferredActivity> removed = null; 16819 boolean changed = false; 16820 synchronized (mPackages) { 16821 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 16822 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 16823 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 16824 .valueAt(i); 16825 if (userId != thisUserId) { 16826 continue; 16827 } 16828 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 16829 while (it.hasNext()) { 16830 PersistentPreferredActivity ppa = it.next(); 16831 // Mark entry for removal only if it matches the package name. 16832 if (ppa.mComponent.getPackageName().equals(packageName)) { 16833 if (removed == null) { 16834 removed = new ArrayList<PersistentPreferredActivity>(); 16835 } 16836 removed.add(ppa); 16837 } 16838 } 16839 if (removed != null) { 16840 for (int j=0; j<removed.size(); j++) { 16841 PersistentPreferredActivity ppa = removed.get(j); 16842 ppir.removeFilter(ppa); 16843 } 16844 changed = true; 16845 } 16846 } 16847 16848 if (changed) { 16849 scheduleWritePackageRestrictionsLocked(userId); 16850 } 16851 } 16852 } 16853 16854 /** 16855 * Common machinery for picking apart a restored XML blob and passing 16856 * it to a caller-supplied functor to be applied to the running system. 16857 */ 16858 private void restoreFromXml(XmlPullParser parser, int userId, 16859 String expectedStartTag, BlobXmlRestorer functor) 16860 throws IOException, XmlPullParserException { 16861 int type; 16862 while ((type = parser.next()) != XmlPullParser.START_TAG 16863 && type != XmlPullParser.END_DOCUMENT) { 16864 } 16865 if (type != XmlPullParser.START_TAG) { 16866 // oops didn't find a start tag?! 16867 if (DEBUG_BACKUP) { 16868 Slog.e(TAG, "Didn't find start tag during restore"); 16869 } 16870 return; 16871 } 16872Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 16873 // this is supposed to be TAG_PREFERRED_BACKUP 16874 if (!expectedStartTag.equals(parser.getName())) { 16875 if (DEBUG_BACKUP) { 16876 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 16877 } 16878 return; 16879 } 16880 16881 // skip interfering stuff, then we're aligned with the backing implementation 16882 while ((type = parser.next()) == XmlPullParser.TEXT) { } 16883Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 16884 functor.apply(parser, userId); 16885 } 16886 16887 private interface BlobXmlRestorer { 16888 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 16889 } 16890 16891 /** 16892 * Non-Binder method, support for the backup/restore mechanism: write the 16893 * full set of preferred activities in its canonical XML format. Returns the 16894 * XML output as a byte array, or null if there is none. 16895 */ 16896 @Override 16897 public byte[] getPreferredActivityBackup(int userId) { 16898 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16899 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 16900 } 16901 16902 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16903 try { 16904 final XmlSerializer serializer = new FastXmlSerializer(); 16905 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16906 serializer.startDocument(null, true); 16907 serializer.startTag(null, TAG_PREFERRED_BACKUP); 16908 16909 synchronized (mPackages) { 16910 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 16911 } 16912 16913 serializer.endTag(null, TAG_PREFERRED_BACKUP); 16914 serializer.endDocument(); 16915 serializer.flush(); 16916 } catch (Exception e) { 16917 if (DEBUG_BACKUP) { 16918 Slog.e(TAG, "Unable to write preferred activities for backup", e); 16919 } 16920 return null; 16921 } 16922 16923 return dataStream.toByteArray(); 16924 } 16925 16926 @Override 16927 public void restorePreferredActivities(byte[] backup, int userId) { 16928 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16929 throw new SecurityException("Only the system may call restorePreferredActivities()"); 16930 } 16931 16932 try { 16933 final XmlPullParser parser = Xml.newPullParser(); 16934 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16935 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 16936 new BlobXmlRestorer() { 16937 @Override 16938 public void apply(XmlPullParser parser, int userId) 16939 throws XmlPullParserException, IOException { 16940 synchronized (mPackages) { 16941 mSettings.readPreferredActivitiesLPw(parser, userId); 16942 } 16943 } 16944 } ); 16945 } catch (Exception e) { 16946 if (DEBUG_BACKUP) { 16947 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16948 } 16949 } 16950 } 16951 16952 /** 16953 * Non-Binder method, support for the backup/restore mechanism: write the 16954 * default browser (etc) settings in its canonical XML format. Returns the default 16955 * browser XML representation as a byte array, or null if there is none. 16956 */ 16957 @Override 16958 public byte[] getDefaultAppsBackup(int userId) { 16959 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16960 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 16961 } 16962 16963 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16964 try { 16965 final XmlSerializer serializer = new FastXmlSerializer(); 16966 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16967 serializer.startDocument(null, true); 16968 serializer.startTag(null, TAG_DEFAULT_APPS); 16969 16970 synchronized (mPackages) { 16971 mSettings.writeDefaultAppsLPr(serializer, userId); 16972 } 16973 16974 serializer.endTag(null, TAG_DEFAULT_APPS); 16975 serializer.endDocument(); 16976 serializer.flush(); 16977 } catch (Exception e) { 16978 if (DEBUG_BACKUP) { 16979 Slog.e(TAG, "Unable to write default apps for backup", e); 16980 } 16981 return null; 16982 } 16983 16984 return dataStream.toByteArray(); 16985 } 16986 16987 @Override 16988 public void restoreDefaultApps(byte[] backup, int userId) { 16989 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16990 throw new SecurityException("Only the system may call restoreDefaultApps()"); 16991 } 16992 16993 try { 16994 final XmlPullParser parser = Xml.newPullParser(); 16995 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16996 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 16997 new BlobXmlRestorer() { 16998 @Override 16999 public void apply(XmlPullParser parser, int userId) 17000 throws XmlPullParserException, IOException { 17001 synchronized (mPackages) { 17002 mSettings.readDefaultAppsLPw(parser, userId); 17003 } 17004 } 17005 } ); 17006 } catch (Exception e) { 17007 if (DEBUG_BACKUP) { 17008 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 17009 } 17010 } 17011 } 17012 17013 @Override 17014 public byte[] getIntentFilterVerificationBackup(int userId) { 17015 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17016 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 17017 } 17018 17019 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17020 try { 17021 final XmlSerializer serializer = new FastXmlSerializer(); 17022 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17023 serializer.startDocument(null, true); 17024 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 17025 17026 synchronized (mPackages) { 17027 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 17028 } 17029 17030 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 17031 serializer.endDocument(); 17032 serializer.flush(); 17033 } catch (Exception e) { 17034 if (DEBUG_BACKUP) { 17035 Slog.e(TAG, "Unable to write default apps for backup", e); 17036 } 17037 return null; 17038 } 17039 17040 return dataStream.toByteArray(); 17041 } 17042 17043 @Override 17044 public void restoreIntentFilterVerification(byte[] backup, int userId) { 17045 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17046 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17047 } 17048 17049 try { 17050 final XmlPullParser parser = Xml.newPullParser(); 17051 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17052 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 17053 new BlobXmlRestorer() { 17054 @Override 17055 public void apply(XmlPullParser parser, int userId) 17056 throws XmlPullParserException, IOException { 17057 synchronized (mPackages) { 17058 mSettings.readAllDomainVerificationsLPr(parser, userId); 17059 mSettings.writeLPr(); 17060 } 17061 } 17062 } ); 17063 } catch (Exception e) { 17064 if (DEBUG_BACKUP) { 17065 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17066 } 17067 } 17068 } 17069 17070 @Override 17071 public byte[] getPermissionGrantBackup(int userId) { 17072 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17073 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 17074 } 17075 17076 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17077 try { 17078 final XmlSerializer serializer = new FastXmlSerializer(); 17079 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17080 serializer.startDocument(null, true); 17081 serializer.startTag(null, TAG_PERMISSION_BACKUP); 17082 17083 synchronized (mPackages) { 17084 serializeRuntimePermissionGrantsLPr(serializer, userId); 17085 } 17086 17087 serializer.endTag(null, TAG_PERMISSION_BACKUP); 17088 serializer.endDocument(); 17089 serializer.flush(); 17090 } catch (Exception e) { 17091 if (DEBUG_BACKUP) { 17092 Slog.e(TAG, "Unable to write default apps for backup", e); 17093 } 17094 return null; 17095 } 17096 17097 return dataStream.toByteArray(); 17098 } 17099 17100 @Override 17101 public void restorePermissionGrants(byte[] backup, int userId) { 17102 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17103 throw new SecurityException("Only the system may call restorePermissionGrants()"); 17104 } 17105 17106 try { 17107 final XmlPullParser parser = Xml.newPullParser(); 17108 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17109 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 17110 new BlobXmlRestorer() { 17111 @Override 17112 public void apply(XmlPullParser parser, int userId) 17113 throws XmlPullParserException, IOException { 17114 synchronized (mPackages) { 17115 processRestoredPermissionGrantsLPr(parser, userId); 17116 } 17117 } 17118 } ); 17119 } catch (Exception e) { 17120 if (DEBUG_BACKUP) { 17121 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17122 } 17123 } 17124 } 17125 17126 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 17127 throws IOException { 17128 serializer.startTag(null, TAG_ALL_GRANTS); 17129 17130 final int N = mSettings.mPackages.size(); 17131 for (int i = 0; i < N; i++) { 17132 final PackageSetting ps = mSettings.mPackages.valueAt(i); 17133 boolean pkgGrantsKnown = false; 17134 17135 PermissionsState packagePerms = ps.getPermissionsState(); 17136 17137 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 17138 final int grantFlags = state.getFlags(); 17139 // only look at grants that are not system/policy fixed 17140 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 17141 final boolean isGranted = state.isGranted(); 17142 // And only back up the user-twiddled state bits 17143 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 17144 final String packageName = mSettings.mPackages.keyAt(i); 17145 if (!pkgGrantsKnown) { 17146 serializer.startTag(null, TAG_GRANT); 17147 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 17148 pkgGrantsKnown = true; 17149 } 17150 17151 final boolean userSet = 17152 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 17153 final boolean userFixed = 17154 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 17155 final boolean revoke = 17156 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 17157 17158 serializer.startTag(null, TAG_PERMISSION); 17159 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 17160 if (isGranted) { 17161 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 17162 } 17163 if (userSet) { 17164 serializer.attribute(null, ATTR_USER_SET, "true"); 17165 } 17166 if (userFixed) { 17167 serializer.attribute(null, ATTR_USER_FIXED, "true"); 17168 } 17169 if (revoke) { 17170 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 17171 } 17172 serializer.endTag(null, TAG_PERMISSION); 17173 } 17174 } 17175 } 17176 17177 if (pkgGrantsKnown) { 17178 serializer.endTag(null, TAG_GRANT); 17179 } 17180 } 17181 17182 serializer.endTag(null, TAG_ALL_GRANTS); 17183 } 17184 17185 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 17186 throws XmlPullParserException, IOException { 17187 String pkgName = null; 17188 int outerDepth = parser.getDepth(); 17189 int type; 17190 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 17191 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 17192 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 17193 continue; 17194 } 17195 17196 final String tagName = parser.getName(); 17197 if (tagName.equals(TAG_GRANT)) { 17198 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 17199 if (DEBUG_BACKUP) { 17200 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 17201 } 17202 } else if (tagName.equals(TAG_PERMISSION)) { 17203 17204 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 17205 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 17206 17207 int newFlagSet = 0; 17208 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 17209 newFlagSet |= FLAG_PERMISSION_USER_SET; 17210 } 17211 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 17212 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 17213 } 17214 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 17215 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 17216 } 17217 if (DEBUG_BACKUP) { 17218 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 17219 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 17220 } 17221 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17222 if (ps != null) { 17223 // Already installed so we apply the grant immediately 17224 if (DEBUG_BACKUP) { 17225 Slog.v(TAG, " + already installed; applying"); 17226 } 17227 PermissionsState perms = ps.getPermissionsState(); 17228 BasePermission bp = mSettings.mPermissions.get(permName); 17229 if (bp != null) { 17230 if (isGranted) { 17231 perms.grantRuntimePermission(bp, userId); 17232 } 17233 if (newFlagSet != 0) { 17234 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 17235 } 17236 } 17237 } else { 17238 // Need to wait for post-restore install to apply the grant 17239 if (DEBUG_BACKUP) { 17240 Slog.v(TAG, " - not yet installed; saving for later"); 17241 } 17242 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 17243 isGranted, newFlagSet, userId); 17244 } 17245 } else { 17246 PackageManagerService.reportSettingsProblem(Log.WARN, 17247 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 17248 XmlUtils.skipCurrentTag(parser); 17249 } 17250 } 17251 17252 scheduleWriteSettingsLocked(); 17253 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 17254 } 17255 17256 @Override 17257 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 17258 int sourceUserId, int targetUserId, int flags) { 17259 mContext.enforceCallingOrSelfPermission( 17260 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17261 int callingUid = Binder.getCallingUid(); 17262 enforceOwnerRights(ownerPackage, callingUid); 17263 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17264 if (intentFilter.countActions() == 0) { 17265 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 17266 return; 17267 } 17268 synchronized (mPackages) { 17269 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 17270 ownerPackage, targetUserId, flags); 17271 CrossProfileIntentResolver resolver = 17272 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17273 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 17274 // We have all those whose filter is equal. Now checking if the rest is equal as well. 17275 if (existing != null) { 17276 int size = existing.size(); 17277 for (int i = 0; i < size; i++) { 17278 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 17279 return; 17280 } 17281 } 17282 } 17283 resolver.addFilter(newFilter); 17284 scheduleWritePackageRestrictionsLocked(sourceUserId); 17285 } 17286 } 17287 17288 @Override 17289 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 17290 mContext.enforceCallingOrSelfPermission( 17291 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17292 int callingUid = Binder.getCallingUid(); 17293 enforceOwnerRights(ownerPackage, callingUid); 17294 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17295 synchronized (mPackages) { 17296 CrossProfileIntentResolver resolver = 17297 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17298 ArraySet<CrossProfileIntentFilter> set = 17299 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 17300 for (CrossProfileIntentFilter filter : set) { 17301 if (filter.getOwnerPackage().equals(ownerPackage)) { 17302 resolver.removeFilter(filter); 17303 } 17304 } 17305 scheduleWritePackageRestrictionsLocked(sourceUserId); 17306 } 17307 } 17308 17309 // Enforcing that callingUid is owning pkg on userId 17310 private void enforceOwnerRights(String pkg, int callingUid) { 17311 // The system owns everything. 17312 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 17313 return; 17314 } 17315 int callingUserId = UserHandle.getUserId(callingUid); 17316 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 17317 if (pi == null) { 17318 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 17319 + callingUserId); 17320 } 17321 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 17322 throw new SecurityException("Calling uid " + callingUid 17323 + " does not own package " + pkg); 17324 } 17325 } 17326 17327 @Override 17328 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 17329 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 17330 } 17331 17332 private Intent getHomeIntent() { 17333 Intent intent = new Intent(Intent.ACTION_MAIN); 17334 intent.addCategory(Intent.CATEGORY_HOME); 17335 return intent; 17336 } 17337 17338 private IntentFilter getHomeFilter() { 17339 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 17340 filter.addCategory(Intent.CATEGORY_HOME); 17341 filter.addCategory(Intent.CATEGORY_DEFAULT); 17342 return filter; 17343 } 17344 17345 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 17346 int userId) { 17347 Intent intent = getHomeIntent(); 17348 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 17349 PackageManager.GET_META_DATA, userId); 17350 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 17351 true, false, false, userId); 17352 17353 allHomeCandidates.clear(); 17354 if (list != null) { 17355 for (ResolveInfo ri : list) { 17356 allHomeCandidates.add(ri); 17357 } 17358 } 17359 return (preferred == null || preferred.activityInfo == null) 17360 ? null 17361 : new ComponentName(preferred.activityInfo.packageName, 17362 preferred.activityInfo.name); 17363 } 17364 17365 @Override 17366 public void setHomeActivity(ComponentName comp, int userId) { 17367 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 17368 getHomeActivitiesAsUser(homeActivities, userId); 17369 17370 boolean found = false; 17371 17372 final int size = homeActivities.size(); 17373 final ComponentName[] set = new ComponentName[size]; 17374 for (int i = 0; i < size; i++) { 17375 final ResolveInfo candidate = homeActivities.get(i); 17376 final ActivityInfo info = candidate.activityInfo; 17377 final ComponentName activityName = new ComponentName(info.packageName, info.name); 17378 set[i] = activityName; 17379 if (!found && activityName.equals(comp)) { 17380 found = true; 17381 } 17382 } 17383 if (!found) { 17384 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 17385 + userId); 17386 } 17387 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 17388 set, comp, userId); 17389 } 17390 17391 private @Nullable String getSetupWizardPackageName() { 17392 final Intent intent = new Intent(Intent.ACTION_MAIN); 17393 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 17394 17395 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 17396 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 17397 | MATCH_DISABLED_COMPONENTS, 17398 UserHandle.myUserId()); 17399 if (matches.size() == 1) { 17400 return matches.get(0).getComponentInfo().packageName; 17401 } else { 17402 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 17403 + ": matches=" + matches); 17404 return null; 17405 } 17406 } 17407 17408 @Override 17409 public void setApplicationEnabledSetting(String appPackageName, 17410 int newState, int flags, int userId, String callingPackage) { 17411 if (!sUserManager.exists(userId)) return; 17412 if (callingPackage == null) { 17413 callingPackage = Integer.toString(Binder.getCallingUid()); 17414 } 17415 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 17416 } 17417 17418 @Override 17419 public void setComponentEnabledSetting(ComponentName componentName, 17420 int newState, int flags, int userId) { 17421 if (!sUserManager.exists(userId)) return; 17422 setEnabledSetting(componentName.getPackageName(), 17423 componentName.getClassName(), newState, flags, userId, null); 17424 } 17425 17426 private void setEnabledSetting(final String packageName, String className, int newState, 17427 final int flags, int userId, String callingPackage) { 17428 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 17429 || newState == COMPONENT_ENABLED_STATE_ENABLED 17430 || newState == COMPONENT_ENABLED_STATE_DISABLED 17431 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17432 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 17433 throw new IllegalArgumentException("Invalid new component state: " 17434 + newState); 17435 } 17436 PackageSetting pkgSetting; 17437 final int uid = Binder.getCallingUid(); 17438 final int permission; 17439 if (uid == Process.SYSTEM_UID) { 17440 permission = PackageManager.PERMISSION_GRANTED; 17441 } else { 17442 permission = mContext.checkCallingOrSelfPermission( 17443 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17444 } 17445 enforceCrossUserPermission(uid, userId, 17446 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 17447 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17448 boolean sendNow = false; 17449 boolean isApp = (className == null); 17450 String componentName = isApp ? packageName : className; 17451 int packageUid = -1; 17452 ArrayList<String> components; 17453 17454 // writer 17455 synchronized (mPackages) { 17456 pkgSetting = mSettings.mPackages.get(packageName); 17457 if (pkgSetting == null) { 17458 if (className == null) { 17459 throw new IllegalArgumentException("Unknown package: " + packageName); 17460 } 17461 throw new IllegalArgumentException( 17462 "Unknown component: " + packageName + "/" + className); 17463 } 17464 // Allow root and verify that userId is not being specified by a different user 17465 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 17466 throw new SecurityException( 17467 "Permission Denial: attempt to change component state from pid=" 17468 + Binder.getCallingPid() 17469 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 17470 } 17471 if (className == null) { 17472 // We're dealing with an application/package level state change 17473 if (pkgSetting.getEnabled(userId) == newState) { 17474 // Nothing to do 17475 return; 17476 } 17477 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 17478 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 17479 // Don't care about who enables an app. 17480 callingPackage = null; 17481 } 17482 pkgSetting.setEnabled(newState, userId, callingPackage); 17483 // pkgSetting.pkg.mSetEnabled = newState; 17484 } else { 17485 // We're dealing with a component level state change 17486 // First, verify that this is a valid class name. 17487 PackageParser.Package pkg = pkgSetting.pkg; 17488 if (pkg == null || !pkg.hasComponentClassName(className)) { 17489 if (pkg != null && 17490 pkg.applicationInfo.targetSdkVersion >= 17491 Build.VERSION_CODES.JELLY_BEAN) { 17492 throw new IllegalArgumentException("Component class " + className 17493 + " does not exist in " + packageName); 17494 } else { 17495 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 17496 + className + " does not exist in " + packageName); 17497 } 17498 } 17499 switch (newState) { 17500 case COMPONENT_ENABLED_STATE_ENABLED: 17501 if (!pkgSetting.enableComponentLPw(className, userId)) { 17502 return; 17503 } 17504 break; 17505 case COMPONENT_ENABLED_STATE_DISABLED: 17506 if (!pkgSetting.disableComponentLPw(className, userId)) { 17507 return; 17508 } 17509 break; 17510 case COMPONENT_ENABLED_STATE_DEFAULT: 17511 if (!pkgSetting.restoreComponentLPw(className, userId)) { 17512 return; 17513 } 17514 break; 17515 default: 17516 Slog.e(TAG, "Invalid new component state: " + newState); 17517 return; 17518 } 17519 } 17520 scheduleWritePackageRestrictionsLocked(userId); 17521 components = mPendingBroadcasts.get(userId, packageName); 17522 final boolean newPackage = components == null; 17523 if (newPackage) { 17524 components = new ArrayList<String>(); 17525 } 17526 if (!components.contains(componentName)) { 17527 components.add(componentName); 17528 } 17529 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 17530 sendNow = true; 17531 // Purge entry from pending broadcast list if another one exists already 17532 // since we are sending one right away. 17533 mPendingBroadcasts.remove(userId, packageName); 17534 } else { 17535 if (newPackage) { 17536 mPendingBroadcasts.put(userId, packageName, components); 17537 } 17538 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 17539 // Schedule a message 17540 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 17541 } 17542 } 17543 } 17544 17545 long callingId = Binder.clearCallingIdentity(); 17546 try { 17547 if (sendNow) { 17548 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 17549 sendPackageChangedBroadcast(packageName, 17550 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 17551 } 17552 } finally { 17553 Binder.restoreCallingIdentity(callingId); 17554 } 17555 } 17556 17557 @Override 17558 public void flushPackageRestrictionsAsUser(int userId) { 17559 if (!sUserManager.exists(userId)) { 17560 return; 17561 } 17562 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 17563 false /* checkShell */, "flushPackageRestrictions"); 17564 synchronized (mPackages) { 17565 mSettings.writePackageRestrictionsLPr(userId); 17566 mDirtyUsers.remove(userId); 17567 if (mDirtyUsers.isEmpty()) { 17568 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 17569 } 17570 } 17571 } 17572 17573 private void sendPackageChangedBroadcast(String packageName, 17574 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 17575 if (DEBUG_INSTALL) 17576 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 17577 + componentNames); 17578 Bundle extras = new Bundle(4); 17579 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 17580 String nameList[] = new String[componentNames.size()]; 17581 componentNames.toArray(nameList); 17582 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 17583 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 17584 extras.putInt(Intent.EXTRA_UID, packageUid); 17585 // If this is not reporting a change of the overall package, then only send it 17586 // to registered receivers. We don't want to launch a swath of apps for every 17587 // little component state change. 17588 final int flags = !componentNames.contains(packageName) 17589 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 17590 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 17591 new int[] {UserHandle.getUserId(packageUid)}); 17592 } 17593 17594 @Override 17595 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 17596 if (!sUserManager.exists(userId)) return; 17597 final int uid = Binder.getCallingUid(); 17598 final int permission = mContext.checkCallingOrSelfPermission( 17599 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17600 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17601 enforceCrossUserPermission(uid, userId, 17602 true /* requireFullPermission */, true /* checkShell */, "stop package"); 17603 // writer 17604 synchronized (mPackages) { 17605 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 17606 allowedByPermission, uid, userId)) { 17607 scheduleWritePackageRestrictionsLocked(userId); 17608 } 17609 } 17610 } 17611 17612 @Override 17613 public String getInstallerPackageName(String packageName) { 17614 // reader 17615 synchronized (mPackages) { 17616 return mSettings.getInstallerPackageNameLPr(packageName); 17617 } 17618 } 17619 17620 public boolean isOrphaned(String packageName) { 17621 // reader 17622 synchronized (mPackages) { 17623 return mSettings.isOrphaned(packageName); 17624 } 17625 } 17626 17627 @Override 17628 public int getApplicationEnabledSetting(String packageName, int userId) { 17629 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17630 int uid = Binder.getCallingUid(); 17631 enforceCrossUserPermission(uid, userId, 17632 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 17633 // reader 17634 synchronized (mPackages) { 17635 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 17636 } 17637 } 17638 17639 @Override 17640 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 17641 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17642 int uid = Binder.getCallingUid(); 17643 enforceCrossUserPermission(uid, userId, 17644 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 17645 // reader 17646 synchronized (mPackages) { 17647 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 17648 } 17649 } 17650 17651 @Override 17652 public void enterSafeMode() { 17653 enforceSystemOrRoot("Only the system can request entering safe mode"); 17654 17655 if (!mSystemReady) { 17656 mSafeMode = true; 17657 } 17658 } 17659 17660 @Override 17661 public void systemReady() { 17662 mSystemReady = true; 17663 17664 // Read the compatibilty setting when the system is ready. 17665 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 17666 mContext.getContentResolver(), 17667 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 17668 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 17669 if (DEBUG_SETTINGS) { 17670 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 17671 } 17672 17673 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 17674 17675 synchronized (mPackages) { 17676 // Verify that all of the preferred activity components actually 17677 // exist. It is possible for applications to be updated and at 17678 // that point remove a previously declared activity component that 17679 // had been set as a preferred activity. We try to clean this up 17680 // the next time we encounter that preferred activity, but it is 17681 // possible for the user flow to never be able to return to that 17682 // situation so here we do a sanity check to make sure we haven't 17683 // left any junk around. 17684 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 17685 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17686 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17687 removed.clear(); 17688 for (PreferredActivity pa : pir.filterSet()) { 17689 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 17690 removed.add(pa); 17691 } 17692 } 17693 if (removed.size() > 0) { 17694 for (int r=0; r<removed.size(); r++) { 17695 PreferredActivity pa = removed.get(r); 17696 Slog.w(TAG, "Removing dangling preferred activity: " 17697 + pa.mPref.mComponent); 17698 pir.removeFilter(pa); 17699 } 17700 mSettings.writePackageRestrictionsLPr( 17701 mSettings.mPreferredActivities.keyAt(i)); 17702 } 17703 } 17704 17705 for (int userId : UserManagerService.getInstance().getUserIds()) { 17706 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 17707 grantPermissionsUserIds = ArrayUtils.appendInt( 17708 grantPermissionsUserIds, userId); 17709 } 17710 } 17711 } 17712 sUserManager.systemReady(); 17713 17714 // If we upgraded grant all default permissions before kicking off. 17715 for (int userId : grantPermissionsUserIds) { 17716 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 17717 } 17718 17719 // Kick off any messages waiting for system ready 17720 if (mPostSystemReadyMessages != null) { 17721 for (Message msg : mPostSystemReadyMessages) { 17722 msg.sendToTarget(); 17723 } 17724 mPostSystemReadyMessages = null; 17725 } 17726 17727 // Watch for external volumes that come and go over time 17728 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17729 storage.registerListener(mStorageListener); 17730 17731 mInstallerService.systemReady(); 17732 mPackageDexOptimizer.systemReady(); 17733 17734 MountServiceInternal mountServiceInternal = LocalServices.getService( 17735 MountServiceInternal.class); 17736 mountServiceInternal.addExternalStoragePolicy( 17737 new MountServiceInternal.ExternalStorageMountPolicy() { 17738 @Override 17739 public int getMountMode(int uid, String packageName) { 17740 if (Process.isIsolated(uid)) { 17741 return Zygote.MOUNT_EXTERNAL_NONE; 17742 } 17743 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 17744 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17745 } 17746 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17747 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17748 } 17749 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17750 return Zygote.MOUNT_EXTERNAL_READ; 17751 } 17752 return Zygote.MOUNT_EXTERNAL_WRITE; 17753 } 17754 17755 @Override 17756 public boolean hasExternalStorage(int uid, String packageName) { 17757 return true; 17758 } 17759 }); 17760 17761 // Now that we're mostly running, clean up stale users and apps 17762 reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 17763 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 17764 } 17765 17766 @Override 17767 public boolean isSafeMode() { 17768 return mSafeMode; 17769 } 17770 17771 @Override 17772 public boolean hasSystemUidErrors() { 17773 return mHasSystemUidErrors; 17774 } 17775 17776 static String arrayToString(int[] array) { 17777 StringBuffer buf = new StringBuffer(128); 17778 buf.append('['); 17779 if (array != null) { 17780 for (int i=0; i<array.length; i++) { 17781 if (i > 0) buf.append(", "); 17782 buf.append(array[i]); 17783 } 17784 } 17785 buf.append(']'); 17786 return buf.toString(); 17787 } 17788 17789 static class DumpState { 17790 public static final int DUMP_LIBS = 1 << 0; 17791 public static final int DUMP_FEATURES = 1 << 1; 17792 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 17793 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 17794 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 17795 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 17796 public static final int DUMP_PERMISSIONS = 1 << 6; 17797 public static final int DUMP_PACKAGES = 1 << 7; 17798 public static final int DUMP_SHARED_USERS = 1 << 8; 17799 public static final int DUMP_MESSAGES = 1 << 9; 17800 public static final int DUMP_PROVIDERS = 1 << 10; 17801 public static final int DUMP_VERIFIERS = 1 << 11; 17802 public static final int DUMP_PREFERRED = 1 << 12; 17803 public static final int DUMP_PREFERRED_XML = 1 << 13; 17804 public static final int DUMP_KEYSETS = 1 << 14; 17805 public static final int DUMP_VERSION = 1 << 15; 17806 public static final int DUMP_INSTALLS = 1 << 16; 17807 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 17808 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 17809 public static final int DUMP_FROZEN = 1 << 19; 17810 public static final int DUMP_DEXOPT = 1 << 20; 17811 17812 public static final int OPTION_SHOW_FILTERS = 1 << 0; 17813 17814 private int mTypes; 17815 17816 private int mOptions; 17817 17818 private boolean mTitlePrinted; 17819 17820 private SharedUserSetting mSharedUser; 17821 17822 public boolean isDumping(int type) { 17823 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 17824 return true; 17825 } 17826 17827 return (mTypes & type) != 0; 17828 } 17829 17830 public void setDump(int type) { 17831 mTypes |= type; 17832 } 17833 17834 public boolean isOptionEnabled(int option) { 17835 return (mOptions & option) != 0; 17836 } 17837 17838 public void setOptionEnabled(int option) { 17839 mOptions |= option; 17840 } 17841 17842 public boolean onTitlePrinted() { 17843 final boolean printed = mTitlePrinted; 17844 mTitlePrinted = true; 17845 return printed; 17846 } 17847 17848 public boolean getTitlePrinted() { 17849 return mTitlePrinted; 17850 } 17851 17852 public void setTitlePrinted(boolean enabled) { 17853 mTitlePrinted = enabled; 17854 } 17855 17856 public SharedUserSetting getSharedUser() { 17857 return mSharedUser; 17858 } 17859 17860 public void setSharedUser(SharedUserSetting user) { 17861 mSharedUser = user; 17862 } 17863 } 17864 17865 @Override 17866 public void onShellCommand(FileDescriptor in, FileDescriptor out, 17867 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 17868 (new PackageManagerShellCommand(this)).exec( 17869 this, in, out, err, args, resultReceiver); 17870 } 17871 17872 @Override 17873 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 17874 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 17875 != PackageManager.PERMISSION_GRANTED) { 17876 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 17877 + Binder.getCallingPid() 17878 + ", uid=" + Binder.getCallingUid() 17879 + " without permission " 17880 + android.Manifest.permission.DUMP); 17881 return; 17882 } 17883 17884 DumpState dumpState = new DumpState(); 17885 boolean fullPreferred = false; 17886 boolean checkin = false; 17887 17888 String packageName = null; 17889 ArraySet<String> permissionNames = null; 17890 17891 int opti = 0; 17892 while (opti < args.length) { 17893 String opt = args[opti]; 17894 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 17895 break; 17896 } 17897 opti++; 17898 17899 if ("-a".equals(opt)) { 17900 // Right now we only know how to print all. 17901 } else if ("-h".equals(opt)) { 17902 pw.println("Package manager dump options:"); 17903 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 17904 pw.println(" --checkin: dump for a checkin"); 17905 pw.println(" -f: print details of intent filters"); 17906 pw.println(" -h: print this help"); 17907 pw.println(" cmd may be one of:"); 17908 pw.println(" l[ibraries]: list known shared libraries"); 17909 pw.println(" f[eatures]: list device features"); 17910 pw.println(" k[eysets]: print known keysets"); 17911 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 17912 pw.println(" perm[issions]: dump permissions"); 17913 pw.println(" permission [name ...]: dump declaration and use of given permission"); 17914 pw.println(" pref[erred]: print preferred package settings"); 17915 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 17916 pw.println(" prov[iders]: dump content providers"); 17917 pw.println(" p[ackages]: dump installed packages"); 17918 pw.println(" s[hared-users]: dump shared user IDs"); 17919 pw.println(" m[essages]: print collected runtime messages"); 17920 pw.println(" v[erifiers]: print package verifier info"); 17921 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 17922 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 17923 pw.println(" version: print database version info"); 17924 pw.println(" write: write current settings now"); 17925 pw.println(" installs: details about install sessions"); 17926 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 17927 pw.println(" dexopt: dump dexopt state"); 17928 pw.println(" <package.name>: info about given package"); 17929 return; 17930 } else if ("--checkin".equals(opt)) { 17931 checkin = true; 17932 } else if ("-f".equals(opt)) { 17933 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 17934 } else { 17935 pw.println("Unknown argument: " + opt + "; use -h for help"); 17936 } 17937 } 17938 17939 // Is the caller requesting to dump a particular piece of data? 17940 if (opti < args.length) { 17941 String cmd = args[opti]; 17942 opti++; 17943 // Is this a package name? 17944 if ("android".equals(cmd) || cmd.contains(".")) { 17945 packageName = cmd; 17946 // When dumping a single package, we always dump all of its 17947 // filter information since the amount of data will be reasonable. 17948 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 17949 } else if ("check-permission".equals(cmd)) { 17950 if (opti >= args.length) { 17951 pw.println("Error: check-permission missing permission argument"); 17952 return; 17953 } 17954 String perm = args[opti]; 17955 opti++; 17956 if (opti >= args.length) { 17957 pw.println("Error: check-permission missing package argument"); 17958 return; 17959 } 17960 String pkg = args[opti]; 17961 opti++; 17962 int user = UserHandle.getUserId(Binder.getCallingUid()); 17963 if (opti < args.length) { 17964 try { 17965 user = Integer.parseInt(args[opti]); 17966 } catch (NumberFormatException e) { 17967 pw.println("Error: check-permission user argument is not a number: " 17968 + args[opti]); 17969 return; 17970 } 17971 } 17972 pw.println(checkPermission(perm, pkg, user)); 17973 return; 17974 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 17975 dumpState.setDump(DumpState.DUMP_LIBS); 17976 } else if ("f".equals(cmd) || "features".equals(cmd)) { 17977 dumpState.setDump(DumpState.DUMP_FEATURES); 17978 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 17979 if (opti >= args.length) { 17980 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 17981 | DumpState.DUMP_SERVICE_RESOLVERS 17982 | DumpState.DUMP_RECEIVER_RESOLVERS 17983 | DumpState.DUMP_CONTENT_RESOLVERS); 17984 } else { 17985 while (opti < args.length) { 17986 String name = args[opti]; 17987 if ("a".equals(name) || "activity".equals(name)) { 17988 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 17989 } else if ("s".equals(name) || "service".equals(name)) { 17990 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 17991 } else if ("r".equals(name) || "receiver".equals(name)) { 17992 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 17993 } else if ("c".equals(name) || "content".equals(name)) { 17994 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 17995 } else { 17996 pw.println("Error: unknown resolver table type: " + name); 17997 return; 17998 } 17999 opti++; 18000 } 18001 } 18002 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 18003 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 18004 } else if ("permission".equals(cmd)) { 18005 if (opti >= args.length) { 18006 pw.println("Error: permission requires permission name"); 18007 return; 18008 } 18009 permissionNames = new ArraySet<>(); 18010 while (opti < args.length) { 18011 permissionNames.add(args[opti]); 18012 opti++; 18013 } 18014 dumpState.setDump(DumpState.DUMP_PERMISSIONS 18015 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 18016 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 18017 dumpState.setDump(DumpState.DUMP_PREFERRED); 18018 } else if ("preferred-xml".equals(cmd)) { 18019 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 18020 if (opti < args.length && "--full".equals(args[opti])) { 18021 fullPreferred = true; 18022 opti++; 18023 } 18024 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 18025 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 18026 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 18027 dumpState.setDump(DumpState.DUMP_PACKAGES); 18028 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 18029 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 18030 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 18031 dumpState.setDump(DumpState.DUMP_PROVIDERS); 18032 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 18033 dumpState.setDump(DumpState.DUMP_MESSAGES); 18034 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 18035 dumpState.setDump(DumpState.DUMP_VERIFIERS); 18036 } else if ("i".equals(cmd) || "ifv".equals(cmd) 18037 || "intent-filter-verifiers".equals(cmd)) { 18038 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 18039 } else if ("version".equals(cmd)) { 18040 dumpState.setDump(DumpState.DUMP_VERSION); 18041 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 18042 dumpState.setDump(DumpState.DUMP_KEYSETS); 18043 } else if ("installs".equals(cmd)) { 18044 dumpState.setDump(DumpState.DUMP_INSTALLS); 18045 } else if ("frozen".equals(cmd)) { 18046 dumpState.setDump(DumpState.DUMP_FROZEN); 18047 } else if ("dexopt".equals(cmd)) { 18048 dumpState.setDump(DumpState.DUMP_DEXOPT); 18049 } else if ("write".equals(cmd)) { 18050 synchronized (mPackages) { 18051 mSettings.writeLPr(); 18052 pw.println("Settings written."); 18053 return; 18054 } 18055 } 18056 } 18057 18058 if (checkin) { 18059 pw.println("vers,1"); 18060 } 18061 18062 // reader 18063 synchronized (mPackages) { 18064 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 18065 if (!checkin) { 18066 if (dumpState.onTitlePrinted()) 18067 pw.println(); 18068 pw.println("Database versions:"); 18069 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 18070 } 18071 } 18072 18073 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 18074 if (!checkin) { 18075 if (dumpState.onTitlePrinted()) 18076 pw.println(); 18077 pw.println("Verifiers:"); 18078 pw.print(" Required: "); 18079 pw.print(mRequiredVerifierPackage); 18080 pw.print(" (uid="); 18081 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18082 UserHandle.USER_SYSTEM)); 18083 pw.println(")"); 18084 } else if (mRequiredVerifierPackage != null) { 18085 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 18086 pw.print(","); 18087 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18088 UserHandle.USER_SYSTEM)); 18089 } 18090 } 18091 18092 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 18093 packageName == null) { 18094 if (mIntentFilterVerifierComponent != null) { 18095 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 18096 if (!checkin) { 18097 if (dumpState.onTitlePrinted()) 18098 pw.println(); 18099 pw.println("Intent Filter Verifier:"); 18100 pw.print(" Using: "); 18101 pw.print(verifierPackageName); 18102 pw.print(" (uid="); 18103 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18104 UserHandle.USER_SYSTEM)); 18105 pw.println(")"); 18106 } else if (verifierPackageName != null) { 18107 pw.print("ifv,"); pw.print(verifierPackageName); 18108 pw.print(","); 18109 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18110 UserHandle.USER_SYSTEM)); 18111 } 18112 } else { 18113 pw.println(); 18114 pw.println("No Intent Filter Verifier available!"); 18115 } 18116 } 18117 18118 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 18119 boolean printedHeader = false; 18120 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 18121 while (it.hasNext()) { 18122 String name = it.next(); 18123 SharedLibraryEntry ent = mSharedLibraries.get(name); 18124 if (!checkin) { 18125 if (!printedHeader) { 18126 if (dumpState.onTitlePrinted()) 18127 pw.println(); 18128 pw.println("Libraries:"); 18129 printedHeader = true; 18130 } 18131 pw.print(" "); 18132 } else { 18133 pw.print("lib,"); 18134 } 18135 pw.print(name); 18136 if (!checkin) { 18137 pw.print(" -> "); 18138 } 18139 if (ent.path != null) { 18140 if (!checkin) { 18141 pw.print("(jar) "); 18142 pw.print(ent.path); 18143 } else { 18144 pw.print(",jar,"); 18145 pw.print(ent.path); 18146 } 18147 } else { 18148 if (!checkin) { 18149 pw.print("(apk) "); 18150 pw.print(ent.apk); 18151 } else { 18152 pw.print(",apk,"); 18153 pw.print(ent.apk); 18154 } 18155 } 18156 pw.println(); 18157 } 18158 } 18159 18160 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 18161 if (dumpState.onTitlePrinted()) 18162 pw.println(); 18163 if (!checkin) { 18164 pw.println("Features:"); 18165 } 18166 18167 for (FeatureInfo feat : mAvailableFeatures.values()) { 18168 if (checkin) { 18169 pw.print("feat,"); 18170 pw.print(feat.name); 18171 pw.print(","); 18172 pw.println(feat.version); 18173 } else { 18174 pw.print(" "); 18175 pw.print(feat.name); 18176 if (feat.version > 0) { 18177 pw.print(" version="); 18178 pw.print(feat.version); 18179 } 18180 pw.println(); 18181 } 18182 } 18183 } 18184 18185 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 18186 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 18187 : "Activity Resolver Table:", " ", packageName, 18188 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18189 dumpState.setTitlePrinted(true); 18190 } 18191 } 18192 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 18193 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 18194 : "Receiver Resolver Table:", " ", packageName, 18195 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18196 dumpState.setTitlePrinted(true); 18197 } 18198 } 18199 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 18200 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 18201 : "Service Resolver Table:", " ", packageName, 18202 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18203 dumpState.setTitlePrinted(true); 18204 } 18205 } 18206 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 18207 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 18208 : "Provider Resolver Table:", " ", packageName, 18209 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18210 dumpState.setTitlePrinted(true); 18211 } 18212 } 18213 18214 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 18215 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18216 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18217 int user = mSettings.mPreferredActivities.keyAt(i); 18218 if (pir.dump(pw, 18219 dumpState.getTitlePrinted() 18220 ? "\nPreferred Activities User " + user + ":" 18221 : "Preferred Activities User " + user + ":", " ", 18222 packageName, true, false)) { 18223 dumpState.setTitlePrinted(true); 18224 } 18225 } 18226 } 18227 18228 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 18229 pw.flush(); 18230 FileOutputStream fout = new FileOutputStream(fd); 18231 BufferedOutputStream str = new BufferedOutputStream(fout); 18232 XmlSerializer serializer = new FastXmlSerializer(); 18233 try { 18234 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 18235 serializer.startDocument(null, true); 18236 serializer.setFeature( 18237 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 18238 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 18239 serializer.endDocument(); 18240 serializer.flush(); 18241 } catch (IllegalArgumentException e) { 18242 pw.println("Failed writing: " + e); 18243 } catch (IllegalStateException e) { 18244 pw.println("Failed writing: " + e); 18245 } catch (IOException e) { 18246 pw.println("Failed writing: " + e); 18247 } 18248 } 18249 18250 if (!checkin 18251 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 18252 && packageName == null) { 18253 pw.println(); 18254 int count = mSettings.mPackages.size(); 18255 if (count == 0) { 18256 pw.println("No applications!"); 18257 pw.println(); 18258 } else { 18259 final String prefix = " "; 18260 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 18261 if (allPackageSettings.size() == 0) { 18262 pw.println("No domain preferred apps!"); 18263 pw.println(); 18264 } else { 18265 pw.println("App verification status:"); 18266 pw.println(); 18267 count = 0; 18268 for (PackageSetting ps : allPackageSettings) { 18269 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 18270 if (ivi == null || ivi.getPackageName() == null) continue; 18271 pw.println(prefix + "Package: " + ivi.getPackageName()); 18272 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 18273 pw.println(prefix + "Status: " + ivi.getStatusString()); 18274 pw.println(); 18275 count++; 18276 } 18277 if (count == 0) { 18278 pw.println(prefix + "No app verification established."); 18279 pw.println(); 18280 } 18281 for (int userId : sUserManager.getUserIds()) { 18282 pw.println("App linkages for user " + userId + ":"); 18283 pw.println(); 18284 count = 0; 18285 for (PackageSetting ps : allPackageSettings) { 18286 final long status = ps.getDomainVerificationStatusForUser(userId); 18287 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 18288 continue; 18289 } 18290 pw.println(prefix + "Package: " + ps.name); 18291 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 18292 String statusStr = IntentFilterVerificationInfo. 18293 getStatusStringFromValue(status); 18294 pw.println(prefix + "Status: " + statusStr); 18295 pw.println(); 18296 count++; 18297 } 18298 if (count == 0) { 18299 pw.println(prefix + "No configured app linkages."); 18300 pw.println(); 18301 } 18302 } 18303 } 18304 } 18305 } 18306 18307 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 18308 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 18309 if (packageName == null && permissionNames == null) { 18310 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 18311 if (iperm == 0) { 18312 if (dumpState.onTitlePrinted()) 18313 pw.println(); 18314 pw.println("AppOp Permissions:"); 18315 } 18316 pw.print(" AppOp Permission "); 18317 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 18318 pw.println(":"); 18319 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 18320 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 18321 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 18322 } 18323 } 18324 } 18325 } 18326 18327 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 18328 boolean printedSomething = false; 18329 for (PackageParser.Provider p : mProviders.mProviders.values()) { 18330 if (packageName != null && !packageName.equals(p.info.packageName)) { 18331 continue; 18332 } 18333 if (!printedSomething) { 18334 if (dumpState.onTitlePrinted()) 18335 pw.println(); 18336 pw.println("Registered ContentProviders:"); 18337 printedSomething = true; 18338 } 18339 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 18340 pw.print(" "); pw.println(p.toString()); 18341 } 18342 printedSomething = false; 18343 for (Map.Entry<String, PackageParser.Provider> entry : 18344 mProvidersByAuthority.entrySet()) { 18345 PackageParser.Provider p = entry.getValue(); 18346 if (packageName != null && !packageName.equals(p.info.packageName)) { 18347 continue; 18348 } 18349 if (!printedSomething) { 18350 if (dumpState.onTitlePrinted()) 18351 pw.println(); 18352 pw.println("ContentProvider Authorities:"); 18353 printedSomething = true; 18354 } 18355 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 18356 pw.print(" "); pw.println(p.toString()); 18357 if (p.info != null && p.info.applicationInfo != null) { 18358 final String appInfo = p.info.applicationInfo.toString(); 18359 pw.print(" applicationInfo="); pw.println(appInfo); 18360 } 18361 } 18362 } 18363 18364 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 18365 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 18366 } 18367 18368 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 18369 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 18370 } 18371 18372 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 18373 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 18374 } 18375 18376 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 18377 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 18378 } 18379 18380 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 18381 // XXX should handle packageName != null by dumping only install data that 18382 // the given package is involved with. 18383 if (dumpState.onTitlePrinted()) pw.println(); 18384 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 18385 } 18386 18387 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 18388 // XXX should handle packageName != null by dumping only install data that 18389 // the given package is involved with. 18390 if (dumpState.onTitlePrinted()) pw.println(); 18391 18392 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18393 ipw.println(); 18394 ipw.println("Frozen packages:"); 18395 ipw.increaseIndent(); 18396 if (mFrozenPackages.size() == 0) { 18397 ipw.println("(none)"); 18398 } else { 18399 for (int i = 0; i < mFrozenPackages.size(); i++) { 18400 ipw.println(mFrozenPackages.valueAt(i)); 18401 } 18402 } 18403 ipw.decreaseIndent(); 18404 } 18405 18406 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 18407 if (dumpState.onTitlePrinted()) pw.println(); 18408 dumpDexoptStateLPr(pw, packageName); 18409 } 18410 18411 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 18412 if (dumpState.onTitlePrinted()) pw.println(); 18413 mSettings.dumpReadMessagesLPr(pw, dumpState); 18414 18415 pw.println(); 18416 pw.println("Package warning messages:"); 18417 BufferedReader in = null; 18418 String line = null; 18419 try { 18420 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18421 while ((line = in.readLine()) != null) { 18422 if (line.contains("ignored: updated version")) continue; 18423 pw.println(line); 18424 } 18425 } catch (IOException ignored) { 18426 } finally { 18427 IoUtils.closeQuietly(in); 18428 } 18429 } 18430 18431 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 18432 BufferedReader in = null; 18433 String line = null; 18434 try { 18435 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18436 while ((line = in.readLine()) != null) { 18437 if (line.contains("ignored: updated version")) continue; 18438 pw.print("msg,"); 18439 pw.println(line); 18440 } 18441 } catch (IOException ignored) { 18442 } finally { 18443 IoUtils.closeQuietly(in); 18444 } 18445 } 18446 } 18447 } 18448 18449 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 18450 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18451 ipw.println(); 18452 ipw.println("Dexopt state:"); 18453 ipw.increaseIndent(); 18454 Collection<PackageParser.Package> packages = null; 18455 if (packageName != null) { 18456 PackageParser.Package targetPackage = mPackages.get(packageName); 18457 if (targetPackage != null) { 18458 packages = Collections.singletonList(targetPackage); 18459 } else { 18460 ipw.println("Unable to find package: " + packageName); 18461 return; 18462 } 18463 } else { 18464 packages = mPackages.values(); 18465 } 18466 18467 for (PackageParser.Package pkg : packages) { 18468 ipw.println("[" + pkg.packageName + "]"); 18469 ipw.increaseIndent(); 18470 mPackageDexOptimizer.dumpDexoptState(ipw, pkg); 18471 ipw.decreaseIndent(); 18472 } 18473 } 18474 18475 private String dumpDomainString(String packageName) { 18476 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 18477 .getList(); 18478 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 18479 18480 ArraySet<String> result = new ArraySet<>(); 18481 if (iviList.size() > 0) { 18482 for (IntentFilterVerificationInfo ivi : iviList) { 18483 for (String host : ivi.getDomains()) { 18484 result.add(host); 18485 } 18486 } 18487 } 18488 if (filters != null && filters.size() > 0) { 18489 for (IntentFilter filter : filters) { 18490 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 18491 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 18492 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 18493 result.addAll(filter.getHostsList()); 18494 } 18495 } 18496 } 18497 18498 StringBuilder sb = new StringBuilder(result.size() * 16); 18499 for (String domain : result) { 18500 if (sb.length() > 0) sb.append(" "); 18501 sb.append(domain); 18502 } 18503 return sb.toString(); 18504 } 18505 18506 // ------- apps on sdcard specific code ------- 18507 static final boolean DEBUG_SD_INSTALL = false; 18508 18509 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 18510 18511 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 18512 18513 private boolean mMediaMounted = false; 18514 18515 static String getEncryptKey() { 18516 try { 18517 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 18518 SD_ENCRYPTION_KEYSTORE_NAME); 18519 if (sdEncKey == null) { 18520 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 18521 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 18522 if (sdEncKey == null) { 18523 Slog.e(TAG, "Failed to create encryption keys"); 18524 return null; 18525 } 18526 } 18527 return sdEncKey; 18528 } catch (NoSuchAlgorithmException nsae) { 18529 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 18530 return null; 18531 } catch (IOException ioe) { 18532 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 18533 return null; 18534 } 18535 } 18536 18537 /* 18538 * Update media status on PackageManager. 18539 */ 18540 @Override 18541 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 18542 int callingUid = Binder.getCallingUid(); 18543 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 18544 throw new SecurityException("Media status can only be updated by the system"); 18545 } 18546 // reader; this apparently protects mMediaMounted, but should probably 18547 // be a different lock in that case. 18548 synchronized (mPackages) { 18549 Log.i(TAG, "Updating external media status from " 18550 + (mMediaMounted ? "mounted" : "unmounted") + " to " 18551 + (mediaStatus ? "mounted" : "unmounted")); 18552 if (DEBUG_SD_INSTALL) 18553 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 18554 + ", mMediaMounted=" + mMediaMounted); 18555 if (mediaStatus == mMediaMounted) { 18556 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 18557 : 0, -1); 18558 mHandler.sendMessage(msg); 18559 return; 18560 } 18561 mMediaMounted = mediaStatus; 18562 } 18563 // Queue up an async operation since the package installation may take a 18564 // little while. 18565 mHandler.post(new Runnable() { 18566 public void run() { 18567 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 18568 } 18569 }); 18570 } 18571 18572 /** 18573 * Called by MountService when the initial ASECs to scan are available. 18574 * Should block until all the ASEC containers are finished being scanned. 18575 */ 18576 public void scanAvailableAsecs() { 18577 updateExternalMediaStatusInner(true, false, false); 18578 } 18579 18580 /* 18581 * Collect information of applications on external media, map them against 18582 * existing containers and update information based on current mount status. 18583 * Please note that we always have to report status if reportStatus has been 18584 * set to true especially when unloading packages. 18585 */ 18586 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 18587 boolean externalStorage) { 18588 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 18589 int[] uidArr = EmptyArray.INT; 18590 18591 final String[] list = PackageHelper.getSecureContainerList(); 18592 if (ArrayUtils.isEmpty(list)) { 18593 Log.i(TAG, "No secure containers found"); 18594 } else { 18595 // Process list of secure containers and categorize them 18596 // as active or stale based on their package internal state. 18597 18598 // reader 18599 synchronized (mPackages) { 18600 for (String cid : list) { 18601 // Leave stages untouched for now; installer service owns them 18602 if (PackageInstallerService.isStageName(cid)) continue; 18603 18604 if (DEBUG_SD_INSTALL) 18605 Log.i(TAG, "Processing container " + cid); 18606 String pkgName = getAsecPackageName(cid); 18607 if (pkgName == null) { 18608 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 18609 continue; 18610 } 18611 if (DEBUG_SD_INSTALL) 18612 Log.i(TAG, "Looking for pkg : " + pkgName); 18613 18614 final PackageSetting ps = mSettings.mPackages.get(pkgName); 18615 if (ps == null) { 18616 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 18617 continue; 18618 } 18619 18620 /* 18621 * Skip packages that are not external if we're unmounting 18622 * external storage. 18623 */ 18624 if (externalStorage && !isMounted && !isExternal(ps)) { 18625 continue; 18626 } 18627 18628 final AsecInstallArgs args = new AsecInstallArgs(cid, 18629 getAppDexInstructionSets(ps), ps.isForwardLocked()); 18630 // The package status is changed only if the code path 18631 // matches between settings and the container id. 18632 if (ps.codePathString != null 18633 && ps.codePathString.startsWith(args.getCodePath())) { 18634 if (DEBUG_SD_INSTALL) { 18635 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 18636 + " at code path: " + ps.codePathString); 18637 } 18638 18639 // We do have a valid package installed on sdcard 18640 processCids.put(args, ps.codePathString); 18641 final int uid = ps.appId; 18642 if (uid != -1) { 18643 uidArr = ArrayUtils.appendInt(uidArr, uid); 18644 } 18645 } else { 18646 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 18647 + ps.codePathString); 18648 } 18649 } 18650 } 18651 18652 Arrays.sort(uidArr); 18653 } 18654 18655 // Process packages with valid entries. 18656 if (isMounted) { 18657 if (DEBUG_SD_INSTALL) 18658 Log.i(TAG, "Loading packages"); 18659 loadMediaPackages(processCids, uidArr, externalStorage); 18660 startCleaningPackages(); 18661 mInstallerService.onSecureContainersAvailable(); 18662 } else { 18663 if (DEBUG_SD_INSTALL) 18664 Log.i(TAG, "Unloading packages"); 18665 unloadMediaPackages(processCids, uidArr, reportStatus); 18666 } 18667 } 18668 18669 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18670 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 18671 final int size = infos.size(); 18672 final String[] packageNames = new String[size]; 18673 final int[] packageUids = new int[size]; 18674 for (int i = 0; i < size; i++) { 18675 final ApplicationInfo info = infos.get(i); 18676 packageNames[i] = info.packageName; 18677 packageUids[i] = info.uid; 18678 } 18679 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 18680 finishedReceiver); 18681 } 18682 18683 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18684 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18685 sendResourcesChangedBroadcast(mediaStatus, replacing, 18686 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 18687 } 18688 18689 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18690 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18691 int size = pkgList.length; 18692 if (size > 0) { 18693 // Send broadcasts here 18694 Bundle extras = new Bundle(); 18695 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 18696 if (uidArr != null) { 18697 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 18698 } 18699 if (replacing) { 18700 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 18701 } 18702 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 18703 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 18704 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 18705 } 18706 } 18707 18708 /* 18709 * Look at potentially valid container ids from processCids If package 18710 * information doesn't match the one on record or package scanning fails, 18711 * the cid is added to list of removeCids. We currently don't delete stale 18712 * containers. 18713 */ 18714 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 18715 boolean externalStorage) { 18716 ArrayList<String> pkgList = new ArrayList<String>(); 18717 Set<AsecInstallArgs> keys = processCids.keySet(); 18718 18719 for (AsecInstallArgs args : keys) { 18720 String codePath = processCids.get(args); 18721 if (DEBUG_SD_INSTALL) 18722 Log.i(TAG, "Loading container : " + args.cid); 18723 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 18724 try { 18725 // Make sure there are no container errors first. 18726 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 18727 Slog.e(TAG, "Failed to mount cid : " + args.cid 18728 + " when installing from sdcard"); 18729 continue; 18730 } 18731 // Check code path here. 18732 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 18733 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 18734 + " does not match one in settings " + codePath); 18735 continue; 18736 } 18737 // Parse package 18738 int parseFlags = mDefParseFlags; 18739 if (args.isExternalAsec()) { 18740 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 18741 } 18742 if (args.isFwdLocked()) { 18743 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 18744 } 18745 18746 synchronized (mInstallLock) { 18747 PackageParser.Package pkg = null; 18748 try { 18749 // Sadly we don't know the package name yet to freeze it 18750 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 18751 SCAN_IGNORE_FROZEN, 0, null); 18752 } catch (PackageManagerException e) { 18753 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 18754 } 18755 // Scan the package 18756 if (pkg != null) { 18757 /* 18758 * TODO why is the lock being held? doPostInstall is 18759 * called in other places without the lock. This needs 18760 * to be straightened out. 18761 */ 18762 // writer 18763 synchronized (mPackages) { 18764 retCode = PackageManager.INSTALL_SUCCEEDED; 18765 pkgList.add(pkg.packageName); 18766 // Post process args 18767 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 18768 pkg.applicationInfo.uid); 18769 } 18770 } else { 18771 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 18772 } 18773 } 18774 18775 } finally { 18776 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 18777 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 18778 } 18779 } 18780 } 18781 // writer 18782 synchronized (mPackages) { 18783 // If the platform SDK has changed since the last time we booted, 18784 // we need to re-grant app permission to catch any new ones that 18785 // appear. This is really a hack, and means that apps can in some 18786 // cases get permissions that the user didn't initially explicitly 18787 // allow... it would be nice to have some better way to handle 18788 // this situation. 18789 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 18790 : mSettings.getInternalVersion(); 18791 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 18792 : StorageManager.UUID_PRIVATE_INTERNAL; 18793 18794 int updateFlags = UPDATE_PERMISSIONS_ALL; 18795 if (ver.sdkVersion != mSdkVersion) { 18796 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 18797 + mSdkVersion + "; regranting permissions for external"); 18798 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 18799 } 18800 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 18801 18802 // Yay, everything is now upgraded 18803 ver.forceCurrent(); 18804 18805 // can downgrade to reader 18806 // Persist settings 18807 mSettings.writeLPr(); 18808 } 18809 // Send a broadcast to let everyone know we are done processing 18810 if (pkgList.size() > 0) { 18811 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 18812 } 18813 } 18814 18815 /* 18816 * Utility method to unload a list of specified containers 18817 */ 18818 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 18819 // Just unmount all valid containers. 18820 for (AsecInstallArgs arg : cidArgs) { 18821 synchronized (mInstallLock) { 18822 arg.doPostDeleteLI(false); 18823 } 18824 } 18825 } 18826 18827 /* 18828 * Unload packages mounted on external media. This involves deleting package 18829 * data from internal structures, sending broadcasts about disabled packages, 18830 * gc'ing to free up references, unmounting all secure containers 18831 * corresponding to packages on external media, and posting a 18832 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 18833 * that we always have to post this message if status has been requested no 18834 * matter what. 18835 */ 18836 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 18837 final boolean reportStatus) { 18838 if (DEBUG_SD_INSTALL) 18839 Log.i(TAG, "unloading media packages"); 18840 ArrayList<String> pkgList = new ArrayList<String>(); 18841 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 18842 final Set<AsecInstallArgs> keys = processCids.keySet(); 18843 for (AsecInstallArgs args : keys) { 18844 String pkgName = args.getPackageName(); 18845 if (DEBUG_SD_INSTALL) 18846 Log.i(TAG, "Trying to unload pkg : " + pkgName); 18847 // Delete package internally 18848 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 18849 synchronized (mInstallLock) { 18850 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 18851 final boolean res; 18852 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 18853 "unloadMediaPackages")) { 18854 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 18855 null); 18856 } 18857 if (res) { 18858 pkgList.add(pkgName); 18859 } else { 18860 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 18861 failedList.add(args); 18862 } 18863 } 18864 } 18865 18866 // reader 18867 synchronized (mPackages) { 18868 // We didn't update the settings after removing each package; 18869 // write them now for all packages. 18870 mSettings.writeLPr(); 18871 } 18872 18873 // We have to absolutely send UPDATED_MEDIA_STATUS only 18874 // after confirming that all the receivers processed the ordered 18875 // broadcast when packages get disabled, force a gc to clean things up. 18876 // and unload all the containers. 18877 if (pkgList.size() > 0) { 18878 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 18879 new IIntentReceiver.Stub() { 18880 public void performReceive(Intent intent, int resultCode, String data, 18881 Bundle extras, boolean ordered, boolean sticky, 18882 int sendingUser) throws RemoteException { 18883 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 18884 reportStatus ? 1 : 0, 1, keys); 18885 mHandler.sendMessage(msg); 18886 } 18887 }); 18888 } else { 18889 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 18890 keys); 18891 mHandler.sendMessage(msg); 18892 } 18893 } 18894 18895 private void loadPrivatePackages(final VolumeInfo vol) { 18896 mHandler.post(new Runnable() { 18897 @Override 18898 public void run() { 18899 loadPrivatePackagesInner(vol); 18900 } 18901 }); 18902 } 18903 18904 private void loadPrivatePackagesInner(VolumeInfo vol) { 18905 final String volumeUuid = vol.fsUuid; 18906 if (TextUtils.isEmpty(volumeUuid)) { 18907 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 18908 return; 18909 } 18910 18911 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 18912 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 18913 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 18914 18915 final VersionInfo ver; 18916 final List<PackageSetting> packages; 18917 synchronized (mPackages) { 18918 ver = mSettings.findOrCreateVersion(volumeUuid); 18919 packages = mSettings.getVolumePackagesLPr(volumeUuid); 18920 } 18921 18922 for (PackageSetting ps : packages) { 18923 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 18924 synchronized (mInstallLock) { 18925 final PackageParser.Package pkg; 18926 try { 18927 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 18928 loaded.add(pkg.applicationInfo); 18929 18930 } catch (PackageManagerException e) { 18931 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 18932 } 18933 18934 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 18935 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 18936 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 18937 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 18938 } 18939 } 18940 } 18941 18942 // Reconcile app data for all started/unlocked users 18943 final StorageManager sm = mContext.getSystemService(StorageManager.class); 18944 final UserManager um = mContext.getSystemService(UserManager.class); 18945 for (UserInfo user : um.getUsers()) { 18946 final int flags; 18947 if (um.isUserUnlockingOrUnlocked(user.id)) { 18948 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18949 } else if (um.isUserRunning(user.id)) { 18950 flags = StorageManager.FLAG_STORAGE_DE; 18951 } else { 18952 continue; 18953 } 18954 18955 try { 18956 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 18957 synchronized (mInstallLock) { 18958 reconcileAppsDataLI(volumeUuid, user.id, flags); 18959 } 18960 } catch (IllegalStateException e) { 18961 // Device was probably ejected, and we'll process that event momentarily 18962 Slog.w(TAG, "Failed to prepare storage: " + e); 18963 } 18964 } 18965 18966 synchronized (mPackages) { 18967 int updateFlags = UPDATE_PERMISSIONS_ALL; 18968 if (ver.sdkVersion != mSdkVersion) { 18969 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 18970 + mSdkVersion + "; regranting permissions for " + volumeUuid); 18971 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 18972 } 18973 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 18974 18975 // Yay, everything is now upgraded 18976 ver.forceCurrent(); 18977 18978 mSettings.writeLPr(); 18979 } 18980 18981 for (PackageFreezer freezer : freezers) { 18982 freezer.close(); 18983 } 18984 18985 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 18986 sendResourcesChangedBroadcast(true, false, loaded, null); 18987 } 18988 18989 private void unloadPrivatePackages(final VolumeInfo vol) { 18990 mHandler.post(new Runnable() { 18991 @Override 18992 public void run() { 18993 unloadPrivatePackagesInner(vol); 18994 } 18995 }); 18996 } 18997 18998 private void unloadPrivatePackagesInner(VolumeInfo vol) { 18999 final String volumeUuid = vol.fsUuid; 19000 if (TextUtils.isEmpty(volumeUuid)) { 19001 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 19002 return; 19003 } 19004 19005 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 19006 synchronized (mInstallLock) { 19007 synchronized (mPackages) { 19008 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 19009 for (PackageSetting ps : packages) { 19010 if (ps.pkg == null) continue; 19011 19012 final ApplicationInfo info = ps.pkg.applicationInfo; 19013 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19014 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19015 19016 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 19017 "unloadPrivatePackagesInner")) { 19018 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 19019 false, null)) { 19020 unloaded.add(info); 19021 } else { 19022 Slog.w(TAG, "Failed to unload " + ps.codePath); 19023 } 19024 } 19025 } 19026 19027 mSettings.writeLPr(); 19028 } 19029 } 19030 19031 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 19032 sendResourcesChangedBroadcast(false, false, unloaded, null); 19033 } 19034 19035 /** 19036 * Prepare storage areas for given user on all mounted devices. 19037 */ 19038 void prepareUserData(int userId, int userSerial, int flags) { 19039 synchronized (mInstallLock) { 19040 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19041 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19042 final String volumeUuid = vol.getFsUuid(); 19043 prepareUserDataLI(volumeUuid, userId, userSerial, flags, true); 19044 } 19045 } 19046 } 19047 19048 private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags, 19049 boolean allowRecover) { 19050 // Prepare storage and verify that serial numbers are consistent; if 19051 // there's a mismatch we need to destroy to avoid leaking data 19052 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19053 try { 19054 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags); 19055 19056 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) { 19057 UserManagerService.enforceSerialNumber( 19058 Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial); 19059 } 19060 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) { 19061 UserManagerService.enforceSerialNumber( 19062 Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial); 19063 } 19064 19065 synchronized (mInstallLock) { 19066 mInstaller.createUserData(volumeUuid, userId, userSerial, flags); 19067 } 19068 } catch (Exception e) { 19069 logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid 19070 + " because we failed to prepare: " + e); 19071 destroyUserDataLI(volumeUuid, userId, 19072 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19073 19074 if (allowRecover) { 19075 // Try one last time; if we fail again we're really in trouble 19076 prepareUserDataLI(volumeUuid, userId, userSerial, flags, false); 19077 } 19078 } 19079 } 19080 19081 /** 19082 * Destroy storage areas for given user on all mounted devices. 19083 */ 19084 void destroyUserData(int userId, int flags) { 19085 synchronized (mInstallLock) { 19086 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19087 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19088 final String volumeUuid = vol.getFsUuid(); 19089 destroyUserDataLI(volumeUuid, userId, flags); 19090 } 19091 } 19092 } 19093 19094 private void destroyUserDataLI(String volumeUuid, int userId, int flags) { 19095 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19096 try { 19097 // Clean up app data, profile data, and media data 19098 mInstaller.destroyUserData(volumeUuid, userId, flags); 19099 19100 // Clean up system data 19101 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19102 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19103 FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId)); 19104 FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId)); 19105 } 19106 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19107 FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId)); 19108 } 19109 } 19110 19111 // Data with special labels is now gone, so finish the job 19112 storage.destroyUserStorage(volumeUuid, userId, flags); 19113 19114 } catch (Exception e) { 19115 logCriticalInfo(Log.WARN, 19116 "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e); 19117 } 19118 } 19119 19120 /** 19121 * Examine all users present on given mounted volume, and destroy data 19122 * belonging to users that are no longer valid, or whose user ID has been 19123 * recycled. 19124 */ 19125 private void reconcileUsers(String volumeUuid) { 19126 final List<File> files = new ArrayList<>(); 19127 Collections.addAll(files, FileUtils 19128 .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid))); 19129 Collections.addAll(files, FileUtils 19130 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid))); 19131 for (File file : files) { 19132 if (!file.isDirectory()) continue; 19133 19134 final int userId; 19135 final UserInfo info; 19136 try { 19137 userId = Integer.parseInt(file.getName()); 19138 info = sUserManager.getUserInfo(userId); 19139 } catch (NumberFormatException e) { 19140 Slog.w(TAG, "Invalid user directory " + file); 19141 continue; 19142 } 19143 19144 boolean destroyUser = false; 19145 if (info == null) { 19146 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19147 + " because no matching user was found"); 19148 destroyUser = true; 19149 } else if (!mOnlyCore) { 19150 try { 19151 UserManagerService.enforceSerialNumber(file, info.serialNumber); 19152 } catch (IOException e) { 19153 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19154 + " because we failed to enforce serial number: " + e); 19155 destroyUser = true; 19156 } 19157 } 19158 19159 if (destroyUser) { 19160 synchronized (mInstallLock) { 19161 destroyUserDataLI(volumeUuid, userId, 19162 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19163 } 19164 } 19165 } 19166 } 19167 19168 private void assertPackageKnown(String volumeUuid, String packageName) 19169 throws PackageManagerException { 19170 synchronized (mPackages) { 19171 final PackageSetting ps = mSettings.mPackages.get(packageName); 19172 if (ps == null) { 19173 throw new PackageManagerException("Package " + packageName + " is unknown"); 19174 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19175 throw new PackageManagerException( 19176 "Package " + packageName + " found on unknown volume " + volumeUuid 19177 + "; expected volume " + ps.volumeUuid); 19178 } 19179 } 19180 } 19181 19182 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 19183 throws PackageManagerException { 19184 synchronized (mPackages) { 19185 final PackageSetting ps = mSettings.mPackages.get(packageName); 19186 if (ps == null) { 19187 throw new PackageManagerException("Package " + packageName + " is unknown"); 19188 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19189 throw new PackageManagerException( 19190 "Package " + packageName + " found on unknown volume " + volumeUuid 19191 + "; expected volume " + ps.volumeUuid); 19192 } else if (!ps.getInstalled(userId)) { 19193 throw new PackageManagerException( 19194 "Package " + packageName + " not installed for user " + userId); 19195 } 19196 } 19197 } 19198 19199 /** 19200 * Examine all apps present on given mounted volume, and destroy apps that 19201 * aren't expected, either due to uninstallation or reinstallation on 19202 * another volume. 19203 */ 19204 private void reconcileApps(String volumeUuid) { 19205 final File[] files = FileUtils 19206 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 19207 for (File file : files) { 19208 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 19209 && !PackageInstallerService.isStageName(file.getName()); 19210 if (!isPackage) { 19211 // Ignore entries which are not packages 19212 continue; 19213 } 19214 19215 try { 19216 final PackageLite pkg = PackageParser.parsePackageLite(file, 19217 PackageParser.PARSE_MUST_BE_APK); 19218 assertPackageKnown(volumeUuid, pkg.packageName); 19219 19220 } catch (PackageParserException | PackageManagerException e) { 19221 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19222 synchronized (mInstallLock) { 19223 removeCodePathLI(file); 19224 } 19225 } 19226 } 19227 } 19228 19229 /** 19230 * Reconcile all app data for the given user. 19231 * <p> 19232 * Verifies that directories exist and that ownership and labeling is 19233 * correct for all installed apps on all mounted volumes. 19234 */ 19235 void reconcileAppsData(int userId, int flags) { 19236 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19237 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19238 final String volumeUuid = vol.getFsUuid(); 19239 synchronized (mInstallLock) { 19240 reconcileAppsDataLI(volumeUuid, userId, flags); 19241 } 19242 } 19243 } 19244 19245 /** 19246 * Reconcile all app data on given mounted volume. 19247 * <p> 19248 * Destroys app data that isn't expected, either due to uninstallation or 19249 * reinstallation on another volume. 19250 * <p> 19251 * Verifies that directories exist and that ownership and labeling is 19252 * correct for all installed apps. 19253 */ 19254 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) { 19255 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 19256 + Integer.toHexString(flags)); 19257 19258 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 19259 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 19260 19261 boolean restoreconNeeded = false; 19262 19263 // First look for stale data that doesn't belong, and check if things 19264 // have changed since we did our last restorecon 19265 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19266 if (StorageManager.isFileEncryptedNativeOrEmulated() 19267 && !StorageManager.isUserKeyUnlocked(userId)) { 19268 throw new RuntimeException( 19269 "Yikes, someone asked us to reconcile CE storage while " + userId 19270 + " was still locked; this would have caused massive data loss!"); 19271 } 19272 19273 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 19274 19275 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 19276 for (File file : files) { 19277 final String packageName = file.getName(); 19278 try { 19279 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19280 } catch (PackageManagerException e) { 19281 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19282 try { 19283 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19284 StorageManager.FLAG_STORAGE_CE, 0); 19285 } catch (InstallerException e2) { 19286 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19287 } 19288 } 19289 } 19290 } 19291 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19292 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 19293 19294 final File[] files = FileUtils.listFilesOrEmpty(deDir); 19295 for (File file : files) { 19296 final String packageName = file.getName(); 19297 try { 19298 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19299 } catch (PackageManagerException e) { 19300 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19301 try { 19302 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19303 StorageManager.FLAG_STORAGE_DE, 0); 19304 } catch (InstallerException e2) { 19305 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19306 } 19307 } 19308 } 19309 } 19310 19311 // Ensure that data directories are ready to roll for all packages 19312 // installed for this volume and user 19313 final List<PackageSetting> packages; 19314 synchronized (mPackages) { 19315 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19316 } 19317 int preparedCount = 0; 19318 for (PackageSetting ps : packages) { 19319 final String packageName = ps.name; 19320 if (ps.pkg == null) { 19321 Slog.w(TAG, "Odd, missing scanned package " + packageName); 19322 // TODO: might be due to legacy ASEC apps; we should circle back 19323 // and reconcile again once they're scanned 19324 continue; 19325 } 19326 19327 if (ps.getInstalled(userId)) { 19328 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19329 19330 if (maybeMigrateAppDataLIF(ps.pkg, userId)) { 19331 // We may have just shuffled around app data directories, so 19332 // prepare them one more time 19333 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19334 } 19335 19336 preparedCount++; 19337 } 19338 } 19339 19340 if (restoreconNeeded) { 19341 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19342 SELinuxMMAC.setRestoreconDone(ceDir); 19343 } 19344 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19345 SELinuxMMAC.setRestoreconDone(deDir); 19346 } 19347 } 19348 19349 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 19350 + " packages; restoreconNeeded was " + restoreconNeeded); 19351 } 19352 19353 /** 19354 * Prepare app data for the given app just after it was installed or 19355 * upgraded. This method carefully only touches users that it's installed 19356 * for, and it forces a restorecon to handle any seinfo changes. 19357 * <p> 19358 * Verifies that directories exist and that ownership and labeling is 19359 * correct for all installed apps. If there is an ownership mismatch, it 19360 * will try recovering system apps by wiping data; third-party app data is 19361 * left intact. 19362 * <p> 19363 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 19364 */ 19365 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 19366 final PackageSetting ps; 19367 synchronized (mPackages) { 19368 ps = mSettings.mPackages.get(pkg.packageName); 19369 mSettings.writeKernelMappingLPr(ps); 19370 } 19371 19372 final UserManager um = mContext.getSystemService(UserManager.class); 19373 for (UserInfo user : um.getUsers()) { 19374 final int flags; 19375 if (um.isUserUnlockingOrUnlocked(user.id)) { 19376 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19377 } else if (um.isUserRunning(user.id)) { 19378 flags = StorageManager.FLAG_STORAGE_DE; 19379 } else { 19380 continue; 19381 } 19382 19383 if (ps.getInstalled(user.id)) { 19384 // Whenever an app changes, force a restorecon of its data 19385 // TODO: when user data is locked, mark that we're still dirty 19386 prepareAppDataLIF(pkg, user.id, flags, true); 19387 } 19388 } 19389 } 19390 19391 /** 19392 * Prepare app data for the given app. 19393 * <p> 19394 * Verifies that directories exist and that ownership and labeling is 19395 * correct for all installed apps. If there is an ownership mismatch, this 19396 * will try recovering system apps by wiping data; third-party app data is 19397 * left intact. 19398 */ 19399 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags, 19400 boolean restoreconNeeded) { 19401 if (pkg == null) { 19402 Slog.wtf(TAG, "Package was null!", new Throwable()); 19403 return; 19404 } 19405 prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded); 19406 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19407 for (int i = 0; i < childCount; i++) { 19408 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded); 19409 } 19410 } 19411 19412 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags, 19413 boolean restoreconNeeded) { 19414 if (DEBUG_APP_DATA) { 19415 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 19416 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 19417 } 19418 19419 final String volumeUuid = pkg.volumeUuid; 19420 final String packageName = pkg.packageName; 19421 final ApplicationInfo app = pkg.applicationInfo; 19422 final int appId = UserHandle.getAppId(app.uid); 19423 19424 Preconditions.checkNotNull(app.seinfo); 19425 19426 try { 19427 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19428 appId, app.seinfo, app.targetSdkVersion); 19429 } catch (InstallerException e) { 19430 if (app.isSystemApp()) { 19431 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 19432 + ", but trying to recover: " + e); 19433 destroyAppDataLeafLIF(pkg, userId, flags); 19434 try { 19435 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19436 appId, app.seinfo, app.targetSdkVersion); 19437 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 19438 } catch (InstallerException e2) { 19439 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 19440 } 19441 } else { 19442 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 19443 } 19444 } 19445 19446 if (restoreconNeeded) { 19447 try { 19448 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, 19449 app.seinfo); 19450 } catch (InstallerException e) { 19451 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 19452 } 19453 } 19454 19455 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19456 try { 19457 // CE storage is unlocked right now, so read out the inode and 19458 // remember for use later when it's locked 19459 // TODO: mark this structure as dirty so we persist it! 19460 final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId, 19461 StorageManager.FLAG_STORAGE_CE); 19462 synchronized (mPackages) { 19463 final PackageSetting ps = mSettings.mPackages.get(packageName); 19464 if (ps != null) { 19465 ps.setCeDataInode(ceDataInode, userId); 19466 } 19467 } 19468 } catch (InstallerException e) { 19469 Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e); 19470 } 19471 } 19472 19473 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19474 } 19475 19476 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 19477 if (pkg == null) { 19478 Slog.wtf(TAG, "Package was null!", new Throwable()); 19479 return; 19480 } 19481 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19482 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19483 for (int i = 0; i < childCount; i++) { 19484 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 19485 } 19486 } 19487 19488 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 19489 final String volumeUuid = pkg.volumeUuid; 19490 final String packageName = pkg.packageName; 19491 final ApplicationInfo app = pkg.applicationInfo; 19492 19493 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19494 // Create a native library symlink only if we have native libraries 19495 // and if the native libraries are 32 bit libraries. We do not provide 19496 // this symlink for 64 bit libraries. 19497 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 19498 final String nativeLibPath = app.nativeLibraryDir; 19499 try { 19500 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 19501 nativeLibPath, userId); 19502 } catch (InstallerException e) { 19503 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 19504 } 19505 } 19506 } 19507 } 19508 19509 /** 19510 * For system apps on non-FBE devices, this method migrates any existing 19511 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 19512 * requested by the app. 19513 */ 19514 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 19515 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 19516 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 19517 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 19518 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 19519 try { 19520 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 19521 storageTarget); 19522 } catch (InstallerException e) { 19523 logCriticalInfo(Log.WARN, 19524 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 19525 } 19526 return true; 19527 } else { 19528 return false; 19529 } 19530 } 19531 19532 public PackageFreezer freezePackage(String packageName, String killReason) { 19533 return new PackageFreezer(packageName, killReason); 19534 } 19535 19536 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 19537 String killReason) { 19538 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 19539 return new PackageFreezer(); 19540 } else { 19541 return freezePackage(packageName, killReason); 19542 } 19543 } 19544 19545 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 19546 String killReason) { 19547 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 19548 return new PackageFreezer(); 19549 } else { 19550 return freezePackage(packageName, killReason); 19551 } 19552 } 19553 19554 /** 19555 * Class that freezes and kills the given package upon creation, and 19556 * unfreezes it upon closing. This is typically used when doing surgery on 19557 * app code/data to prevent the app from running while you're working. 19558 */ 19559 private class PackageFreezer implements AutoCloseable { 19560 private final String mPackageName; 19561 private final PackageFreezer[] mChildren; 19562 19563 private final boolean mWeFroze; 19564 19565 private final AtomicBoolean mClosed = new AtomicBoolean(); 19566 private final CloseGuard mCloseGuard = CloseGuard.get(); 19567 19568 /** 19569 * Create and return a stub freezer that doesn't actually do anything, 19570 * typically used when someone requested 19571 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 19572 * {@link PackageManager#DELETE_DONT_KILL_APP}. 19573 */ 19574 public PackageFreezer() { 19575 mPackageName = null; 19576 mChildren = null; 19577 mWeFroze = false; 19578 mCloseGuard.open("close"); 19579 } 19580 19581 public PackageFreezer(String packageName, String killReason) { 19582 synchronized (mPackages) { 19583 mPackageName = packageName; 19584 mWeFroze = mFrozenPackages.add(mPackageName); 19585 19586 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 19587 if (ps != null) { 19588 killApplication(ps.name, ps.appId, killReason); 19589 } 19590 19591 final PackageParser.Package p = mPackages.get(packageName); 19592 if (p != null && p.childPackages != null) { 19593 final int N = p.childPackages.size(); 19594 mChildren = new PackageFreezer[N]; 19595 for (int i = 0; i < N; i++) { 19596 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 19597 killReason); 19598 } 19599 } else { 19600 mChildren = null; 19601 } 19602 } 19603 mCloseGuard.open("close"); 19604 } 19605 19606 @Override 19607 protected void finalize() throws Throwable { 19608 try { 19609 mCloseGuard.warnIfOpen(); 19610 close(); 19611 } finally { 19612 super.finalize(); 19613 } 19614 } 19615 19616 @Override 19617 public void close() { 19618 mCloseGuard.close(); 19619 if (mClosed.compareAndSet(false, true)) { 19620 synchronized (mPackages) { 19621 if (mWeFroze) { 19622 mFrozenPackages.remove(mPackageName); 19623 } 19624 19625 if (mChildren != null) { 19626 for (PackageFreezer freezer : mChildren) { 19627 freezer.close(); 19628 } 19629 } 19630 } 19631 } 19632 } 19633 } 19634 19635 /** 19636 * Verify that given package is currently frozen. 19637 */ 19638 private void checkPackageFrozen(String packageName) { 19639 synchronized (mPackages) { 19640 if (!mFrozenPackages.contains(packageName)) { 19641 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 19642 } 19643 } 19644 } 19645 19646 @Override 19647 public int movePackage(final String packageName, final String volumeUuid) { 19648 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19649 19650 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 19651 final int moveId = mNextMoveId.getAndIncrement(); 19652 mHandler.post(new Runnable() { 19653 @Override 19654 public void run() { 19655 try { 19656 movePackageInternal(packageName, volumeUuid, moveId, user); 19657 } catch (PackageManagerException e) { 19658 Slog.w(TAG, "Failed to move " + packageName, e); 19659 mMoveCallbacks.notifyStatusChanged(moveId, 19660 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19661 } 19662 } 19663 }); 19664 return moveId; 19665 } 19666 19667 private void movePackageInternal(final String packageName, final String volumeUuid, 19668 final int moveId, UserHandle user) throws PackageManagerException { 19669 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19670 final PackageManager pm = mContext.getPackageManager(); 19671 19672 final boolean currentAsec; 19673 final String currentVolumeUuid; 19674 final File codeFile; 19675 final String installerPackageName; 19676 final String packageAbiOverride; 19677 final int appId; 19678 final String seinfo; 19679 final String label; 19680 final int targetSdkVersion; 19681 final PackageFreezer freezer; 19682 final int[] installedUserIds; 19683 19684 // reader 19685 synchronized (mPackages) { 19686 final PackageParser.Package pkg = mPackages.get(packageName); 19687 final PackageSetting ps = mSettings.mPackages.get(packageName); 19688 if (pkg == null || ps == null) { 19689 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 19690 } 19691 19692 if (pkg.applicationInfo.isSystemApp()) { 19693 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 19694 "Cannot move system application"); 19695 } 19696 19697 if (pkg.applicationInfo.isExternalAsec()) { 19698 currentAsec = true; 19699 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 19700 } else if (pkg.applicationInfo.isForwardLocked()) { 19701 currentAsec = true; 19702 currentVolumeUuid = "forward_locked"; 19703 } else { 19704 currentAsec = false; 19705 currentVolumeUuid = ps.volumeUuid; 19706 19707 final File probe = new File(pkg.codePath); 19708 final File probeOat = new File(probe, "oat"); 19709 if (!probe.isDirectory() || !probeOat.isDirectory()) { 19710 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19711 "Move only supported for modern cluster style installs"); 19712 } 19713 } 19714 19715 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 19716 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19717 "Package already moved to " + volumeUuid); 19718 } 19719 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 19720 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 19721 "Device admin cannot be moved"); 19722 } 19723 19724 if (mFrozenPackages.contains(packageName)) { 19725 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 19726 "Failed to move already frozen package"); 19727 } 19728 19729 codeFile = new File(pkg.codePath); 19730 installerPackageName = ps.installerPackageName; 19731 packageAbiOverride = ps.cpuAbiOverrideString; 19732 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 19733 seinfo = pkg.applicationInfo.seinfo; 19734 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 19735 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 19736 freezer = new PackageFreezer(packageName, "movePackageInternal"); 19737 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 19738 } 19739 19740 final Bundle extras = new Bundle(); 19741 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 19742 extras.putString(Intent.EXTRA_TITLE, label); 19743 mMoveCallbacks.notifyCreated(moveId, extras); 19744 19745 int installFlags; 19746 final boolean moveCompleteApp; 19747 final File measurePath; 19748 19749 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 19750 installFlags = INSTALL_INTERNAL; 19751 moveCompleteApp = !currentAsec; 19752 measurePath = Environment.getDataAppDirectory(volumeUuid); 19753 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 19754 installFlags = INSTALL_EXTERNAL; 19755 moveCompleteApp = false; 19756 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 19757 } else { 19758 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 19759 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 19760 || !volume.isMountedWritable()) { 19761 freezer.close(); 19762 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19763 "Move location not mounted private volume"); 19764 } 19765 19766 Preconditions.checkState(!currentAsec); 19767 19768 installFlags = INSTALL_INTERNAL; 19769 moveCompleteApp = true; 19770 measurePath = Environment.getDataAppDirectory(volumeUuid); 19771 } 19772 19773 final PackageStats stats = new PackageStats(null, -1); 19774 synchronized (mInstaller) { 19775 for (int userId : installedUserIds) { 19776 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 19777 freezer.close(); 19778 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19779 "Failed to measure package size"); 19780 } 19781 } 19782 } 19783 19784 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 19785 + stats.dataSize); 19786 19787 final long startFreeBytes = measurePath.getFreeSpace(); 19788 final long sizeBytes; 19789 if (moveCompleteApp) { 19790 sizeBytes = stats.codeSize + stats.dataSize; 19791 } else { 19792 sizeBytes = stats.codeSize; 19793 } 19794 19795 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 19796 freezer.close(); 19797 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19798 "Not enough free space to move"); 19799 } 19800 19801 mMoveCallbacks.notifyStatusChanged(moveId, 10); 19802 19803 final CountDownLatch installedLatch = new CountDownLatch(1); 19804 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 19805 @Override 19806 public void onUserActionRequired(Intent intent) throws RemoteException { 19807 throw new IllegalStateException(); 19808 } 19809 19810 @Override 19811 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 19812 Bundle extras) throws RemoteException { 19813 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 19814 + PackageManager.installStatusToString(returnCode, msg)); 19815 19816 installedLatch.countDown(); 19817 freezer.close(); 19818 19819 final int status = PackageManager.installStatusToPublicStatus(returnCode); 19820 switch (status) { 19821 case PackageInstaller.STATUS_SUCCESS: 19822 mMoveCallbacks.notifyStatusChanged(moveId, 19823 PackageManager.MOVE_SUCCEEDED); 19824 break; 19825 case PackageInstaller.STATUS_FAILURE_STORAGE: 19826 mMoveCallbacks.notifyStatusChanged(moveId, 19827 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 19828 break; 19829 default: 19830 mMoveCallbacks.notifyStatusChanged(moveId, 19831 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19832 break; 19833 } 19834 } 19835 }; 19836 19837 final MoveInfo move; 19838 if (moveCompleteApp) { 19839 // Kick off a thread to report progress estimates 19840 new Thread() { 19841 @Override 19842 public void run() { 19843 while (true) { 19844 try { 19845 if (installedLatch.await(1, TimeUnit.SECONDS)) { 19846 break; 19847 } 19848 } catch (InterruptedException ignored) { 19849 } 19850 19851 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 19852 final int progress = 10 + (int) MathUtils.constrain( 19853 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 19854 mMoveCallbacks.notifyStatusChanged(moveId, progress); 19855 } 19856 } 19857 }.start(); 19858 19859 final String dataAppName = codeFile.getName(); 19860 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 19861 dataAppName, appId, seinfo, targetSdkVersion); 19862 } else { 19863 move = null; 19864 } 19865 19866 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 19867 19868 final Message msg = mHandler.obtainMessage(INIT_COPY); 19869 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 19870 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 19871 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 19872 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/); 19873 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 19874 msg.obj = params; 19875 19876 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 19877 System.identityHashCode(msg.obj)); 19878 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 19879 System.identityHashCode(msg.obj)); 19880 19881 mHandler.sendMessage(msg); 19882 } 19883 19884 @Override 19885 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 19886 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19887 19888 final int realMoveId = mNextMoveId.getAndIncrement(); 19889 final Bundle extras = new Bundle(); 19890 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 19891 mMoveCallbacks.notifyCreated(realMoveId, extras); 19892 19893 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 19894 @Override 19895 public void onCreated(int moveId, Bundle extras) { 19896 // Ignored 19897 } 19898 19899 @Override 19900 public void onStatusChanged(int moveId, int status, long estMillis) { 19901 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 19902 } 19903 }; 19904 19905 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19906 storage.setPrimaryStorageUuid(volumeUuid, callback); 19907 return realMoveId; 19908 } 19909 19910 @Override 19911 public int getMoveStatus(int moveId) { 19912 mContext.enforceCallingOrSelfPermission( 19913 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19914 return mMoveCallbacks.mLastStatus.get(moveId); 19915 } 19916 19917 @Override 19918 public void registerMoveCallback(IPackageMoveObserver callback) { 19919 mContext.enforceCallingOrSelfPermission( 19920 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19921 mMoveCallbacks.register(callback); 19922 } 19923 19924 @Override 19925 public void unregisterMoveCallback(IPackageMoveObserver callback) { 19926 mContext.enforceCallingOrSelfPermission( 19927 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19928 mMoveCallbacks.unregister(callback); 19929 } 19930 19931 @Override 19932 public boolean setInstallLocation(int loc) { 19933 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 19934 null); 19935 if (getInstallLocation() == loc) { 19936 return true; 19937 } 19938 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 19939 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 19940 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 19941 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 19942 return true; 19943 } 19944 return false; 19945 } 19946 19947 @Override 19948 public int getInstallLocation() { 19949 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 19950 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 19951 PackageHelper.APP_INSTALL_AUTO); 19952 } 19953 19954 /** Called by UserManagerService */ 19955 void cleanUpUser(UserManagerService userManager, int userHandle) { 19956 synchronized (mPackages) { 19957 mDirtyUsers.remove(userHandle); 19958 mUserNeedsBadging.delete(userHandle); 19959 mSettings.removeUserLPw(userHandle); 19960 mPendingBroadcasts.remove(userHandle); 19961 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 19962 removeUnusedPackagesLPw(userManager, userHandle); 19963 } 19964 } 19965 19966 /** 19967 * We're removing userHandle and would like to remove any downloaded packages 19968 * that are no longer in use by any other user. 19969 * @param userHandle the user being removed 19970 */ 19971 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 19972 final boolean DEBUG_CLEAN_APKS = false; 19973 int [] users = userManager.getUserIds(); 19974 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 19975 while (psit.hasNext()) { 19976 PackageSetting ps = psit.next(); 19977 if (ps.pkg == null) { 19978 continue; 19979 } 19980 final String packageName = ps.pkg.packageName; 19981 // Skip over if system app 19982 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 19983 continue; 19984 } 19985 if (DEBUG_CLEAN_APKS) { 19986 Slog.i(TAG, "Checking package " + packageName); 19987 } 19988 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 19989 if (keep) { 19990 if (DEBUG_CLEAN_APKS) { 19991 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 19992 } 19993 } else { 19994 for (int i = 0; i < users.length; i++) { 19995 if (users[i] != userHandle && ps.getInstalled(users[i])) { 19996 keep = true; 19997 if (DEBUG_CLEAN_APKS) { 19998 Slog.i(TAG, " Keeping package " + packageName + " for user " 19999 + users[i]); 20000 } 20001 break; 20002 } 20003 } 20004 } 20005 if (!keep) { 20006 if (DEBUG_CLEAN_APKS) { 20007 Slog.i(TAG, " Removing package " + packageName); 20008 } 20009 mHandler.post(new Runnable() { 20010 public void run() { 20011 deletePackageX(packageName, userHandle, 0); 20012 } //end run 20013 }); 20014 } 20015 } 20016 } 20017 20018 /** Called by UserManagerService */ 20019 void createNewUser(int userId) { 20020 synchronized (mInstallLock) { 20021 mSettings.createNewUserLI(this, mInstaller, userId); 20022 } 20023 synchronized (mPackages) { 20024 scheduleWritePackageRestrictionsLocked(userId); 20025 scheduleWritePackageListLocked(userId); 20026 applyFactoryDefaultBrowserLPw(userId); 20027 primeDomainVerificationsLPw(userId); 20028 } 20029 } 20030 20031 void newUserCreated(final int userHandle) { 20032 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 20033 // If permission review for legacy apps is required, we represent 20034 // dagerous permissions for such apps as always granted runtime 20035 // permissions to keep per user flag state whether review is needed. 20036 // Hence, if a new user is added we have to propagate dangerous 20037 // permission grants for these legacy apps. 20038 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 20039 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 20040 | UPDATE_PERMISSIONS_REPLACE_ALL); 20041 } 20042 } 20043 20044 @Override 20045 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 20046 mContext.enforceCallingOrSelfPermission( 20047 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 20048 "Only package verification agents can read the verifier device identity"); 20049 20050 synchronized (mPackages) { 20051 return mSettings.getVerifierDeviceIdentityLPw(); 20052 } 20053 } 20054 20055 @Override 20056 public void setPermissionEnforced(String permission, boolean enforced) { 20057 // TODO: Now that we no longer change GID for storage, this should to away. 20058 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 20059 "setPermissionEnforced"); 20060 if (READ_EXTERNAL_STORAGE.equals(permission)) { 20061 synchronized (mPackages) { 20062 if (mSettings.mReadExternalStorageEnforced == null 20063 || mSettings.mReadExternalStorageEnforced != enforced) { 20064 mSettings.mReadExternalStorageEnforced = enforced; 20065 mSettings.writeLPr(); 20066 } 20067 } 20068 // kill any non-foreground processes so we restart them and 20069 // grant/revoke the GID. 20070 final IActivityManager am = ActivityManagerNative.getDefault(); 20071 if (am != null) { 20072 final long token = Binder.clearCallingIdentity(); 20073 try { 20074 am.killProcessesBelowForeground("setPermissionEnforcement"); 20075 } catch (RemoteException e) { 20076 } finally { 20077 Binder.restoreCallingIdentity(token); 20078 } 20079 } 20080 } else { 20081 throw new IllegalArgumentException("No selective enforcement for " + permission); 20082 } 20083 } 20084 20085 @Override 20086 @Deprecated 20087 public boolean isPermissionEnforced(String permission) { 20088 return true; 20089 } 20090 20091 @Override 20092 public boolean isStorageLow() { 20093 final long token = Binder.clearCallingIdentity(); 20094 try { 20095 final DeviceStorageMonitorInternal 20096 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 20097 if (dsm != null) { 20098 return dsm.isMemoryLow(); 20099 } else { 20100 return false; 20101 } 20102 } finally { 20103 Binder.restoreCallingIdentity(token); 20104 } 20105 } 20106 20107 @Override 20108 public IPackageInstaller getPackageInstaller() { 20109 return mInstallerService; 20110 } 20111 20112 private boolean userNeedsBadging(int userId) { 20113 int index = mUserNeedsBadging.indexOfKey(userId); 20114 if (index < 0) { 20115 final UserInfo userInfo; 20116 final long token = Binder.clearCallingIdentity(); 20117 try { 20118 userInfo = sUserManager.getUserInfo(userId); 20119 } finally { 20120 Binder.restoreCallingIdentity(token); 20121 } 20122 final boolean b; 20123 if (userInfo != null && userInfo.isManagedProfile()) { 20124 b = true; 20125 } else { 20126 b = false; 20127 } 20128 mUserNeedsBadging.put(userId, b); 20129 return b; 20130 } 20131 return mUserNeedsBadging.valueAt(index); 20132 } 20133 20134 @Override 20135 public KeySet getKeySetByAlias(String packageName, String alias) { 20136 if (packageName == null || alias == null) { 20137 return null; 20138 } 20139 synchronized(mPackages) { 20140 final PackageParser.Package pkg = mPackages.get(packageName); 20141 if (pkg == null) { 20142 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20143 throw new IllegalArgumentException("Unknown package: " + packageName); 20144 } 20145 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20146 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 20147 } 20148 } 20149 20150 @Override 20151 public KeySet getSigningKeySet(String packageName) { 20152 if (packageName == null) { 20153 return null; 20154 } 20155 synchronized(mPackages) { 20156 final PackageParser.Package pkg = mPackages.get(packageName); 20157 if (pkg == null) { 20158 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20159 throw new IllegalArgumentException("Unknown package: " + packageName); 20160 } 20161 if (pkg.applicationInfo.uid != Binder.getCallingUid() 20162 && Process.SYSTEM_UID != Binder.getCallingUid()) { 20163 throw new SecurityException("May not access signing KeySet of other apps."); 20164 } 20165 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20166 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 20167 } 20168 } 20169 20170 @Override 20171 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 20172 if (packageName == null || ks == null) { 20173 return false; 20174 } 20175 synchronized(mPackages) { 20176 final PackageParser.Package pkg = mPackages.get(packageName); 20177 if (pkg == null) { 20178 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20179 throw new IllegalArgumentException("Unknown package: " + packageName); 20180 } 20181 IBinder ksh = ks.getToken(); 20182 if (ksh instanceof KeySetHandle) { 20183 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20184 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 20185 } 20186 return false; 20187 } 20188 } 20189 20190 @Override 20191 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 20192 if (packageName == null || ks == null) { 20193 return false; 20194 } 20195 synchronized(mPackages) { 20196 final PackageParser.Package pkg = mPackages.get(packageName); 20197 if (pkg == null) { 20198 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20199 throw new IllegalArgumentException("Unknown package: " + packageName); 20200 } 20201 IBinder ksh = ks.getToken(); 20202 if (ksh instanceof KeySetHandle) { 20203 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20204 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 20205 } 20206 return false; 20207 } 20208 } 20209 20210 private void deletePackageIfUnusedLPr(final String packageName) { 20211 PackageSetting ps = mSettings.mPackages.get(packageName); 20212 if (ps == null) { 20213 return; 20214 } 20215 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 20216 // TODO Implement atomic delete if package is unused 20217 // It is currently possible that the package will be deleted even if it is installed 20218 // after this method returns. 20219 mHandler.post(new Runnable() { 20220 public void run() { 20221 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 20222 } 20223 }); 20224 } 20225 } 20226 20227 /** 20228 * Check and throw if the given before/after packages would be considered a 20229 * downgrade. 20230 */ 20231 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 20232 throws PackageManagerException { 20233 if (after.versionCode < before.mVersionCode) { 20234 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20235 "Update version code " + after.versionCode + " is older than current " 20236 + before.mVersionCode); 20237 } else if (after.versionCode == before.mVersionCode) { 20238 if (after.baseRevisionCode < before.baseRevisionCode) { 20239 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20240 "Update base revision code " + after.baseRevisionCode 20241 + " is older than current " + before.baseRevisionCode); 20242 } 20243 20244 if (!ArrayUtils.isEmpty(after.splitNames)) { 20245 for (int i = 0; i < after.splitNames.length; i++) { 20246 final String splitName = after.splitNames[i]; 20247 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 20248 if (j != -1) { 20249 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 20250 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20251 "Update split " + splitName + " revision code " 20252 + after.splitRevisionCodes[i] + " is older than current " 20253 + before.splitRevisionCodes[j]); 20254 } 20255 } 20256 } 20257 } 20258 } 20259 } 20260 20261 private static class MoveCallbacks extends Handler { 20262 private static final int MSG_CREATED = 1; 20263 private static final int MSG_STATUS_CHANGED = 2; 20264 20265 private final RemoteCallbackList<IPackageMoveObserver> 20266 mCallbacks = new RemoteCallbackList<>(); 20267 20268 private final SparseIntArray mLastStatus = new SparseIntArray(); 20269 20270 public MoveCallbacks(Looper looper) { 20271 super(looper); 20272 } 20273 20274 public void register(IPackageMoveObserver callback) { 20275 mCallbacks.register(callback); 20276 } 20277 20278 public void unregister(IPackageMoveObserver callback) { 20279 mCallbacks.unregister(callback); 20280 } 20281 20282 @Override 20283 public void handleMessage(Message msg) { 20284 final SomeArgs args = (SomeArgs) msg.obj; 20285 final int n = mCallbacks.beginBroadcast(); 20286 for (int i = 0; i < n; i++) { 20287 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 20288 try { 20289 invokeCallback(callback, msg.what, args); 20290 } catch (RemoteException ignored) { 20291 } 20292 } 20293 mCallbacks.finishBroadcast(); 20294 args.recycle(); 20295 } 20296 20297 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 20298 throws RemoteException { 20299 switch (what) { 20300 case MSG_CREATED: { 20301 callback.onCreated(args.argi1, (Bundle) args.arg2); 20302 break; 20303 } 20304 case MSG_STATUS_CHANGED: { 20305 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 20306 break; 20307 } 20308 } 20309 } 20310 20311 private void notifyCreated(int moveId, Bundle extras) { 20312 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 20313 20314 final SomeArgs args = SomeArgs.obtain(); 20315 args.argi1 = moveId; 20316 args.arg2 = extras; 20317 obtainMessage(MSG_CREATED, args).sendToTarget(); 20318 } 20319 20320 private void notifyStatusChanged(int moveId, int status) { 20321 notifyStatusChanged(moveId, status, -1); 20322 } 20323 20324 private void notifyStatusChanged(int moveId, int status, long estMillis) { 20325 Slog.v(TAG, "Move " + moveId + " status " + status); 20326 20327 final SomeArgs args = SomeArgs.obtain(); 20328 args.argi1 = moveId; 20329 args.argi2 = status; 20330 args.arg3 = estMillis; 20331 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 20332 20333 synchronized (mLastStatus) { 20334 mLastStatus.put(moveId, status); 20335 } 20336 } 20337 } 20338 20339 private final static class OnPermissionChangeListeners extends Handler { 20340 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 20341 20342 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 20343 new RemoteCallbackList<>(); 20344 20345 public OnPermissionChangeListeners(Looper looper) { 20346 super(looper); 20347 } 20348 20349 @Override 20350 public void handleMessage(Message msg) { 20351 switch (msg.what) { 20352 case MSG_ON_PERMISSIONS_CHANGED: { 20353 final int uid = msg.arg1; 20354 handleOnPermissionsChanged(uid); 20355 } break; 20356 } 20357 } 20358 20359 public void addListenerLocked(IOnPermissionsChangeListener listener) { 20360 mPermissionListeners.register(listener); 20361 20362 } 20363 20364 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 20365 mPermissionListeners.unregister(listener); 20366 } 20367 20368 public void onPermissionsChanged(int uid) { 20369 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 20370 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 20371 } 20372 } 20373 20374 private void handleOnPermissionsChanged(int uid) { 20375 final int count = mPermissionListeners.beginBroadcast(); 20376 try { 20377 for (int i = 0; i < count; i++) { 20378 IOnPermissionsChangeListener callback = mPermissionListeners 20379 .getBroadcastItem(i); 20380 try { 20381 callback.onPermissionsChanged(uid); 20382 } catch (RemoteException e) { 20383 Log.e(TAG, "Permission listener is dead", e); 20384 } 20385 } 20386 } finally { 20387 mPermissionListeners.finishBroadcast(); 20388 } 20389 } 20390 } 20391 20392 private class PackageManagerInternalImpl extends PackageManagerInternal { 20393 @Override 20394 public void setLocationPackagesProvider(PackagesProvider provider) { 20395 synchronized (mPackages) { 20396 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 20397 } 20398 } 20399 20400 @Override 20401 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 20402 synchronized (mPackages) { 20403 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 20404 } 20405 } 20406 20407 @Override 20408 public void setSmsAppPackagesProvider(PackagesProvider provider) { 20409 synchronized (mPackages) { 20410 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 20411 } 20412 } 20413 20414 @Override 20415 public void setDialerAppPackagesProvider(PackagesProvider provider) { 20416 synchronized (mPackages) { 20417 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 20418 } 20419 } 20420 20421 @Override 20422 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 20423 synchronized (mPackages) { 20424 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 20425 } 20426 } 20427 20428 @Override 20429 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 20430 synchronized (mPackages) { 20431 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 20432 } 20433 } 20434 20435 @Override 20436 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 20437 synchronized (mPackages) { 20438 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 20439 packageName, userId); 20440 } 20441 } 20442 20443 @Override 20444 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 20445 synchronized (mPackages) { 20446 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 20447 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 20448 packageName, userId); 20449 } 20450 } 20451 20452 @Override 20453 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 20454 synchronized (mPackages) { 20455 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 20456 packageName, userId); 20457 } 20458 } 20459 20460 @Override 20461 public void setKeepUninstalledPackages(final List<String> packageList) { 20462 Preconditions.checkNotNull(packageList); 20463 List<String> removedFromList = null; 20464 synchronized (mPackages) { 20465 if (mKeepUninstalledPackages != null) { 20466 final int packagesCount = mKeepUninstalledPackages.size(); 20467 for (int i = 0; i < packagesCount; i++) { 20468 String oldPackage = mKeepUninstalledPackages.get(i); 20469 if (packageList != null && packageList.contains(oldPackage)) { 20470 continue; 20471 } 20472 if (removedFromList == null) { 20473 removedFromList = new ArrayList<>(); 20474 } 20475 removedFromList.add(oldPackage); 20476 } 20477 } 20478 mKeepUninstalledPackages = new ArrayList<>(packageList); 20479 if (removedFromList != null) { 20480 final int removedCount = removedFromList.size(); 20481 for (int i = 0; i < removedCount; i++) { 20482 deletePackageIfUnusedLPr(removedFromList.get(i)); 20483 } 20484 } 20485 } 20486 } 20487 20488 @Override 20489 public boolean isPermissionsReviewRequired(String packageName, int userId) { 20490 synchronized (mPackages) { 20491 // If we do not support permission review, done. 20492 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 20493 return false; 20494 } 20495 20496 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 20497 if (packageSetting == null) { 20498 return false; 20499 } 20500 20501 // Permission review applies only to apps not supporting the new permission model. 20502 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 20503 return false; 20504 } 20505 20506 // Legacy apps have the permission and get user consent on launch. 20507 PermissionsState permissionsState = packageSetting.getPermissionsState(); 20508 return permissionsState.isPermissionReviewRequired(userId); 20509 } 20510 } 20511 20512 @Override 20513 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 20514 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 20515 } 20516 20517 @Override 20518 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 20519 int userId) { 20520 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 20521 } 20522 } 20523 20524 @Override 20525 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 20526 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 20527 synchronized (mPackages) { 20528 final long identity = Binder.clearCallingIdentity(); 20529 try { 20530 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 20531 packageNames, userId); 20532 } finally { 20533 Binder.restoreCallingIdentity(identity); 20534 } 20535 } 20536 } 20537 20538 private static void enforceSystemOrPhoneCaller(String tag) { 20539 int callingUid = Binder.getCallingUid(); 20540 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 20541 throw new SecurityException( 20542 "Cannot call " + tag + " from UID " + callingUid); 20543 } 20544 } 20545 20546 boolean isHistoricalPackageUsageAvailable() { 20547 return mPackageUsage.isHistoricalPackageUsageAvailable(); 20548 } 20549 20550 /** 20551 * Return a <b>copy</b> of the collection of packages known to the package manager. 20552 * @return A copy of the values of mPackages. 20553 */ 20554 Collection<PackageParser.Package> getPackages() { 20555 synchronized (mPackages) { 20556 return new ArrayList<>(mPackages.values()); 20557 } 20558 } 20559 20560 /** 20561 * Logs process start information (including base APK hash) to the security log. 20562 * @hide 20563 */ 20564 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 20565 String apkFile, int pid) { 20566 if (!SecurityLog.isLoggingEnabled()) { 20567 return; 20568 } 20569 Bundle data = new Bundle(); 20570 data.putLong("startTimestamp", System.currentTimeMillis()); 20571 data.putString("processName", processName); 20572 data.putInt("uid", uid); 20573 data.putString("seinfo", seinfo); 20574 data.putString("apkFile", apkFile); 20575 data.putInt("pid", pid); 20576 Message msg = mProcessLoggingHandler.obtainMessage( 20577 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 20578 msg.setData(data); 20579 mProcessLoggingHandler.sendMessage(msg); 20580 } 20581} 20582