PackageManagerService.java revision 7742a315fc0793e330beb14d538e9efca8e67c98
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.annotation.UserIdInt; 106import android.app.ActivityManager; 107import android.app.ActivityManagerNative; 108import android.app.IActivityManager; 109import android.app.ResourcesManager; 110import android.app.admin.IDevicePolicyManager; 111import android.app.admin.SecurityLog; 112import android.app.backup.IBackupManager; 113import android.content.BroadcastReceiver; 114import android.content.ComponentName; 115import android.content.Context; 116import android.content.IIntentReceiver; 117import android.content.Intent; 118import android.content.IntentFilter; 119import android.content.IntentSender; 120import android.content.IntentSender.SendIntentException; 121import android.content.ServiceConnection; 122import android.content.pm.ActivityInfo; 123import android.content.pm.ApplicationInfo; 124import android.content.pm.AppsQueryHelper; 125import android.content.pm.ComponentInfo; 126import android.content.pm.EphemeralApplicationInfo; 127import android.content.pm.EphemeralResolveInfo; 128import android.content.pm.EphemeralResolveInfo.EphemeralDigest; 129import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo; 130import android.content.pm.FeatureInfo; 131import android.content.pm.IOnPermissionsChangeListener; 132import android.content.pm.IPackageDataObserver; 133import android.content.pm.IPackageDeleteObserver; 134import android.content.pm.IPackageDeleteObserver2; 135import android.content.pm.IPackageInstallObserver2; 136import android.content.pm.IPackageInstaller; 137import android.content.pm.IPackageManager; 138import android.content.pm.IPackageMoveObserver; 139import android.content.pm.IPackageStatsObserver; 140import android.content.pm.InstrumentationInfo; 141import android.content.pm.IntentFilterVerificationInfo; 142import android.content.pm.KeySet; 143import android.content.pm.PackageCleanItem; 144import android.content.pm.PackageInfo; 145import android.content.pm.PackageInfoLite; 146import android.content.pm.PackageInstaller; 147import android.content.pm.PackageManager; 148import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 149import android.content.pm.PackageManagerInternal; 150import android.content.pm.PackageParser; 151import android.content.pm.PackageParser.ActivityIntentInfo; 152import android.content.pm.PackageParser.PackageLite; 153import android.content.pm.PackageParser.PackageParserException; 154import android.content.pm.PackageStats; 155import android.content.pm.PackageUserState; 156import android.content.pm.ParceledListSlice; 157import android.content.pm.PermissionGroupInfo; 158import android.content.pm.PermissionInfo; 159import android.content.pm.ProviderInfo; 160import android.content.pm.ResolveInfo; 161import android.content.pm.ServiceInfo; 162import android.content.pm.Signature; 163import android.content.pm.UserInfo; 164import android.content.pm.VerifierDeviceIdentity; 165import android.content.pm.VerifierInfo; 166import android.content.res.Resources; 167import android.graphics.Bitmap; 168import android.hardware.display.DisplayManager; 169import android.net.Uri; 170import android.os.Binder; 171import android.os.Build; 172import android.os.Bundle; 173import android.os.Debug; 174import android.os.Environment; 175import android.os.Environment.UserEnvironment; 176import android.os.FileUtils; 177import android.os.Handler; 178import android.os.IBinder; 179import android.os.Looper; 180import android.os.Message; 181import android.os.Parcel; 182import android.os.ParcelFileDescriptor; 183import android.os.Process; 184import android.os.RemoteCallbackList; 185import android.os.RemoteException; 186import android.os.ResultReceiver; 187import android.os.SELinux; 188import android.os.ServiceManager; 189import android.os.SystemClock; 190import android.os.SystemProperties; 191import android.os.Trace; 192import android.os.UserHandle; 193import android.os.UserManager; 194import android.os.UserManagerInternal; 195import android.os.storage.IMountService; 196import android.os.storage.MountServiceInternal; 197import android.os.storage.StorageEventListener; 198import android.os.storage.StorageManager; 199import android.os.storage.VolumeInfo; 200import android.os.storage.VolumeRecord; 201import android.provider.Settings.Global; 202import android.security.KeyStore; 203import android.security.SystemKeyStore; 204import android.system.ErrnoException; 205import android.system.Os; 206import android.text.TextUtils; 207import android.text.format.DateUtils; 208import android.util.ArrayMap; 209import android.util.ArraySet; 210import android.util.AtomicFile; 211import android.util.DisplayMetrics; 212import android.util.EventLog; 213import android.util.ExceptionUtils; 214import android.util.Log; 215import android.util.LogPrinter; 216import android.util.MathUtils; 217import android.util.PrintStreamPrinter; 218import android.util.Slog; 219import android.util.SparseArray; 220import android.util.SparseBooleanArray; 221import android.util.SparseIntArray; 222import android.util.Xml; 223import android.util.jar.StrictJarFile; 224import android.view.Display; 225 226import com.android.internal.R; 227import com.android.internal.annotations.GuardedBy; 228import com.android.internal.app.IMediaContainerService; 229import com.android.internal.app.ResolverActivity; 230import com.android.internal.content.NativeLibraryHelper; 231import com.android.internal.content.PackageHelper; 232import com.android.internal.logging.MetricsLogger; 233import com.android.internal.os.IParcelFileDescriptorFactory; 234import com.android.internal.os.InstallerConnection.InstallerException; 235import com.android.internal.os.SomeArgs; 236import com.android.internal.os.Zygote; 237import com.android.internal.telephony.CarrierAppUtils; 238import com.android.internal.util.ArrayUtils; 239import com.android.internal.util.FastPrintWriter; 240import com.android.internal.util.FastXmlSerializer; 241import com.android.internal.util.IndentingPrintWriter; 242import com.android.internal.util.Preconditions; 243import com.android.internal.util.XmlUtils; 244import com.android.server.AttributeCache; 245import com.android.server.EventLogTags; 246import com.android.server.FgThread; 247import com.android.server.IntentResolver; 248import com.android.server.LocalServices; 249import com.android.server.ServiceThread; 250import com.android.server.SystemConfig; 251import com.android.server.Watchdog; 252import com.android.server.net.NetworkPolicyManagerInternal; 253import com.android.server.pm.PermissionsState.PermissionState; 254import com.android.server.pm.Settings.DatabaseVersion; 255import com.android.server.pm.Settings.VersionInfo; 256import com.android.server.storage.DeviceStorageMonitorInternal; 257 258import dalvik.system.CloseGuard; 259import dalvik.system.DexFile; 260import dalvik.system.VMRuntime; 261 262import libcore.io.IoUtils; 263import libcore.util.EmptyArray; 264 265import org.xmlpull.v1.XmlPullParser; 266import org.xmlpull.v1.XmlPullParserException; 267import org.xmlpull.v1.XmlSerializer; 268 269import java.io.BufferedInputStream; 270import java.io.BufferedOutputStream; 271import java.io.BufferedReader; 272import java.io.ByteArrayInputStream; 273import java.io.ByteArrayOutputStream; 274import java.io.File; 275import java.io.FileDescriptor; 276import java.io.FileInputStream; 277import java.io.FileNotFoundException; 278import java.io.FileOutputStream; 279import java.io.FileReader; 280import java.io.FilenameFilter; 281import java.io.IOException; 282import java.io.InputStream; 283import java.io.PrintWriter; 284import java.nio.charset.StandardCharsets; 285import java.security.DigestInputStream; 286import java.security.MessageDigest; 287import java.security.NoSuchAlgorithmException; 288import java.security.PublicKey; 289import java.security.cert.Certificate; 290import java.security.cert.CertificateEncodingException; 291import java.security.cert.CertificateException; 292import java.text.SimpleDateFormat; 293import java.util.ArrayList; 294import java.util.Arrays; 295import java.util.Collection; 296import java.util.Collections; 297import java.util.Comparator; 298import java.util.Date; 299import java.util.HashSet; 300import java.util.Iterator; 301import java.util.List; 302import java.util.Map; 303import java.util.Objects; 304import java.util.Set; 305import java.util.concurrent.CountDownLatch; 306import java.util.concurrent.TimeUnit; 307import java.util.concurrent.atomic.AtomicBoolean; 308import java.util.concurrent.atomic.AtomicInteger; 309import java.util.concurrent.atomic.AtomicLong; 310 311/** 312 * Keep track of all those APKs everywhere. 313 * <p> 314 * Internally there are two important locks: 315 * <ul> 316 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 317 * and other related state. It is a fine-grained lock that should only be held 318 * momentarily, as it's one of the most contended locks in the system. 319 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 320 * operations typically involve heavy lifting of application data on disk. Since 321 * {@code installd} is single-threaded, and it's operations can often be slow, 322 * this lock should never be acquired while already holding {@link #mPackages}. 323 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 324 * holding {@link #mInstallLock}. 325 * </ul> 326 * Many internal methods rely on the caller to hold the appropriate locks, and 327 * this contract is expressed through method name suffixes: 328 * <ul> 329 * <li>fooLI(): the caller must hold {@link #mInstallLock} 330 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 331 * being modified must be frozen 332 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 333 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 334 * </ul> 335 * <p> 336 * Because this class is very central to the platform's security; please run all 337 * CTS and unit tests whenever making modifications: 338 * 339 * <pre> 340 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 341 * $ cts-tradefed run commandAndExit cts -m AppSecurityTests 342 * </pre> 343 */ 344public class PackageManagerService extends IPackageManager.Stub { 345 static final String TAG = "PackageManager"; 346 static final boolean DEBUG_SETTINGS = false; 347 static final boolean DEBUG_PREFERRED = false; 348 static final boolean DEBUG_UPGRADE = false; 349 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 350 private static final boolean DEBUG_BACKUP = false; 351 private static final boolean DEBUG_INSTALL = false; 352 private static final boolean DEBUG_REMOVE = false; 353 private static final boolean DEBUG_BROADCASTS = false; 354 private static final boolean DEBUG_SHOW_INFO = false; 355 private static final boolean DEBUG_PACKAGE_INFO = false; 356 private static final boolean DEBUG_INTENT_MATCHING = false; 357 private static final boolean DEBUG_PACKAGE_SCANNING = false; 358 private static final boolean DEBUG_VERIFY = false; 359 private static final boolean DEBUG_FILTERS = false; 360 361 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 362 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 363 // user, but by default initialize to this. 364 static final boolean DEBUG_DEXOPT = false; 365 366 private static final boolean DEBUG_ABI_SELECTION = false; 367 private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE; 368 private static final boolean DEBUG_TRIAGED_MISSING = false; 369 private static final boolean DEBUG_APP_DATA = false; 370 371 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 372 373 private static final boolean DISABLE_EPHEMERAL_APPS = !Build.IS_DEBUGGABLE; 374 375 private static final int RADIO_UID = Process.PHONE_UID; 376 private static final int LOG_UID = Process.LOG_UID; 377 private static final int NFC_UID = Process.NFC_UID; 378 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 379 private static final int SHELL_UID = Process.SHELL_UID; 380 381 // Cap the size of permission trees that 3rd party apps can define 382 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 383 384 // Suffix used during package installation when copying/moving 385 // package apks to install directory. 386 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 387 388 static final int SCAN_NO_DEX = 1<<1; 389 static final int SCAN_FORCE_DEX = 1<<2; 390 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 391 static final int SCAN_NEW_INSTALL = 1<<4; 392 static final int SCAN_NO_PATHS = 1<<5; 393 static final int SCAN_UPDATE_TIME = 1<<6; 394 static final int SCAN_DEFER_DEX = 1<<7; 395 static final int SCAN_BOOTING = 1<<8; 396 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 397 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 398 static final int SCAN_REPLACING = 1<<11; 399 static final int SCAN_REQUIRE_KNOWN = 1<<12; 400 static final int SCAN_MOVE = 1<<13; 401 static final int SCAN_INITIAL = 1<<14; 402 static final int SCAN_CHECK_ONLY = 1<<15; 403 static final int SCAN_DONT_KILL_APP = 1<<17; 404 static final int SCAN_IGNORE_FROZEN = 1<<18; 405 406 static final int REMOVE_CHATTY = 1<<16; 407 408 private static final int[] EMPTY_INT_ARRAY = new int[0]; 409 410 /** 411 * Timeout (in milliseconds) after which the watchdog should declare that 412 * our handler thread is wedged. The usual default for such things is one 413 * minute but we sometimes do very lengthy I/O operations on this thread, 414 * such as installing multi-gigabyte applications, so ours needs to be longer. 415 */ 416 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 417 418 /** 419 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 420 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 421 * settings entry if available, otherwise we use the hardcoded default. If it's been 422 * more than this long since the last fstrim, we force one during the boot sequence. 423 * 424 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 425 * one gets run at the next available charging+idle time. This final mandatory 426 * no-fstrim check kicks in only of the other scheduling criteria is never met. 427 */ 428 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 429 430 /** 431 * Whether verification is enabled by default. 432 */ 433 private static final boolean DEFAULT_VERIFY_ENABLE = true; 434 435 /** 436 * The default maximum time to wait for the verification agent to return in 437 * milliseconds. 438 */ 439 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 440 441 /** 442 * The default response for package verification timeout. 443 * 444 * This can be either PackageManager.VERIFICATION_ALLOW or 445 * PackageManager.VERIFICATION_REJECT. 446 */ 447 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 448 449 static final String PLATFORM_PACKAGE_NAME = "android"; 450 451 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 452 453 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 454 DEFAULT_CONTAINER_PACKAGE, 455 "com.android.defcontainer.DefaultContainerService"); 456 457 private static final String KILL_APP_REASON_GIDS_CHANGED = 458 "permission grant or revoke changed gids"; 459 460 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 461 "permissions revoked"; 462 463 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 464 465 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 466 467 private static int DEFAULT_EPHEMERAL_HASH_PREFIX_MASK = 0xFFFFF000; 468 private static int DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT = 5; 469 470 /** Permission grant: not grant the permission. */ 471 private static final int GRANT_DENIED = 1; 472 473 /** Permission grant: grant the permission as an install permission. */ 474 private static final int GRANT_INSTALL = 2; 475 476 /** Permission grant: grant the permission as a runtime one. */ 477 private static final int GRANT_RUNTIME = 3; 478 479 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 480 private static final int GRANT_UPGRADE = 4; 481 482 /** Canonical intent used to identify what counts as a "web browser" app */ 483 private static final Intent sBrowserIntent; 484 static { 485 sBrowserIntent = new Intent(); 486 sBrowserIntent.setAction(Intent.ACTION_VIEW); 487 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 488 sBrowserIntent.setData(Uri.parse("http:")); 489 } 490 491 /** 492 * The set of all protected actions [i.e. those actions for which a high priority 493 * intent filter is disallowed]. 494 */ 495 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 496 static { 497 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 498 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 499 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 500 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 501 } 502 503 // Compilation reasons. 504 public static final int REASON_FIRST_BOOT = 0; 505 public static final int REASON_BOOT = 1; 506 public static final int REASON_INSTALL = 2; 507 public static final int REASON_BACKGROUND_DEXOPT = 3; 508 public static final int REASON_AB_OTA = 4; 509 public static final int REASON_NON_SYSTEM_LIBRARY = 5; 510 public static final int REASON_SHARED_APK = 6; 511 public static final int REASON_FORCED_DEXOPT = 7; 512 public static final int REASON_CORE_APP = 8; 513 514 public static final int REASON_LAST = REASON_CORE_APP; 515 516 /** Special library name that skips shared libraries check during compilation. */ 517 private static final String SKIP_SHARED_LIBRARY_CHECK = "&"; 518 519 final ServiceThread mHandlerThread; 520 521 final PackageHandler mHandler; 522 523 private final ProcessLoggingHandler mProcessLoggingHandler; 524 525 /** 526 * Messages for {@link #mHandler} that need to wait for system ready before 527 * being dispatched. 528 */ 529 private ArrayList<Message> mPostSystemReadyMessages; 530 531 final int mSdkVersion = Build.VERSION.SDK_INT; 532 533 final Context mContext; 534 final boolean mFactoryTest; 535 final boolean mOnlyCore; 536 final DisplayMetrics mMetrics; 537 final int mDefParseFlags; 538 final String[] mSeparateProcesses; 539 final boolean mIsUpgrade; 540 final boolean mIsPreNUpgrade; 541 542 /** The location for ASEC container files on internal storage. */ 543 final String mAsecInternalPath; 544 545 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 546 // LOCK HELD. Can be called with mInstallLock held. 547 @GuardedBy("mInstallLock") 548 final Installer mInstaller; 549 550 /** Directory where installed third-party apps stored */ 551 final File mAppInstallDir; 552 final File mEphemeralInstallDir; 553 554 /** 555 * Directory to which applications installed internally have their 556 * 32 bit native libraries copied. 557 */ 558 private File mAppLib32InstallDir; 559 560 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 561 // apps. 562 final File mDrmAppPrivateInstallDir; 563 564 // ---------------------------------------------------------------- 565 566 // Lock for state used when installing and doing other long running 567 // operations. Methods that must be called with this lock held have 568 // the suffix "LI". 569 final Object mInstallLock = new Object(); 570 571 // ---------------------------------------------------------------- 572 573 // Keys are String (package name), values are Package. This also serves 574 // as the lock for the global state. Methods that must be called with 575 // this lock held have the prefix "LP". 576 @GuardedBy("mPackages") 577 final ArrayMap<String, PackageParser.Package> mPackages = 578 new ArrayMap<String, PackageParser.Package>(); 579 580 final ArrayMap<String, Set<String>> mKnownCodebase = 581 new ArrayMap<String, Set<String>>(); 582 583 // Tracks available target package names -> overlay package paths. 584 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 585 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 586 587 /** 588 * Tracks new system packages [received in an OTA] that we expect to 589 * find updated user-installed versions. Keys are package name, values 590 * are package location. 591 */ 592 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 593 /** 594 * Tracks high priority intent filters for protected actions. During boot, certain 595 * filter actions are protected and should never be allowed to have a high priority 596 * intent filter for them. However, there is one, and only one exception -- the 597 * setup wizard. It must be able to define a high priority intent filter for these 598 * actions to ensure there are no escapes from the wizard. We need to delay processing 599 * of these during boot as we need to look at all of the system packages in order 600 * to know which component is the setup wizard. 601 */ 602 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 603 /** 604 * Whether or not processing protected filters should be deferred. 605 */ 606 private boolean mDeferProtectedFilters = true; 607 608 /** 609 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 610 */ 611 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 612 /** 613 * Whether or not system app permissions should be promoted from install to runtime. 614 */ 615 boolean mPromoteSystemApps; 616 617 @GuardedBy("mPackages") 618 final Settings mSettings; 619 620 /** 621 * Set of package names that are currently "frozen", which means active 622 * surgery is being done on the code/data for that package. The platform 623 * will refuse to launch frozen packages to avoid race conditions. 624 * 625 * @see PackageFreezer 626 */ 627 @GuardedBy("mPackages") 628 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 629 630 final ProtectedPackages mProtectedPackages; 631 632 boolean mFirstBoot; 633 634 // System configuration read by SystemConfig. 635 final int[] mGlobalGids; 636 final SparseArray<ArraySet<String>> mSystemPermissions; 637 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 638 639 // If mac_permissions.xml was found for seinfo labeling. 640 boolean mFoundPolicyFile; 641 642 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 643 644 public static final class SharedLibraryEntry { 645 public final String path; 646 public final String apk; 647 648 SharedLibraryEntry(String _path, String _apk) { 649 path = _path; 650 apk = _apk; 651 } 652 } 653 654 // Currently known shared libraries. 655 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 656 new ArrayMap<String, SharedLibraryEntry>(); 657 658 // All available activities, for your resolving pleasure. 659 final ActivityIntentResolver mActivities = 660 new ActivityIntentResolver(); 661 662 // All available receivers, for your resolving pleasure. 663 final ActivityIntentResolver mReceivers = 664 new ActivityIntentResolver(); 665 666 // All available services, for your resolving pleasure. 667 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 668 669 // All available providers, for your resolving pleasure. 670 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 671 672 // Mapping from provider base names (first directory in content URI codePath) 673 // to the provider information. 674 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 675 new ArrayMap<String, PackageParser.Provider>(); 676 677 // Mapping from instrumentation class names to info about them. 678 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 679 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 680 681 // Mapping from permission names to info about them. 682 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 683 new ArrayMap<String, PackageParser.PermissionGroup>(); 684 685 // Packages whose data we have transfered into another package, thus 686 // should no longer exist. 687 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 688 689 // Broadcast actions that are only available to the system. 690 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 691 692 /** List of packages waiting for verification. */ 693 final SparseArray<PackageVerificationState> mPendingVerification 694 = new SparseArray<PackageVerificationState>(); 695 696 /** Set of packages associated with each app op permission. */ 697 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 698 699 final PackageInstallerService mInstallerService; 700 701 private final PackageDexOptimizer mPackageDexOptimizer; 702 703 private AtomicInteger mNextMoveId = new AtomicInteger(); 704 private final MoveCallbacks mMoveCallbacks; 705 706 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 707 708 // Cache of users who need badging. 709 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 710 711 /** Token for keys in mPendingVerification. */ 712 private int mPendingVerificationToken = 0; 713 714 volatile boolean mSystemReady; 715 volatile boolean mSafeMode; 716 volatile boolean mHasSystemUidErrors; 717 718 ApplicationInfo mAndroidApplication; 719 final ActivityInfo mResolveActivity = new ActivityInfo(); 720 final ResolveInfo mResolveInfo = new ResolveInfo(); 721 ComponentName mResolveComponentName; 722 PackageParser.Package mPlatformPackage; 723 ComponentName mCustomResolverComponentName; 724 725 boolean mResolverReplaced = false; 726 727 private final @Nullable ComponentName mIntentFilterVerifierComponent; 728 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 729 730 private int mIntentFilterVerificationToken = 0; 731 732 /** Component that knows whether or not an ephemeral application exists */ 733 final ComponentName mEphemeralResolverComponent; 734 /** The service connection to the ephemeral resolver */ 735 final EphemeralResolverConnection mEphemeralResolverConnection; 736 737 /** Component used to install ephemeral applications */ 738 final ComponentName mEphemeralInstallerComponent; 739 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 740 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 741 742 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 743 = new SparseArray<IntentFilterVerificationState>(); 744 745 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 746 new DefaultPermissionGrantPolicy(this); 747 748 // List of packages names to keep cached, even if they are uninstalled for all users 749 private List<String> mKeepUninstalledPackages; 750 751 private UserManagerInternal mUserManagerInternal; 752 753 private static class IFVerificationParams { 754 PackageParser.Package pkg; 755 boolean replacing; 756 int userId; 757 int verifierUid; 758 759 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 760 int _userId, int _verifierUid) { 761 pkg = _pkg; 762 replacing = _replacing; 763 userId = _userId; 764 replacing = _replacing; 765 verifierUid = _verifierUid; 766 } 767 } 768 769 private interface IntentFilterVerifier<T extends IntentFilter> { 770 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 771 T filter, String packageName); 772 void startVerifications(int userId); 773 void receiveVerificationResponse(int verificationId); 774 } 775 776 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 777 private Context mContext; 778 private ComponentName mIntentFilterVerifierComponent; 779 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 780 781 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 782 mContext = context; 783 mIntentFilterVerifierComponent = verifierComponent; 784 } 785 786 private String getDefaultScheme() { 787 return IntentFilter.SCHEME_HTTPS; 788 } 789 790 @Override 791 public void startVerifications(int userId) { 792 // Launch verifications requests 793 int count = mCurrentIntentFilterVerifications.size(); 794 for (int n=0; n<count; n++) { 795 int verificationId = mCurrentIntentFilterVerifications.get(n); 796 final IntentFilterVerificationState ivs = 797 mIntentFilterVerificationStates.get(verificationId); 798 799 String packageName = ivs.getPackageName(); 800 801 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 802 final int filterCount = filters.size(); 803 ArraySet<String> domainsSet = new ArraySet<>(); 804 for (int m=0; m<filterCount; m++) { 805 PackageParser.ActivityIntentInfo filter = filters.get(m); 806 domainsSet.addAll(filter.getHostsList()); 807 } 808 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 809 synchronized (mPackages) { 810 if (mSettings.createIntentFilterVerificationIfNeededLPw( 811 packageName, domainsList) != null) { 812 scheduleWriteSettingsLocked(); 813 } 814 } 815 sendVerificationRequest(userId, verificationId, ivs); 816 } 817 mCurrentIntentFilterVerifications.clear(); 818 } 819 820 private void sendVerificationRequest(int userId, int verificationId, 821 IntentFilterVerificationState ivs) { 822 823 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 824 verificationIntent.putExtra( 825 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 826 verificationId); 827 verificationIntent.putExtra( 828 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 829 getDefaultScheme()); 830 verificationIntent.putExtra( 831 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 832 ivs.getHostsString()); 833 verificationIntent.putExtra( 834 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 835 ivs.getPackageName()); 836 verificationIntent.setComponent(mIntentFilterVerifierComponent); 837 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 838 839 UserHandle user = new UserHandle(userId); 840 mContext.sendBroadcastAsUser(verificationIntent, user); 841 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 842 "Sending IntentFilter verification broadcast"); 843 } 844 845 public void receiveVerificationResponse(int verificationId) { 846 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 847 848 final boolean verified = ivs.isVerified(); 849 850 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 851 final int count = filters.size(); 852 if (DEBUG_DOMAIN_VERIFICATION) { 853 Slog.i(TAG, "Received verification response " + verificationId 854 + " for " + count + " filters, verified=" + verified); 855 } 856 for (int n=0; n<count; n++) { 857 PackageParser.ActivityIntentInfo filter = filters.get(n); 858 filter.setVerified(verified); 859 860 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 861 + " verified with result:" + verified + " and hosts:" 862 + ivs.getHostsString()); 863 } 864 865 mIntentFilterVerificationStates.remove(verificationId); 866 867 final String packageName = ivs.getPackageName(); 868 IntentFilterVerificationInfo ivi = null; 869 870 synchronized (mPackages) { 871 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 872 } 873 if (ivi == null) { 874 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 875 + verificationId + " packageName:" + packageName); 876 return; 877 } 878 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 879 "Updating IntentFilterVerificationInfo for package " + packageName 880 +" verificationId:" + verificationId); 881 882 synchronized (mPackages) { 883 if (verified) { 884 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 885 } else { 886 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 887 } 888 scheduleWriteSettingsLocked(); 889 890 final int userId = ivs.getUserId(); 891 if (userId != UserHandle.USER_ALL) { 892 final int userStatus = 893 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 894 895 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 896 boolean needUpdate = false; 897 898 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 899 // already been set by the User thru the Disambiguation dialog 900 switch (userStatus) { 901 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 902 if (verified) { 903 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 904 } else { 905 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 906 } 907 needUpdate = true; 908 break; 909 910 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 911 if (verified) { 912 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 913 needUpdate = true; 914 } 915 break; 916 917 default: 918 // Nothing to do 919 } 920 921 if (needUpdate) { 922 mSettings.updateIntentFilterVerificationStatusLPw( 923 packageName, updatedStatus, userId); 924 scheduleWritePackageRestrictionsLocked(userId); 925 } 926 } 927 } 928 } 929 930 @Override 931 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 932 ActivityIntentInfo filter, String packageName) { 933 if (!hasValidDomains(filter)) { 934 return false; 935 } 936 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 937 if (ivs == null) { 938 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 939 packageName); 940 } 941 if (DEBUG_DOMAIN_VERIFICATION) { 942 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 943 } 944 ivs.addFilter(filter); 945 return true; 946 } 947 948 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 949 int userId, int verificationId, String packageName) { 950 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 951 verifierUid, userId, packageName); 952 ivs.setPendingState(); 953 synchronized (mPackages) { 954 mIntentFilterVerificationStates.append(verificationId, ivs); 955 mCurrentIntentFilterVerifications.add(verificationId); 956 } 957 return ivs; 958 } 959 } 960 961 private static boolean hasValidDomains(ActivityIntentInfo filter) { 962 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 963 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 964 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 965 } 966 967 // Set of pending broadcasts for aggregating enable/disable of components. 968 static class PendingPackageBroadcasts { 969 // for each user id, a map of <package name -> components within that package> 970 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 971 972 public PendingPackageBroadcasts() { 973 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 974 } 975 976 public ArrayList<String> get(int userId, String packageName) { 977 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 978 return packages.get(packageName); 979 } 980 981 public void put(int userId, String packageName, ArrayList<String> components) { 982 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 983 packages.put(packageName, components); 984 } 985 986 public void remove(int userId, String packageName) { 987 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 988 if (packages != null) { 989 packages.remove(packageName); 990 } 991 } 992 993 public void remove(int userId) { 994 mUidMap.remove(userId); 995 } 996 997 public int userIdCount() { 998 return mUidMap.size(); 999 } 1000 1001 public int userIdAt(int n) { 1002 return mUidMap.keyAt(n); 1003 } 1004 1005 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 1006 return mUidMap.get(userId); 1007 } 1008 1009 public int size() { 1010 // total number of pending broadcast entries across all userIds 1011 int num = 0; 1012 for (int i = 0; i< mUidMap.size(); i++) { 1013 num += mUidMap.valueAt(i).size(); 1014 } 1015 return num; 1016 } 1017 1018 public void clear() { 1019 mUidMap.clear(); 1020 } 1021 1022 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1023 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1024 if (map == null) { 1025 map = new ArrayMap<String, ArrayList<String>>(); 1026 mUidMap.put(userId, map); 1027 } 1028 return map; 1029 } 1030 } 1031 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1032 1033 // Service Connection to remote media container service to copy 1034 // package uri's from external media onto secure containers 1035 // or internal storage. 1036 private IMediaContainerService mContainerService = null; 1037 1038 static final int SEND_PENDING_BROADCAST = 1; 1039 static final int MCS_BOUND = 3; 1040 static final int END_COPY = 4; 1041 static final int INIT_COPY = 5; 1042 static final int MCS_UNBIND = 6; 1043 static final int START_CLEANING_PACKAGE = 7; 1044 static final int FIND_INSTALL_LOC = 8; 1045 static final int POST_INSTALL = 9; 1046 static final int MCS_RECONNECT = 10; 1047 static final int MCS_GIVE_UP = 11; 1048 static final int UPDATED_MEDIA_STATUS = 12; 1049 static final int WRITE_SETTINGS = 13; 1050 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1051 static final int PACKAGE_VERIFIED = 15; 1052 static final int CHECK_PENDING_VERIFICATION = 16; 1053 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1054 static final int INTENT_FILTER_VERIFIED = 18; 1055 static final int WRITE_PACKAGE_LIST = 19; 1056 1057 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1058 1059 // Delay time in millisecs 1060 static final int BROADCAST_DELAY = 10 * 1000; 1061 1062 static UserManagerService sUserManager; 1063 1064 // Stores a list of users whose package restrictions file needs to be updated 1065 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1066 1067 final private DefaultContainerConnection mDefContainerConn = 1068 new DefaultContainerConnection(); 1069 class DefaultContainerConnection implements ServiceConnection { 1070 public void onServiceConnected(ComponentName name, IBinder service) { 1071 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1072 IMediaContainerService imcs = 1073 IMediaContainerService.Stub.asInterface(service); 1074 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1075 } 1076 1077 public void onServiceDisconnected(ComponentName name) { 1078 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1079 } 1080 } 1081 1082 // Recordkeeping of restore-after-install operations that are currently in flight 1083 // between the Package Manager and the Backup Manager 1084 static class PostInstallData { 1085 public InstallArgs args; 1086 public PackageInstalledInfo res; 1087 1088 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1089 args = _a; 1090 res = _r; 1091 } 1092 } 1093 1094 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1095 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1096 1097 // XML tags for backup/restore of various bits of state 1098 private static final String TAG_PREFERRED_BACKUP = "pa"; 1099 private static final String TAG_DEFAULT_APPS = "da"; 1100 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1101 1102 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1103 private static final String TAG_ALL_GRANTS = "rt-grants"; 1104 private static final String TAG_GRANT = "grant"; 1105 private static final String ATTR_PACKAGE_NAME = "pkg"; 1106 1107 private static final String TAG_PERMISSION = "perm"; 1108 private static final String ATTR_PERMISSION_NAME = "name"; 1109 private static final String ATTR_IS_GRANTED = "g"; 1110 private static final String ATTR_USER_SET = "set"; 1111 private static final String ATTR_USER_FIXED = "fixed"; 1112 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1113 1114 // System/policy permission grants are not backed up 1115 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1116 FLAG_PERMISSION_POLICY_FIXED 1117 | FLAG_PERMISSION_SYSTEM_FIXED 1118 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1119 1120 // And we back up these user-adjusted states 1121 private static final int USER_RUNTIME_GRANT_MASK = 1122 FLAG_PERMISSION_USER_SET 1123 | FLAG_PERMISSION_USER_FIXED 1124 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1125 1126 final @Nullable String mRequiredVerifierPackage; 1127 final @NonNull String mRequiredInstallerPackage; 1128 final @Nullable String mSetupWizardPackage; 1129 final @NonNull String mServicesSystemSharedLibraryPackageName; 1130 final @NonNull String mSharedSystemSharedLibraryPackageName; 1131 1132 private final PackageUsage mPackageUsage = new PackageUsage(); 1133 1134 private class PackageUsage { 1135 private static final int WRITE_INTERVAL 1136 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 1137 1138 private final Object mFileLock = new Object(); 1139 private final AtomicLong mLastWritten = new AtomicLong(0); 1140 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 1141 1142 private boolean mIsHistoricalPackageUsageAvailable = true; 1143 1144 boolean isHistoricalPackageUsageAvailable() { 1145 return mIsHistoricalPackageUsageAvailable; 1146 } 1147 1148 void write(boolean force) { 1149 if (force) { 1150 writeInternal(); 1151 return; 1152 } 1153 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 1154 && !DEBUG_DEXOPT) { 1155 return; 1156 } 1157 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 1158 new Thread("PackageUsage_DiskWriter") { 1159 @Override 1160 public void run() { 1161 try { 1162 writeInternal(); 1163 } finally { 1164 mBackgroundWriteRunning.set(false); 1165 } 1166 } 1167 }.start(); 1168 } 1169 } 1170 1171 private void writeInternal() { 1172 synchronized (mPackages) { 1173 synchronized (mFileLock) { 1174 AtomicFile file = getFile(); 1175 FileOutputStream f = null; 1176 try { 1177 f = file.startWrite(); 1178 BufferedOutputStream out = new BufferedOutputStream(f); 1179 FileUtils.setPermissions(file.getBaseFile().getPath(), 1180 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1181 StringBuilder sb = new StringBuilder(); 1182 1183 sb.append(USAGE_FILE_MAGIC_VERSION_1); 1184 sb.append('\n'); 1185 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1186 1187 for (PackageParser.Package pkg : mPackages.values()) { 1188 if (pkg.getLatestPackageUseTimeInMills() == 0L) { 1189 continue; 1190 } 1191 sb.setLength(0); 1192 sb.append(pkg.packageName); 1193 for (long usageTimeInMillis : pkg.mLastPackageUsageTimeInMills) { 1194 sb.append(' '); 1195 sb.append(usageTimeInMillis); 1196 } 1197 sb.append('\n'); 1198 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1199 } 1200 out.flush(); 1201 file.finishWrite(f); 1202 } catch (IOException e) { 1203 if (f != null) { 1204 file.failWrite(f); 1205 } 1206 Log.e(TAG, "Failed to write package usage times", e); 1207 } 1208 } 1209 } 1210 mLastWritten.set(SystemClock.elapsedRealtime()); 1211 } 1212 1213 void readLP() { 1214 synchronized (mFileLock) { 1215 AtomicFile file = getFile(); 1216 BufferedInputStream in = null; 1217 try { 1218 in = new BufferedInputStream(file.openRead()); 1219 StringBuffer sb = new StringBuffer(); 1220 1221 String firstLine = readLine(in, sb); 1222 if (firstLine == null) { 1223 // Empty file. Do nothing. 1224 } else if (USAGE_FILE_MAGIC_VERSION_1.equals(firstLine)) { 1225 readVersion1LP(in, sb); 1226 } else { 1227 readVersion0LP(in, sb, firstLine); 1228 } 1229 } catch (FileNotFoundException expected) { 1230 mIsHistoricalPackageUsageAvailable = false; 1231 } catch (IOException e) { 1232 Log.w(TAG, "Failed to read package usage times", e); 1233 } finally { 1234 IoUtils.closeQuietly(in); 1235 } 1236 } 1237 mLastWritten.set(SystemClock.elapsedRealtime()); 1238 } 1239 1240 private void readVersion0LP(InputStream in, StringBuffer sb, String firstLine) 1241 throws IOException { 1242 // Initial version of the file had no version number and stored one 1243 // package-timestamp pair per line. 1244 // Note that the first line has already been read from the InputStream. 1245 for (String line = firstLine; line != null; line = readLine(in, sb)) { 1246 String[] tokens = line.split(" "); 1247 if (tokens.length != 2) { 1248 throw new IOException("Failed to parse " + line + 1249 " as package-timestamp pair."); 1250 } 1251 1252 String packageName = tokens[0]; 1253 PackageParser.Package pkg = mPackages.get(packageName); 1254 if (pkg == null) { 1255 continue; 1256 } 1257 1258 long timestamp = parseAsLong(tokens[1]); 1259 for (int reason = 0; 1260 reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT; 1261 reason++) { 1262 pkg.mLastPackageUsageTimeInMills[reason] = timestamp; 1263 } 1264 } 1265 } 1266 1267 private void readVersion1LP(InputStream in, StringBuffer sb) throws IOException { 1268 // Version 1 of the file started with the corresponding version 1269 // number and then stored a package name and eight timestamps per line. 1270 String line; 1271 while ((line = readLine(in, sb)) != null) { 1272 String[] tokens = line.split(" "); 1273 if (tokens.length != PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT + 1) { 1274 throw new IOException("Failed to parse " + line + " as a timestamp array."); 1275 } 1276 1277 String packageName = tokens[0]; 1278 PackageParser.Package pkg = mPackages.get(packageName); 1279 if (pkg == null) { 1280 continue; 1281 } 1282 1283 for (int reason = 0; 1284 reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT; 1285 reason++) { 1286 pkg.mLastPackageUsageTimeInMills[reason] = parseAsLong(tokens[reason + 1]); 1287 } 1288 } 1289 } 1290 1291 private long parseAsLong(String token) throws IOException { 1292 try { 1293 return Long.parseLong(token); 1294 } catch (NumberFormatException e) { 1295 throw new IOException("Failed to parse " + token + " as a long.", e); 1296 } 1297 } 1298 1299 private String readLine(InputStream in, StringBuffer sb) throws IOException { 1300 return readToken(in, sb, '\n'); 1301 } 1302 1303 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1304 throws IOException { 1305 sb.setLength(0); 1306 while (true) { 1307 int ch = in.read(); 1308 if (ch == -1) { 1309 if (sb.length() == 0) { 1310 return null; 1311 } 1312 throw new IOException("Unexpected EOF"); 1313 } 1314 if (ch == endOfToken) { 1315 return sb.toString(); 1316 } 1317 sb.append((char)ch); 1318 } 1319 } 1320 1321 private AtomicFile getFile() { 1322 File dataDir = Environment.getDataDirectory(); 1323 File systemDir = new File(dataDir, "system"); 1324 File fname = new File(systemDir, "package-usage.list"); 1325 return new AtomicFile(fname); 1326 } 1327 1328 private static final String USAGE_FILE_MAGIC = "PACKAGE_USAGE__VERSION_"; 1329 private static final String USAGE_FILE_MAGIC_VERSION_1 = USAGE_FILE_MAGIC + "1"; 1330 } 1331 1332 class PackageHandler extends Handler { 1333 private boolean mBound = false; 1334 final ArrayList<HandlerParams> mPendingInstalls = 1335 new ArrayList<HandlerParams>(); 1336 1337 private boolean connectToService() { 1338 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1339 " DefaultContainerService"); 1340 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1341 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1342 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1343 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1344 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1345 mBound = true; 1346 return true; 1347 } 1348 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1349 return false; 1350 } 1351 1352 private void disconnectService() { 1353 mContainerService = null; 1354 mBound = false; 1355 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1356 mContext.unbindService(mDefContainerConn); 1357 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1358 } 1359 1360 PackageHandler(Looper looper) { 1361 super(looper); 1362 } 1363 1364 public void handleMessage(Message msg) { 1365 try { 1366 doHandleMessage(msg); 1367 } finally { 1368 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1369 } 1370 } 1371 1372 void doHandleMessage(Message msg) { 1373 switch (msg.what) { 1374 case INIT_COPY: { 1375 HandlerParams params = (HandlerParams) msg.obj; 1376 int idx = mPendingInstalls.size(); 1377 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1378 // If a bind was already initiated we dont really 1379 // need to do anything. The pending install 1380 // will be processed later on. 1381 if (!mBound) { 1382 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1383 System.identityHashCode(mHandler)); 1384 // If this is the only one pending we might 1385 // have to bind to the service again. 1386 if (!connectToService()) { 1387 Slog.e(TAG, "Failed to bind to media container service"); 1388 params.serviceError(); 1389 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1390 System.identityHashCode(mHandler)); 1391 if (params.traceMethod != null) { 1392 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1393 params.traceCookie); 1394 } 1395 return; 1396 } else { 1397 // Once we bind to the service, the first 1398 // pending request will be processed. 1399 mPendingInstalls.add(idx, params); 1400 } 1401 } else { 1402 mPendingInstalls.add(idx, params); 1403 // Already bound to the service. Just make 1404 // sure we trigger off processing the first request. 1405 if (idx == 0) { 1406 mHandler.sendEmptyMessage(MCS_BOUND); 1407 } 1408 } 1409 break; 1410 } 1411 case MCS_BOUND: { 1412 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1413 if (msg.obj != null) { 1414 mContainerService = (IMediaContainerService) msg.obj; 1415 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1416 System.identityHashCode(mHandler)); 1417 } 1418 if (mContainerService == null) { 1419 if (!mBound) { 1420 // Something seriously wrong since we are not bound and we are not 1421 // waiting for connection. Bail out. 1422 Slog.e(TAG, "Cannot bind to media container service"); 1423 for (HandlerParams params : mPendingInstalls) { 1424 // Indicate service bind error 1425 params.serviceError(); 1426 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1427 System.identityHashCode(params)); 1428 if (params.traceMethod != null) { 1429 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1430 params.traceMethod, params.traceCookie); 1431 } 1432 return; 1433 } 1434 mPendingInstalls.clear(); 1435 } else { 1436 Slog.w(TAG, "Waiting to connect to media container service"); 1437 } 1438 } else if (mPendingInstalls.size() > 0) { 1439 HandlerParams params = mPendingInstalls.get(0); 1440 if (params != null) { 1441 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1442 System.identityHashCode(params)); 1443 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1444 if (params.startCopy()) { 1445 // We are done... look for more work or to 1446 // go idle. 1447 if (DEBUG_SD_INSTALL) Log.i(TAG, 1448 "Checking for more work or unbind..."); 1449 // Delete pending install 1450 if (mPendingInstalls.size() > 0) { 1451 mPendingInstalls.remove(0); 1452 } 1453 if (mPendingInstalls.size() == 0) { 1454 if (mBound) { 1455 if (DEBUG_SD_INSTALL) Log.i(TAG, 1456 "Posting delayed MCS_UNBIND"); 1457 removeMessages(MCS_UNBIND); 1458 Message ubmsg = obtainMessage(MCS_UNBIND); 1459 // Unbind after a little delay, to avoid 1460 // continual thrashing. 1461 sendMessageDelayed(ubmsg, 10000); 1462 } 1463 } else { 1464 // There are more pending requests in queue. 1465 // Just post MCS_BOUND message to trigger processing 1466 // of next pending install. 1467 if (DEBUG_SD_INSTALL) Log.i(TAG, 1468 "Posting MCS_BOUND for next work"); 1469 mHandler.sendEmptyMessage(MCS_BOUND); 1470 } 1471 } 1472 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1473 } 1474 } else { 1475 // Should never happen ideally. 1476 Slog.w(TAG, "Empty queue"); 1477 } 1478 break; 1479 } 1480 case MCS_RECONNECT: { 1481 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1482 if (mPendingInstalls.size() > 0) { 1483 if (mBound) { 1484 disconnectService(); 1485 } 1486 if (!connectToService()) { 1487 Slog.e(TAG, "Failed to bind to media container service"); 1488 for (HandlerParams params : mPendingInstalls) { 1489 // Indicate service bind error 1490 params.serviceError(); 1491 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1492 System.identityHashCode(params)); 1493 } 1494 mPendingInstalls.clear(); 1495 } 1496 } 1497 break; 1498 } 1499 case MCS_UNBIND: { 1500 // If there is no actual work left, then time to unbind. 1501 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1502 1503 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1504 if (mBound) { 1505 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1506 1507 disconnectService(); 1508 } 1509 } else if (mPendingInstalls.size() > 0) { 1510 // There are more pending requests in queue. 1511 // Just post MCS_BOUND message to trigger processing 1512 // of next pending install. 1513 mHandler.sendEmptyMessage(MCS_BOUND); 1514 } 1515 1516 break; 1517 } 1518 case MCS_GIVE_UP: { 1519 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1520 HandlerParams params = mPendingInstalls.remove(0); 1521 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1522 System.identityHashCode(params)); 1523 break; 1524 } 1525 case SEND_PENDING_BROADCAST: { 1526 String packages[]; 1527 ArrayList<String> components[]; 1528 int size = 0; 1529 int uids[]; 1530 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1531 synchronized (mPackages) { 1532 if (mPendingBroadcasts == null) { 1533 return; 1534 } 1535 size = mPendingBroadcasts.size(); 1536 if (size <= 0) { 1537 // Nothing to be done. Just return 1538 return; 1539 } 1540 packages = new String[size]; 1541 components = new ArrayList[size]; 1542 uids = new int[size]; 1543 int i = 0; // filling out the above arrays 1544 1545 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1546 int packageUserId = mPendingBroadcasts.userIdAt(n); 1547 Iterator<Map.Entry<String, ArrayList<String>>> it 1548 = mPendingBroadcasts.packagesForUserId(packageUserId) 1549 .entrySet().iterator(); 1550 while (it.hasNext() && i < size) { 1551 Map.Entry<String, ArrayList<String>> ent = it.next(); 1552 packages[i] = ent.getKey(); 1553 components[i] = ent.getValue(); 1554 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1555 uids[i] = (ps != null) 1556 ? UserHandle.getUid(packageUserId, ps.appId) 1557 : -1; 1558 i++; 1559 } 1560 } 1561 size = i; 1562 mPendingBroadcasts.clear(); 1563 } 1564 // Send broadcasts 1565 for (int i = 0; i < size; i++) { 1566 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1567 } 1568 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1569 break; 1570 } 1571 case START_CLEANING_PACKAGE: { 1572 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1573 final String packageName = (String)msg.obj; 1574 final int userId = msg.arg1; 1575 final boolean andCode = msg.arg2 != 0; 1576 synchronized (mPackages) { 1577 if (userId == UserHandle.USER_ALL) { 1578 int[] users = sUserManager.getUserIds(); 1579 for (int user : users) { 1580 mSettings.addPackageToCleanLPw( 1581 new PackageCleanItem(user, packageName, andCode)); 1582 } 1583 } else { 1584 mSettings.addPackageToCleanLPw( 1585 new PackageCleanItem(userId, packageName, andCode)); 1586 } 1587 } 1588 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1589 startCleaningPackages(); 1590 } break; 1591 case POST_INSTALL: { 1592 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1593 1594 PostInstallData data = mRunningInstalls.get(msg.arg1); 1595 final boolean didRestore = (msg.arg2 != 0); 1596 mRunningInstalls.delete(msg.arg1); 1597 1598 if (data != null) { 1599 InstallArgs args = data.args; 1600 PackageInstalledInfo parentRes = data.res; 1601 1602 final boolean grantPermissions = (args.installFlags 1603 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1604 final boolean killApp = (args.installFlags 1605 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1606 final String[] grantedPermissions = args.installGrantPermissions; 1607 1608 // Handle the parent package 1609 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1610 grantedPermissions, didRestore, args.installerPackageName, 1611 args.observer); 1612 1613 // Handle the child packages 1614 final int childCount = (parentRes.addedChildPackages != null) 1615 ? parentRes.addedChildPackages.size() : 0; 1616 for (int i = 0; i < childCount; i++) { 1617 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1618 handlePackagePostInstall(childRes, grantPermissions, killApp, 1619 grantedPermissions, false, args.installerPackageName, 1620 args.observer); 1621 } 1622 1623 // Log tracing if needed 1624 if (args.traceMethod != null) { 1625 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1626 args.traceCookie); 1627 } 1628 } else { 1629 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1630 } 1631 1632 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1633 } break; 1634 case UPDATED_MEDIA_STATUS: { 1635 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1636 boolean reportStatus = msg.arg1 == 1; 1637 boolean doGc = msg.arg2 == 1; 1638 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1639 if (doGc) { 1640 // Force a gc to clear up stale containers. 1641 Runtime.getRuntime().gc(); 1642 } 1643 if (msg.obj != null) { 1644 @SuppressWarnings("unchecked") 1645 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1646 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1647 // Unload containers 1648 unloadAllContainers(args); 1649 } 1650 if (reportStatus) { 1651 try { 1652 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1653 PackageHelper.getMountService().finishMediaUpdate(); 1654 } catch (RemoteException e) { 1655 Log.e(TAG, "MountService not running?"); 1656 } 1657 } 1658 } break; 1659 case WRITE_SETTINGS: { 1660 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1661 synchronized (mPackages) { 1662 removeMessages(WRITE_SETTINGS); 1663 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1664 mSettings.writeLPr(); 1665 mDirtyUsers.clear(); 1666 } 1667 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1668 } break; 1669 case WRITE_PACKAGE_RESTRICTIONS: { 1670 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1671 synchronized (mPackages) { 1672 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1673 for (int userId : mDirtyUsers) { 1674 mSettings.writePackageRestrictionsLPr(userId); 1675 } 1676 mDirtyUsers.clear(); 1677 } 1678 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1679 } break; 1680 case WRITE_PACKAGE_LIST: { 1681 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1682 synchronized (mPackages) { 1683 removeMessages(WRITE_PACKAGE_LIST); 1684 mSettings.writePackageListLPr(msg.arg1); 1685 } 1686 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1687 } break; 1688 case CHECK_PENDING_VERIFICATION: { 1689 final int verificationId = msg.arg1; 1690 final PackageVerificationState state = mPendingVerification.get(verificationId); 1691 1692 if ((state != null) && !state.timeoutExtended()) { 1693 final InstallArgs args = state.getInstallArgs(); 1694 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1695 1696 Slog.i(TAG, "Verification timed out for " + originUri); 1697 mPendingVerification.remove(verificationId); 1698 1699 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1700 1701 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1702 Slog.i(TAG, "Continuing with installation of " + originUri); 1703 state.setVerifierResponse(Binder.getCallingUid(), 1704 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1705 broadcastPackageVerified(verificationId, originUri, 1706 PackageManager.VERIFICATION_ALLOW, 1707 state.getInstallArgs().getUser()); 1708 try { 1709 ret = args.copyApk(mContainerService, true); 1710 } catch (RemoteException e) { 1711 Slog.e(TAG, "Could not contact the ContainerService"); 1712 } 1713 } else { 1714 broadcastPackageVerified(verificationId, originUri, 1715 PackageManager.VERIFICATION_REJECT, 1716 state.getInstallArgs().getUser()); 1717 } 1718 1719 Trace.asyncTraceEnd( 1720 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1721 1722 processPendingInstall(args, ret); 1723 mHandler.sendEmptyMessage(MCS_UNBIND); 1724 } 1725 break; 1726 } 1727 case PACKAGE_VERIFIED: { 1728 final int verificationId = msg.arg1; 1729 1730 final PackageVerificationState state = mPendingVerification.get(verificationId); 1731 if (state == null) { 1732 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1733 break; 1734 } 1735 1736 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1737 1738 state.setVerifierResponse(response.callerUid, response.code); 1739 1740 if (state.isVerificationComplete()) { 1741 mPendingVerification.remove(verificationId); 1742 1743 final InstallArgs args = state.getInstallArgs(); 1744 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1745 1746 int ret; 1747 if (state.isInstallAllowed()) { 1748 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1749 broadcastPackageVerified(verificationId, originUri, 1750 response.code, state.getInstallArgs().getUser()); 1751 try { 1752 ret = args.copyApk(mContainerService, true); 1753 } catch (RemoteException e) { 1754 Slog.e(TAG, "Could not contact the ContainerService"); 1755 } 1756 } else { 1757 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1758 } 1759 1760 Trace.asyncTraceEnd( 1761 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1762 1763 processPendingInstall(args, ret); 1764 mHandler.sendEmptyMessage(MCS_UNBIND); 1765 } 1766 1767 break; 1768 } 1769 case START_INTENT_FILTER_VERIFICATIONS: { 1770 IFVerificationParams params = (IFVerificationParams) msg.obj; 1771 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1772 params.replacing, params.pkg); 1773 break; 1774 } 1775 case INTENT_FILTER_VERIFIED: { 1776 final int verificationId = msg.arg1; 1777 1778 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1779 verificationId); 1780 if (state == null) { 1781 Slog.w(TAG, "Invalid IntentFilter verification token " 1782 + verificationId + " received"); 1783 break; 1784 } 1785 1786 final int userId = state.getUserId(); 1787 1788 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1789 "Processing IntentFilter verification with token:" 1790 + verificationId + " and userId:" + userId); 1791 1792 final IntentFilterVerificationResponse response = 1793 (IntentFilterVerificationResponse) msg.obj; 1794 1795 state.setVerifierResponse(response.callerUid, response.code); 1796 1797 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1798 "IntentFilter verification with token:" + verificationId 1799 + " and userId:" + userId 1800 + " is settings verifier response with response code:" 1801 + response.code); 1802 1803 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1804 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1805 + response.getFailedDomainsString()); 1806 } 1807 1808 if (state.isVerificationComplete()) { 1809 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1810 } else { 1811 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1812 "IntentFilter verification with token:" + verificationId 1813 + " was not said to be complete"); 1814 } 1815 1816 break; 1817 } 1818 } 1819 } 1820 } 1821 1822 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1823 boolean killApp, String[] grantedPermissions, 1824 boolean launchedForRestore, String installerPackage, 1825 IPackageInstallObserver2 installObserver) { 1826 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1827 // Send the removed broadcasts 1828 if (res.removedInfo != null) { 1829 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1830 } 1831 1832 // Now that we successfully installed the package, grant runtime 1833 // permissions if requested before broadcasting the install. 1834 if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion 1835 >= Build.VERSION_CODES.M) { 1836 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1837 } 1838 1839 final boolean update = res.removedInfo != null 1840 && res.removedInfo.removedPackage != null; 1841 1842 // If this is the first time we have child packages for a disabled privileged 1843 // app that had no children, we grant requested runtime permissions to the new 1844 // children if the parent on the system image had them already granted. 1845 if (res.pkg.parentPackage != null) { 1846 synchronized (mPackages) { 1847 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1848 } 1849 } 1850 1851 synchronized (mPackages) { 1852 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1853 } 1854 1855 final String packageName = res.pkg.applicationInfo.packageName; 1856 Bundle extras = new Bundle(1); 1857 extras.putInt(Intent.EXTRA_UID, res.uid); 1858 1859 // Determine the set of users who are adding this package for 1860 // the first time vs. those who are seeing an update. 1861 int[] firstUsers = EMPTY_INT_ARRAY; 1862 int[] updateUsers = EMPTY_INT_ARRAY; 1863 if (res.origUsers == null || res.origUsers.length == 0) { 1864 firstUsers = res.newUsers; 1865 } else { 1866 for (int newUser : res.newUsers) { 1867 boolean isNew = true; 1868 for (int origUser : res.origUsers) { 1869 if (origUser == newUser) { 1870 isNew = false; 1871 break; 1872 } 1873 } 1874 if (isNew) { 1875 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1876 } else { 1877 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1878 } 1879 } 1880 } 1881 1882 // Send installed broadcasts if the install/update is not ephemeral 1883 if (!isEphemeral(res.pkg)) { 1884 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1885 1886 // Send added for users that see the package for the first time 1887 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1888 extras, 0 /*flags*/, null /*targetPackage*/, 1889 null /*finishedReceiver*/, firstUsers); 1890 1891 // Send added for users that don't see the package for the first time 1892 if (update) { 1893 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1894 } 1895 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1896 extras, 0 /*flags*/, null /*targetPackage*/, 1897 null /*finishedReceiver*/, updateUsers); 1898 1899 // Send replaced for users that don't see the package for the first time 1900 if (update) { 1901 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1902 packageName, extras, 0 /*flags*/, 1903 null /*targetPackage*/, null /*finishedReceiver*/, 1904 updateUsers); 1905 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1906 null /*package*/, null /*extras*/, 0 /*flags*/, 1907 packageName /*targetPackage*/, 1908 null /*finishedReceiver*/, updateUsers); 1909 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 1910 // First-install and we did a restore, so we're responsible for the 1911 // first-launch broadcast. 1912 if (DEBUG_BACKUP) { 1913 Slog.i(TAG, "Post-restore of " + packageName 1914 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers)); 1915 } 1916 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers); 1917 } 1918 1919 // Send broadcast package appeared if forward locked/external for all users 1920 // treat asec-hosted packages like removable media on upgrade 1921 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1922 if (DEBUG_INSTALL) { 1923 Slog.i(TAG, "upgrading pkg " + res.pkg 1924 + " is ASEC-hosted -> AVAILABLE"); 1925 } 1926 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1927 ArrayList<String> pkgList = new ArrayList<>(1); 1928 pkgList.add(packageName); 1929 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1930 } 1931 } 1932 1933 // Work that needs to happen on first install within each user 1934 if (firstUsers != null && firstUsers.length > 0) { 1935 synchronized (mPackages) { 1936 for (int userId : firstUsers) { 1937 // If this app is a browser and it's newly-installed for some 1938 // users, clear any default-browser state in those users. The 1939 // app's nature doesn't depend on the user, so we can just check 1940 // its browser nature in any user and generalize. 1941 if (packageIsBrowser(packageName, userId)) { 1942 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1943 } 1944 1945 // We may also need to apply pending (restored) runtime 1946 // permission grants within these users. 1947 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1948 } 1949 } 1950 } 1951 1952 // Log current value of "unknown sources" setting 1953 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1954 getUnknownSourcesSettings()); 1955 1956 // Force a gc to clear up things 1957 Runtime.getRuntime().gc(); 1958 1959 // Remove the replaced package's older resources safely now 1960 // We delete after a gc for applications on sdcard. 1961 if (res.removedInfo != null && res.removedInfo.args != null) { 1962 synchronized (mInstallLock) { 1963 res.removedInfo.args.doPostDeleteLI(true); 1964 } 1965 } 1966 } 1967 1968 // If someone is watching installs - notify them 1969 if (installObserver != null) { 1970 try { 1971 Bundle extras = extrasForInstallResult(res); 1972 installObserver.onPackageInstalled(res.name, res.returnCode, 1973 res.returnMsg, extras); 1974 } catch (RemoteException e) { 1975 Slog.i(TAG, "Observer no longer exists."); 1976 } 1977 } 1978 } 1979 1980 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1981 PackageParser.Package pkg) { 1982 if (pkg.parentPackage == null) { 1983 return; 1984 } 1985 if (pkg.requestedPermissions == null) { 1986 return; 1987 } 1988 final PackageSetting disabledSysParentPs = mSettings 1989 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1990 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1991 || !disabledSysParentPs.isPrivileged() 1992 || (disabledSysParentPs.childPackageNames != null 1993 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1994 return; 1995 } 1996 final int[] allUserIds = sUserManager.getUserIds(); 1997 final int permCount = pkg.requestedPermissions.size(); 1998 for (int i = 0; i < permCount; i++) { 1999 String permission = pkg.requestedPermissions.get(i); 2000 BasePermission bp = mSettings.mPermissions.get(permission); 2001 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 2002 continue; 2003 } 2004 for (int userId : allUserIds) { 2005 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 2006 permission, userId)) { 2007 grantRuntimePermission(pkg.packageName, permission, userId); 2008 } 2009 } 2010 } 2011 } 2012 2013 private StorageEventListener mStorageListener = new StorageEventListener() { 2014 @Override 2015 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 2016 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 2017 if (vol.state == VolumeInfo.STATE_MOUNTED) { 2018 final String volumeUuid = vol.getFsUuid(); 2019 2020 // Clean up any users or apps that were removed or recreated 2021 // while this volume was missing 2022 reconcileUsers(volumeUuid); 2023 reconcileApps(volumeUuid); 2024 2025 // Clean up any install sessions that expired or were 2026 // cancelled while this volume was missing 2027 mInstallerService.onPrivateVolumeMounted(volumeUuid); 2028 2029 loadPrivatePackages(vol); 2030 2031 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2032 unloadPrivatePackages(vol); 2033 } 2034 } 2035 2036 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 2037 if (vol.state == VolumeInfo.STATE_MOUNTED) { 2038 updateExternalMediaStatus(true, false); 2039 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2040 updateExternalMediaStatus(false, false); 2041 } 2042 } 2043 } 2044 2045 @Override 2046 public void onVolumeForgotten(String fsUuid) { 2047 if (TextUtils.isEmpty(fsUuid)) { 2048 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 2049 return; 2050 } 2051 2052 // Remove any apps installed on the forgotten volume 2053 synchronized (mPackages) { 2054 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 2055 for (PackageSetting ps : packages) { 2056 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 2057 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 2058 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 2059 } 2060 2061 mSettings.onVolumeForgotten(fsUuid); 2062 mSettings.writeLPr(); 2063 } 2064 } 2065 }; 2066 2067 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 2068 String[] grantedPermissions) { 2069 for (int userId : userIds) { 2070 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 2071 } 2072 2073 // We could have touched GID membership, so flush out packages.list 2074 synchronized (mPackages) { 2075 mSettings.writePackageListLPr(); 2076 } 2077 } 2078 2079 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 2080 String[] grantedPermissions) { 2081 SettingBase sb = (SettingBase) pkg.mExtras; 2082 if (sb == null) { 2083 return; 2084 } 2085 2086 PermissionsState permissionsState = sb.getPermissionsState(); 2087 2088 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 2089 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 2090 2091 for (String permission : pkg.requestedPermissions) { 2092 final BasePermission bp; 2093 synchronized (mPackages) { 2094 bp = mSettings.mPermissions.get(permission); 2095 } 2096 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 2097 && (grantedPermissions == null 2098 || ArrayUtils.contains(grantedPermissions, permission))) { 2099 final int flags = permissionsState.getPermissionFlags(permission, userId); 2100 // Installer cannot change immutable permissions. 2101 if ((flags & immutableFlags) == 0) { 2102 grantRuntimePermission(pkg.packageName, permission, userId); 2103 } 2104 } 2105 } 2106 } 2107 2108 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2109 Bundle extras = null; 2110 switch (res.returnCode) { 2111 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2112 extras = new Bundle(); 2113 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2114 res.origPermission); 2115 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2116 res.origPackage); 2117 break; 2118 } 2119 case PackageManager.INSTALL_SUCCEEDED: { 2120 extras = new Bundle(); 2121 extras.putBoolean(Intent.EXTRA_REPLACING, 2122 res.removedInfo != null && res.removedInfo.removedPackage != null); 2123 break; 2124 } 2125 } 2126 return extras; 2127 } 2128 2129 void scheduleWriteSettingsLocked() { 2130 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2131 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2132 } 2133 } 2134 2135 void scheduleWritePackageListLocked(int userId) { 2136 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 2137 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST); 2138 msg.arg1 = userId; 2139 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY); 2140 } 2141 } 2142 2143 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2144 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2145 scheduleWritePackageRestrictionsLocked(userId); 2146 } 2147 2148 void scheduleWritePackageRestrictionsLocked(int userId) { 2149 final int[] userIds = (userId == UserHandle.USER_ALL) 2150 ? sUserManager.getUserIds() : new int[]{userId}; 2151 for (int nextUserId : userIds) { 2152 if (!sUserManager.exists(nextUserId)) return; 2153 mDirtyUsers.add(nextUserId); 2154 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2155 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2156 } 2157 } 2158 } 2159 2160 public static PackageManagerService main(Context context, Installer installer, 2161 boolean factoryTest, boolean onlyCore) { 2162 // Self-check for initial settings. 2163 PackageManagerServiceCompilerMapping.checkProperties(); 2164 2165 PackageManagerService m = new PackageManagerService(context, installer, 2166 factoryTest, onlyCore); 2167 m.enableSystemUserPackages(); 2168 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 2169 // disabled after already being started. 2170 CarrierAppUtils.disableCarrierAppsUntilPrivileged(context.getOpPackageName(), m, 2171 UserHandle.USER_SYSTEM); 2172 ServiceManager.addService("package", m); 2173 return m; 2174 } 2175 2176 private void enableSystemUserPackages() { 2177 if (!UserManager.isSplitSystemUser()) { 2178 return; 2179 } 2180 // For system user, enable apps based on the following conditions: 2181 // - app is whitelisted or belong to one of these groups: 2182 // -- system app which has no launcher icons 2183 // -- system app which has INTERACT_ACROSS_USERS permission 2184 // -- system IME app 2185 // - app is not in the blacklist 2186 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2187 Set<String> enableApps = new ArraySet<>(); 2188 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2189 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2190 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2191 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2192 enableApps.addAll(wlApps); 2193 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2194 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2195 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2196 enableApps.removeAll(blApps); 2197 Log.i(TAG, "Applications installed for system user: " + enableApps); 2198 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2199 UserHandle.SYSTEM); 2200 final int allAppsSize = allAps.size(); 2201 synchronized (mPackages) { 2202 for (int i = 0; i < allAppsSize; i++) { 2203 String pName = allAps.get(i); 2204 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2205 // Should not happen, but we shouldn't be failing if it does 2206 if (pkgSetting == null) { 2207 continue; 2208 } 2209 boolean install = enableApps.contains(pName); 2210 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2211 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2212 + " for system user"); 2213 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2214 } 2215 } 2216 } 2217 } 2218 2219 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2220 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2221 Context.DISPLAY_SERVICE); 2222 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2223 } 2224 2225 /** 2226 * Requests that files preopted on a secondary system partition be copied to the data partition 2227 * if possible. Note that the actual copying of the files is accomplished by init for security 2228 * reasons. This simply requests that the copy takes place and awaits confirmation of its 2229 * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy. 2230 */ 2231 private static void requestCopyPreoptedFiles() { 2232 final int WAIT_TIME_MS = 100; 2233 final String CP_PREOPT_PROPERTY = "sys.cppreopt"; 2234 if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) { 2235 SystemProperties.set(CP_PREOPT_PROPERTY, "requested"); 2236 // We will wait for up to 100 seconds. 2237 final long timeEnd = SystemClock.uptimeMillis() + 100 * 1000; 2238 while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) { 2239 try { 2240 Thread.sleep(WAIT_TIME_MS); 2241 } catch (InterruptedException e) { 2242 // Do nothing 2243 } 2244 if (SystemClock.uptimeMillis() > timeEnd) { 2245 SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out"); 2246 Slog.wtf(TAG, "cppreopt did not finish!"); 2247 break; 2248 } 2249 } 2250 } 2251 } 2252 2253 public PackageManagerService(Context context, Installer installer, 2254 boolean factoryTest, boolean onlyCore) { 2255 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2256 SystemClock.uptimeMillis()); 2257 2258 if (mSdkVersion <= 0) { 2259 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2260 } 2261 2262 mContext = context; 2263 mFactoryTest = factoryTest; 2264 mOnlyCore = onlyCore; 2265 mMetrics = new DisplayMetrics(); 2266 mSettings = new Settings(mPackages); 2267 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2268 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2269 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2270 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2271 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2272 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2273 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2274 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2275 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2276 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2277 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2278 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2279 2280 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2281 if (separateProcesses != null && separateProcesses.length() > 0) { 2282 if ("*".equals(separateProcesses)) { 2283 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2284 mSeparateProcesses = null; 2285 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2286 } else { 2287 mDefParseFlags = 0; 2288 mSeparateProcesses = separateProcesses.split(","); 2289 Slog.w(TAG, "Running with debug.separate_processes: " 2290 + separateProcesses); 2291 } 2292 } else { 2293 mDefParseFlags = 0; 2294 mSeparateProcesses = null; 2295 } 2296 2297 mInstaller = installer; 2298 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2299 "*dexopt*"); 2300 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2301 2302 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2303 FgThread.get().getLooper()); 2304 2305 getDefaultDisplayMetrics(context, mMetrics); 2306 2307 SystemConfig systemConfig = SystemConfig.getInstance(); 2308 mGlobalGids = systemConfig.getGlobalGids(); 2309 mSystemPermissions = systemConfig.getSystemPermissions(); 2310 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2311 2312 mProtectedPackages = new ProtectedPackages(mContext); 2313 2314 synchronized (mInstallLock) { 2315 // writer 2316 synchronized (mPackages) { 2317 mHandlerThread = new ServiceThread(TAG, 2318 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2319 mHandlerThread.start(); 2320 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2321 mProcessLoggingHandler = new ProcessLoggingHandler(); 2322 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2323 2324 File dataDir = Environment.getDataDirectory(); 2325 mAppInstallDir = new File(dataDir, "app"); 2326 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2327 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2328 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2329 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2330 2331 sUserManager = new UserManagerService(context, this, mPackages); 2332 2333 // Propagate permission configuration in to package manager. 2334 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2335 = systemConfig.getPermissions(); 2336 for (int i=0; i<permConfig.size(); i++) { 2337 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2338 BasePermission bp = mSettings.mPermissions.get(perm.name); 2339 if (bp == null) { 2340 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2341 mSettings.mPermissions.put(perm.name, bp); 2342 } 2343 if (perm.gids != null) { 2344 bp.setGids(perm.gids, perm.perUser); 2345 } 2346 } 2347 2348 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2349 for (int i=0; i<libConfig.size(); i++) { 2350 mSharedLibraries.put(libConfig.keyAt(i), 2351 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2352 } 2353 2354 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2355 2356 mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false)); 2357 2358 if (mFirstBoot) { 2359 requestCopyPreoptedFiles(); 2360 } 2361 2362 String customResolverActivity = Resources.getSystem().getString( 2363 R.string.config_customResolverActivity); 2364 if (TextUtils.isEmpty(customResolverActivity)) { 2365 customResolverActivity = null; 2366 } else { 2367 mCustomResolverComponentName = ComponentName.unflattenFromString( 2368 customResolverActivity); 2369 } 2370 2371 long startTime = SystemClock.uptimeMillis(); 2372 2373 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2374 startTime); 2375 2376 // Set flag to monitor and not change apk file paths when 2377 // scanning install directories. 2378 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2379 2380 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2381 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2382 2383 if (bootClassPath == null) { 2384 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2385 } 2386 2387 if (systemServerClassPath == null) { 2388 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2389 } 2390 2391 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2392 final String[] dexCodeInstructionSets = 2393 getDexCodeInstructionSets( 2394 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2395 2396 /** 2397 * Ensure all external libraries have had dexopt run on them. 2398 */ 2399 if (mSharedLibraries.size() > 0) { 2400 // NOTE: For now, we're compiling these system "shared libraries" 2401 // (and framework jars) into all available architectures. It's possible 2402 // to compile them only when we come across an app that uses them (there's 2403 // already logic for that in scanPackageLI) but that adds some complexity. 2404 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2405 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2406 final String lib = libEntry.path; 2407 if (lib == null) { 2408 continue; 2409 } 2410 2411 try { 2412 // Shared libraries do not have profiles so we perform a full 2413 // AOT compilation (if needed). 2414 int dexoptNeeded = DexFile.getDexOptNeeded( 2415 lib, dexCodeInstructionSet, 2416 getCompilerFilterForReason(REASON_SHARED_APK), 2417 false /* newProfile */); 2418 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2419 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2420 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/, 2421 getCompilerFilterForReason(REASON_SHARED_APK), 2422 StorageManager.UUID_PRIVATE_INTERNAL, 2423 SKIP_SHARED_LIBRARY_CHECK); 2424 } 2425 } catch (FileNotFoundException e) { 2426 Slog.w(TAG, "Library not found: " + lib); 2427 } catch (IOException | InstallerException e) { 2428 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2429 + e.getMessage()); 2430 } 2431 } 2432 } 2433 } 2434 2435 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2436 2437 final VersionInfo ver = mSettings.getInternalVersion(); 2438 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2439 2440 // when upgrading from pre-M, promote system app permissions from install to runtime 2441 mPromoteSystemApps = 2442 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2443 2444 // When upgrading from pre-N, we need to handle package extraction like first boot, 2445 // as there is no profiling data available. 2446 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N; 2447 2448 // save off the names of pre-existing system packages prior to scanning; we don't 2449 // want to automatically grant runtime permissions for new system apps 2450 if (mPromoteSystemApps) { 2451 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2452 while (pkgSettingIter.hasNext()) { 2453 PackageSetting ps = pkgSettingIter.next(); 2454 if (isSystemApp(ps)) { 2455 mExistingSystemPackages.add(ps.name); 2456 } 2457 } 2458 } 2459 2460 // Collect vendor overlay packages. 2461 // (Do this before scanning any apps.) 2462 // For security and version matching reason, only consider 2463 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2464 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2465 scanDirTracedLI(vendorOverlayDir, mDefParseFlags 2466 | PackageParser.PARSE_IS_SYSTEM 2467 | PackageParser.PARSE_IS_SYSTEM_DIR 2468 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2469 2470 // Find base frameworks (resource packages without code). 2471 scanDirTracedLI(frameworkDir, mDefParseFlags 2472 | PackageParser.PARSE_IS_SYSTEM 2473 | PackageParser.PARSE_IS_SYSTEM_DIR 2474 | PackageParser.PARSE_IS_PRIVILEGED, 2475 scanFlags | SCAN_NO_DEX, 0); 2476 2477 // Collected privileged system packages. 2478 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2479 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2480 | PackageParser.PARSE_IS_SYSTEM 2481 | PackageParser.PARSE_IS_SYSTEM_DIR 2482 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2483 2484 // Collect ordinary system packages. 2485 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2486 scanDirTracedLI(systemAppDir, mDefParseFlags 2487 | PackageParser.PARSE_IS_SYSTEM 2488 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2489 2490 // Collect all vendor packages. 2491 File vendorAppDir = new File("/vendor/app"); 2492 try { 2493 vendorAppDir = vendorAppDir.getCanonicalFile(); 2494 } catch (IOException e) { 2495 // failed to look up canonical path, continue with original one 2496 } 2497 scanDirTracedLI(vendorAppDir, mDefParseFlags 2498 | PackageParser.PARSE_IS_SYSTEM 2499 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2500 2501 // Collect all OEM packages. 2502 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2503 scanDirTracedLI(oemAppDir, mDefParseFlags 2504 | PackageParser.PARSE_IS_SYSTEM 2505 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2506 2507 // Prune any system packages that no longer exist. 2508 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2509 if (!mOnlyCore) { 2510 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2511 while (psit.hasNext()) { 2512 PackageSetting ps = psit.next(); 2513 2514 /* 2515 * If this is not a system app, it can't be a 2516 * disable system app. 2517 */ 2518 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2519 continue; 2520 } 2521 2522 /* 2523 * If the package is scanned, it's not erased. 2524 */ 2525 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2526 if (scannedPkg != null) { 2527 /* 2528 * If the system app is both scanned and in the 2529 * disabled packages list, then it must have been 2530 * added via OTA. Remove it from the currently 2531 * scanned package so the previously user-installed 2532 * application can be scanned. 2533 */ 2534 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2535 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2536 + ps.name + "; removing system app. Last known codePath=" 2537 + ps.codePathString + ", installStatus=" + ps.installStatus 2538 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2539 + scannedPkg.mVersionCode); 2540 removePackageLI(scannedPkg, true); 2541 mExpectingBetter.put(ps.name, ps.codePath); 2542 } 2543 2544 continue; 2545 } 2546 2547 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2548 psit.remove(); 2549 logCriticalInfo(Log.WARN, "System package " + ps.name 2550 + " no longer exists; it's data will be wiped"); 2551 // Actual deletion of code and data will be handled by later 2552 // reconciliation step 2553 } else { 2554 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2555 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2556 possiblyDeletedUpdatedSystemApps.add(ps.name); 2557 } 2558 } 2559 } 2560 } 2561 2562 //look for any incomplete package installations 2563 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2564 for (int i = 0; i < deletePkgsList.size(); i++) { 2565 // Actual deletion of code and data will be handled by later 2566 // reconciliation step 2567 final String packageName = deletePkgsList.get(i).name; 2568 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2569 synchronized (mPackages) { 2570 mSettings.removePackageLPw(packageName); 2571 } 2572 } 2573 2574 //delete tmp files 2575 deleteTempPackageFiles(); 2576 2577 // Remove any shared userIDs that have no associated packages 2578 mSettings.pruneSharedUsersLPw(); 2579 2580 if (!mOnlyCore) { 2581 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2582 SystemClock.uptimeMillis()); 2583 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2584 2585 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2586 | PackageParser.PARSE_FORWARD_LOCK, 2587 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2588 2589 scanDirLI(mEphemeralInstallDir, mDefParseFlags 2590 | PackageParser.PARSE_IS_EPHEMERAL, 2591 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2592 2593 /** 2594 * Remove disable package settings for any updated system 2595 * apps that were removed via an OTA. If they're not a 2596 * previously-updated app, remove them completely. 2597 * Otherwise, just revoke their system-level permissions. 2598 */ 2599 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2600 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2601 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2602 2603 String msg; 2604 if (deletedPkg == null) { 2605 msg = "Updated system package " + deletedAppName 2606 + " no longer exists; it's data will be wiped"; 2607 // Actual deletion of code and data will be handled by later 2608 // reconciliation step 2609 } else { 2610 msg = "Updated system app + " + deletedAppName 2611 + " no longer present; removing system privileges for " 2612 + deletedAppName; 2613 2614 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2615 2616 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2617 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2618 } 2619 logCriticalInfo(Log.WARN, msg); 2620 } 2621 2622 /** 2623 * Make sure all system apps that we expected to appear on 2624 * the userdata partition actually showed up. If they never 2625 * appeared, crawl back and revive the system version. 2626 */ 2627 for (int i = 0; i < mExpectingBetter.size(); i++) { 2628 final String packageName = mExpectingBetter.keyAt(i); 2629 if (!mPackages.containsKey(packageName)) { 2630 final File scanFile = mExpectingBetter.valueAt(i); 2631 2632 logCriticalInfo(Log.WARN, "Expected better " + packageName 2633 + " but never showed up; reverting to system"); 2634 2635 int reparseFlags = mDefParseFlags; 2636 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2637 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2638 | PackageParser.PARSE_IS_SYSTEM_DIR 2639 | PackageParser.PARSE_IS_PRIVILEGED; 2640 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2641 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2642 | PackageParser.PARSE_IS_SYSTEM_DIR; 2643 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2644 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2645 | PackageParser.PARSE_IS_SYSTEM_DIR; 2646 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2647 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2648 | PackageParser.PARSE_IS_SYSTEM_DIR; 2649 } else { 2650 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2651 continue; 2652 } 2653 2654 mSettings.enableSystemPackageLPw(packageName); 2655 2656 try { 2657 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2658 } catch (PackageManagerException e) { 2659 Slog.e(TAG, "Failed to parse original system package: " 2660 + e.getMessage()); 2661 } 2662 } 2663 } 2664 } 2665 mExpectingBetter.clear(); 2666 2667 // Resolve protected action filters. Only the setup wizard is allowed to 2668 // have a high priority filter for these actions. 2669 mSetupWizardPackage = getSetupWizardPackageName(); 2670 if (mProtectedFilters.size() > 0) { 2671 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2672 Slog.i(TAG, "No setup wizard;" 2673 + " All protected intents capped to priority 0"); 2674 } 2675 for (ActivityIntentInfo filter : mProtectedFilters) { 2676 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2677 if (DEBUG_FILTERS) { 2678 Slog.i(TAG, "Found setup wizard;" 2679 + " allow priority " + filter.getPriority() + ";" 2680 + " package: " + filter.activity.info.packageName 2681 + " activity: " + filter.activity.className 2682 + " priority: " + filter.getPriority()); 2683 } 2684 // skip setup wizard; allow it to keep the high priority filter 2685 continue; 2686 } 2687 Slog.w(TAG, "Protected action; cap priority to 0;" 2688 + " package: " + filter.activity.info.packageName 2689 + " activity: " + filter.activity.className 2690 + " origPrio: " + filter.getPriority()); 2691 filter.setPriority(0); 2692 } 2693 } 2694 mDeferProtectedFilters = false; 2695 mProtectedFilters.clear(); 2696 2697 // Now that we know all of the shared libraries, update all clients to have 2698 // the correct library paths. 2699 updateAllSharedLibrariesLPw(); 2700 2701 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2702 // NOTE: We ignore potential failures here during a system scan (like 2703 // the rest of the commands above) because there's precious little we 2704 // can do about it. A settings error is reported, though. 2705 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2706 false /* boot complete */); 2707 } 2708 2709 // Now that we know all the packages we are keeping, 2710 // read and update their last usage times. 2711 mPackageUsage.readLP(); 2712 2713 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2714 SystemClock.uptimeMillis()); 2715 Slog.i(TAG, "Time to scan packages: " 2716 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2717 + " seconds"); 2718 2719 // If the platform SDK has changed since the last time we booted, 2720 // we need to re-grant app permission to catch any new ones that 2721 // appear. This is really a hack, and means that apps can in some 2722 // cases get permissions that the user didn't initially explicitly 2723 // allow... it would be nice to have some better way to handle 2724 // this situation. 2725 int updateFlags = UPDATE_PERMISSIONS_ALL; 2726 if (ver.sdkVersion != mSdkVersion) { 2727 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2728 + mSdkVersion + "; regranting permissions for internal storage"); 2729 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2730 } 2731 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2732 ver.sdkVersion = mSdkVersion; 2733 2734 // If this is the first boot or an update from pre-M, and it is a normal 2735 // boot, then we need to initialize the default preferred apps across 2736 // all defined users. 2737 if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) { 2738 for (UserInfo user : sUserManager.getUsers(true)) { 2739 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2740 applyFactoryDefaultBrowserLPw(user.id); 2741 primeDomainVerificationsLPw(user.id); 2742 } 2743 } 2744 2745 // Prepare storage for system user really early during boot, 2746 // since core system apps like SettingsProvider and SystemUI 2747 // can't wait for user to start 2748 final int storageFlags; 2749 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2750 storageFlags = StorageManager.FLAG_STORAGE_DE; 2751 } else { 2752 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2753 } 2754 reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2755 storageFlags); 2756 2757 // If this is first boot after an OTA, and a normal boot, then 2758 // we need to clear code cache directories. 2759 // Note that we do *not* clear the application profiles. These remain valid 2760 // across OTAs and are used to drive profile verification (post OTA) and 2761 // profile compilation (without waiting to collect a fresh set of profiles). 2762 if (mIsUpgrade && !onlyCore) { 2763 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2764 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2765 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2766 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2767 // No apps are running this early, so no need to freeze 2768 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2769 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2770 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2771 } 2772 } 2773 ver.fingerprint = Build.FINGERPRINT; 2774 } 2775 2776 checkDefaultBrowser(); 2777 2778 // clear only after permissions and other defaults have been updated 2779 mExistingSystemPackages.clear(); 2780 mPromoteSystemApps = false; 2781 2782 // All the changes are done during package scanning. 2783 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2784 2785 // can downgrade to reader 2786 mSettings.writeLPr(); 2787 2788 // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty 2789 // early on (before the package manager declares itself as early) because other 2790 // components in the system server might ask for package contexts for these apps. 2791 // 2792 // Note that "onlyCore" in this context means the system is encrypted or encrypting 2793 // (i.e, that the data partition is unavailable). 2794 if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) { 2795 long start = System.nanoTime(); 2796 List<PackageParser.Package> coreApps = new ArrayList<>(); 2797 for (PackageParser.Package pkg : mPackages.values()) { 2798 if (pkg.coreApp) { 2799 coreApps.add(pkg); 2800 } 2801 } 2802 2803 int[] stats = performDexOpt(coreApps, false, 2804 getCompilerFilterForReason(REASON_CORE_APP)); 2805 2806 final int elapsedTimeSeconds = 2807 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start); 2808 MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds); 2809 2810 if (DEBUG_DEXOPT) { 2811 Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" + 2812 stats[0] + ", " + stats[1] + ", " + stats[2] + ")"); 2813 } 2814 2815 2816 // TODO: Should we log these stats to tron too ? 2817 // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]); 2818 // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]); 2819 // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]); 2820 // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size()); 2821 } 2822 2823 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2824 SystemClock.uptimeMillis()); 2825 2826 if (!mOnlyCore) { 2827 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2828 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2829 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2830 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2831 mIntentFilterVerifierComponent); 2832 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2833 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 2834 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2835 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED); 2836 } else { 2837 mRequiredVerifierPackage = null; 2838 mRequiredInstallerPackage = null; 2839 mIntentFilterVerifierComponent = null; 2840 mIntentFilterVerifier = null; 2841 mServicesSystemSharedLibraryPackageName = null; 2842 mSharedSystemSharedLibraryPackageName = null; 2843 } 2844 2845 mInstallerService = new PackageInstallerService(context, this); 2846 2847 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2848 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2849 // both the installer and resolver must be present to enable ephemeral 2850 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2851 if (DEBUG_EPHEMERAL) { 2852 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2853 + " installer:" + ephemeralInstallerComponent); 2854 } 2855 mEphemeralResolverComponent = ephemeralResolverComponent; 2856 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2857 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2858 mEphemeralResolverConnection = 2859 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2860 } else { 2861 if (DEBUG_EPHEMERAL) { 2862 final String missingComponent = 2863 (ephemeralResolverComponent == null) 2864 ? (ephemeralInstallerComponent == null) 2865 ? "resolver and installer" 2866 : "resolver" 2867 : "installer"; 2868 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2869 } 2870 mEphemeralResolverComponent = null; 2871 mEphemeralInstallerComponent = null; 2872 mEphemeralResolverConnection = null; 2873 } 2874 2875 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2876 } // synchronized (mPackages) 2877 } // synchronized (mInstallLock) 2878 2879 // Now after opening every single application zip, make sure they 2880 // are all flushed. Not really needed, but keeps things nice and 2881 // tidy. 2882 Runtime.getRuntime().gc(); 2883 2884 // The initial scanning above does many calls into installd while 2885 // holding the mPackages lock, but we're mostly interested in yelling 2886 // once we have a booted system. 2887 mInstaller.setWarnIfHeld(mPackages); 2888 2889 // Expose private service for system components to use. 2890 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2891 } 2892 2893 @Override 2894 public boolean isFirstBoot() { 2895 return mFirstBoot; 2896 } 2897 2898 @Override 2899 public boolean isOnlyCoreApps() { 2900 return mOnlyCore; 2901 } 2902 2903 @Override 2904 public boolean isUpgrade() { 2905 return mIsUpgrade; 2906 } 2907 2908 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2909 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2910 2911 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2912 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2913 UserHandle.USER_SYSTEM); 2914 if (matches.size() == 1) { 2915 return matches.get(0).getComponentInfo().packageName; 2916 } else { 2917 Log.e(TAG, "There should probably be exactly one verifier; found " + matches); 2918 return null; 2919 } 2920 } 2921 2922 private @NonNull String getRequiredSharedLibraryLPr(String libraryName) { 2923 synchronized (mPackages) { 2924 SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName); 2925 if (libraryEntry == null) { 2926 throw new IllegalStateException("Missing required shared library:" + libraryName); 2927 } 2928 return libraryEntry.apk; 2929 } 2930 } 2931 2932 private @NonNull String getRequiredInstallerLPr() { 2933 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2934 intent.addCategory(Intent.CATEGORY_DEFAULT); 2935 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2936 2937 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2938 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2939 UserHandle.USER_SYSTEM); 2940 if (matches.size() == 1) { 2941 ResolveInfo resolveInfo = matches.get(0); 2942 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 2943 throw new RuntimeException("The installer must be a privileged app"); 2944 } 2945 return matches.get(0).getComponentInfo().packageName; 2946 } else { 2947 throw new RuntimeException("There must be exactly one installer; found " + matches); 2948 } 2949 } 2950 2951 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2952 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2953 2954 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2955 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2956 UserHandle.USER_SYSTEM); 2957 ResolveInfo best = null; 2958 final int N = matches.size(); 2959 for (int i = 0; i < N; i++) { 2960 final ResolveInfo cur = matches.get(i); 2961 final String packageName = cur.getComponentInfo().packageName; 2962 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2963 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2964 continue; 2965 } 2966 2967 if (best == null || cur.priority > best.priority) { 2968 best = cur; 2969 } 2970 } 2971 2972 if (best != null) { 2973 return best.getComponentInfo().getComponentName(); 2974 } else { 2975 throw new RuntimeException("There must be at least one intent filter verifier"); 2976 } 2977 } 2978 2979 private @Nullable ComponentName getEphemeralResolverLPr() { 2980 final String[] packageArray = 2981 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2982 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) { 2983 if (DEBUG_EPHEMERAL) { 2984 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2985 } 2986 return null; 2987 } 2988 2989 final int resolveFlags = 2990 MATCH_DIRECT_BOOT_AWARE 2991 | MATCH_DIRECT_BOOT_UNAWARE 2992 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 2993 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2994 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 2995 resolveFlags, UserHandle.USER_SYSTEM); 2996 2997 final int N = resolvers.size(); 2998 if (N == 0) { 2999 if (DEBUG_EPHEMERAL) { 3000 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 3001 } 3002 return null; 3003 } 3004 3005 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 3006 for (int i = 0; i < N; i++) { 3007 final ResolveInfo info = resolvers.get(i); 3008 3009 if (info.serviceInfo == null) { 3010 continue; 3011 } 3012 3013 final String packageName = info.serviceInfo.packageName; 3014 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) { 3015 if (DEBUG_EPHEMERAL) { 3016 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 3017 + " pkg: " + packageName + ", info:" + info); 3018 } 3019 continue; 3020 } 3021 3022 if (DEBUG_EPHEMERAL) { 3023 Slog.v(TAG, "Ephemeral resolver found;" 3024 + " pkg: " + packageName + ", info:" + info); 3025 } 3026 return new ComponentName(packageName, info.serviceInfo.name); 3027 } 3028 if (DEBUG_EPHEMERAL) { 3029 Slog.v(TAG, "Ephemeral resolver NOT found"); 3030 } 3031 return null; 3032 } 3033 3034 private @Nullable ComponentName getEphemeralInstallerLPr() { 3035 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 3036 intent.addCategory(Intent.CATEGORY_DEFAULT); 3037 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3038 3039 final int resolveFlags = 3040 MATCH_DIRECT_BOOT_AWARE 3041 | MATCH_DIRECT_BOOT_UNAWARE 3042 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3043 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3044 resolveFlags, UserHandle.USER_SYSTEM); 3045 if (matches.size() == 0) { 3046 return null; 3047 } else if (matches.size() == 1) { 3048 return matches.get(0).getComponentInfo().getComponentName(); 3049 } else { 3050 throw new RuntimeException( 3051 "There must be at most one ephemeral installer; found " + matches); 3052 } 3053 } 3054 3055 private void primeDomainVerificationsLPw(int userId) { 3056 if (DEBUG_DOMAIN_VERIFICATION) { 3057 Slog.d(TAG, "Priming domain verifications in user " + userId); 3058 } 3059 3060 SystemConfig systemConfig = SystemConfig.getInstance(); 3061 ArraySet<String> packages = systemConfig.getLinkedApps(); 3062 ArraySet<String> domains = new ArraySet<String>(); 3063 3064 for (String packageName : packages) { 3065 PackageParser.Package pkg = mPackages.get(packageName); 3066 if (pkg != null) { 3067 if (!pkg.isSystemApp()) { 3068 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 3069 continue; 3070 } 3071 3072 domains.clear(); 3073 for (PackageParser.Activity a : pkg.activities) { 3074 for (ActivityIntentInfo filter : a.intents) { 3075 if (hasValidDomains(filter)) { 3076 domains.addAll(filter.getHostsList()); 3077 } 3078 } 3079 } 3080 3081 if (domains.size() > 0) { 3082 if (DEBUG_DOMAIN_VERIFICATION) { 3083 Slog.v(TAG, " + " + packageName); 3084 } 3085 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 3086 // state w.r.t. the formal app-linkage "no verification attempted" state; 3087 // and then 'always' in the per-user state actually used for intent resolution. 3088 final IntentFilterVerificationInfo ivi; 3089 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 3090 new ArrayList<String>(domains)); 3091 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 3092 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 3093 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 3094 } else { 3095 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 3096 + "' does not handle web links"); 3097 } 3098 } else { 3099 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 3100 } 3101 } 3102 3103 scheduleWritePackageRestrictionsLocked(userId); 3104 scheduleWriteSettingsLocked(); 3105 } 3106 3107 private void applyFactoryDefaultBrowserLPw(int userId) { 3108 // The default browser app's package name is stored in a string resource, 3109 // with a product-specific overlay used for vendor customization. 3110 String browserPkg = mContext.getResources().getString( 3111 com.android.internal.R.string.default_browser); 3112 if (!TextUtils.isEmpty(browserPkg)) { 3113 // non-empty string => required to be a known package 3114 PackageSetting ps = mSettings.mPackages.get(browserPkg); 3115 if (ps == null) { 3116 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3117 browserPkg = null; 3118 } else { 3119 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3120 } 3121 } 3122 3123 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3124 // default. If there's more than one, just leave everything alone. 3125 if (browserPkg == null) { 3126 calculateDefaultBrowserLPw(userId); 3127 } 3128 } 3129 3130 private void calculateDefaultBrowserLPw(int userId) { 3131 List<String> allBrowsers = resolveAllBrowserApps(userId); 3132 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3133 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3134 } 3135 3136 private List<String> resolveAllBrowserApps(int userId) { 3137 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3138 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3139 PackageManager.MATCH_ALL, userId); 3140 3141 final int count = list.size(); 3142 List<String> result = new ArrayList<String>(count); 3143 for (int i=0; i<count; i++) { 3144 ResolveInfo info = list.get(i); 3145 if (info.activityInfo == null 3146 || !info.handleAllWebDataURI 3147 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3148 || result.contains(info.activityInfo.packageName)) { 3149 continue; 3150 } 3151 result.add(info.activityInfo.packageName); 3152 } 3153 3154 return result; 3155 } 3156 3157 private boolean packageIsBrowser(String packageName, int userId) { 3158 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3159 PackageManager.MATCH_ALL, userId); 3160 final int N = list.size(); 3161 for (int i = 0; i < N; i++) { 3162 ResolveInfo info = list.get(i); 3163 if (packageName.equals(info.activityInfo.packageName)) { 3164 return true; 3165 } 3166 } 3167 return false; 3168 } 3169 3170 private void checkDefaultBrowser() { 3171 final int myUserId = UserHandle.myUserId(); 3172 final String packageName = getDefaultBrowserPackageName(myUserId); 3173 if (packageName != null) { 3174 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3175 if (info == null) { 3176 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3177 synchronized (mPackages) { 3178 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3179 } 3180 } 3181 } 3182 } 3183 3184 @Override 3185 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3186 throws RemoteException { 3187 try { 3188 return super.onTransact(code, data, reply, flags); 3189 } catch (RuntimeException e) { 3190 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3191 Slog.wtf(TAG, "Package Manager Crash", e); 3192 } 3193 throw e; 3194 } 3195 } 3196 3197 static int[] appendInts(int[] cur, int[] add) { 3198 if (add == null) return cur; 3199 if (cur == null) return add; 3200 final int N = add.length; 3201 for (int i=0; i<N; i++) { 3202 cur = appendInt(cur, add[i]); 3203 } 3204 return cur; 3205 } 3206 3207 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3208 if (!sUserManager.exists(userId)) return null; 3209 if (ps == null) { 3210 return null; 3211 } 3212 final PackageParser.Package p = ps.pkg; 3213 if (p == null) { 3214 return null; 3215 } 3216 3217 final PermissionsState permissionsState = ps.getPermissionsState(); 3218 3219 // Compute GIDs only if requested 3220 final int[] gids = (flags & PackageManager.GET_GIDS) == 0 3221 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId); 3222 // Compute granted permissions only if package has requested permissions 3223 final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions) 3224 ? Collections.<String>emptySet() : permissionsState.getPermissions(userId); 3225 final PackageUserState state = ps.readUserState(userId); 3226 3227 return PackageParser.generatePackageInfo(p, gids, flags, 3228 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3229 } 3230 3231 @Override 3232 public void checkPackageStartable(String packageName, int userId) { 3233 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3234 3235 synchronized (mPackages) { 3236 final PackageSetting ps = mSettings.mPackages.get(packageName); 3237 if (ps == null) { 3238 throw new SecurityException("Package " + packageName + " was not found!"); 3239 } 3240 3241 if (!ps.getInstalled(userId)) { 3242 throw new SecurityException( 3243 "Package " + packageName + " was not installed for user " + userId + "!"); 3244 } 3245 3246 if (mSafeMode && !ps.isSystem()) { 3247 throw new SecurityException("Package " + packageName + " not a system app!"); 3248 } 3249 3250 if (mFrozenPackages.contains(packageName)) { 3251 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3252 } 3253 3254 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3255 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3256 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3257 } 3258 } 3259 } 3260 3261 @Override 3262 public boolean isPackageAvailable(String packageName, int userId) { 3263 if (!sUserManager.exists(userId)) return false; 3264 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3265 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3266 synchronized (mPackages) { 3267 PackageParser.Package p = mPackages.get(packageName); 3268 if (p != null) { 3269 final PackageSetting ps = (PackageSetting) p.mExtras; 3270 if (ps != null) { 3271 final PackageUserState state = ps.readUserState(userId); 3272 if (state != null) { 3273 return PackageParser.isAvailable(state); 3274 } 3275 } 3276 } 3277 } 3278 return false; 3279 } 3280 3281 @Override 3282 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3283 if (!sUserManager.exists(userId)) return null; 3284 flags = updateFlagsForPackage(flags, userId, packageName); 3285 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3286 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3287 // reader 3288 synchronized (mPackages) { 3289 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3290 PackageParser.Package p = null; 3291 if (matchFactoryOnly) { 3292 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3293 if (ps != null) { 3294 return generatePackageInfo(ps, flags, userId); 3295 } 3296 } 3297 if (p == null) { 3298 p = mPackages.get(packageName); 3299 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3300 return null; 3301 } 3302 } 3303 if (DEBUG_PACKAGE_INFO) 3304 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3305 if (p != null) { 3306 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3307 } 3308 if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3309 final PackageSetting ps = mSettings.mPackages.get(packageName); 3310 return generatePackageInfo(ps, flags, userId); 3311 } 3312 } 3313 return null; 3314 } 3315 3316 @Override 3317 public String[] currentToCanonicalPackageNames(String[] names) { 3318 String[] out = new String[names.length]; 3319 // reader 3320 synchronized (mPackages) { 3321 for (int i=names.length-1; i>=0; i--) { 3322 PackageSetting ps = mSettings.mPackages.get(names[i]); 3323 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3324 } 3325 } 3326 return out; 3327 } 3328 3329 @Override 3330 public String[] canonicalToCurrentPackageNames(String[] names) { 3331 String[] out = new String[names.length]; 3332 // reader 3333 synchronized (mPackages) { 3334 for (int i=names.length-1; i>=0; i--) { 3335 String cur = mSettings.mRenamedPackages.get(names[i]); 3336 out[i] = cur != null ? cur : names[i]; 3337 } 3338 } 3339 return out; 3340 } 3341 3342 @Override 3343 public int getPackageUid(String packageName, int flags, int userId) { 3344 if (!sUserManager.exists(userId)) return -1; 3345 flags = updateFlagsForPackage(flags, userId, packageName); 3346 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3347 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3348 3349 // reader 3350 synchronized (mPackages) { 3351 final PackageParser.Package p = mPackages.get(packageName); 3352 if (p != null && p.isMatch(flags)) { 3353 return UserHandle.getUid(userId, p.applicationInfo.uid); 3354 } 3355 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3356 final PackageSetting ps = mSettings.mPackages.get(packageName); 3357 if (ps != null && ps.isMatch(flags)) { 3358 return UserHandle.getUid(userId, ps.appId); 3359 } 3360 } 3361 } 3362 3363 return -1; 3364 } 3365 3366 @Override 3367 public int[] getPackageGids(String packageName, int flags, int userId) { 3368 if (!sUserManager.exists(userId)) return null; 3369 flags = updateFlagsForPackage(flags, userId, packageName); 3370 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3371 false /* requireFullPermission */, false /* checkShell */, 3372 "getPackageGids"); 3373 3374 // reader 3375 synchronized (mPackages) { 3376 final PackageParser.Package p = mPackages.get(packageName); 3377 if (p != null && p.isMatch(flags)) { 3378 PackageSetting ps = (PackageSetting) p.mExtras; 3379 return ps.getPermissionsState().computeGids(userId); 3380 } 3381 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3382 final PackageSetting ps = mSettings.mPackages.get(packageName); 3383 if (ps != null && ps.isMatch(flags)) { 3384 return ps.getPermissionsState().computeGids(userId); 3385 } 3386 } 3387 } 3388 3389 return null; 3390 } 3391 3392 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3393 if (bp.perm != null) { 3394 return PackageParser.generatePermissionInfo(bp.perm, flags); 3395 } 3396 PermissionInfo pi = new PermissionInfo(); 3397 pi.name = bp.name; 3398 pi.packageName = bp.sourcePackage; 3399 pi.nonLocalizedLabel = bp.name; 3400 pi.protectionLevel = bp.protectionLevel; 3401 return pi; 3402 } 3403 3404 @Override 3405 public PermissionInfo getPermissionInfo(String name, int flags) { 3406 // reader 3407 synchronized (mPackages) { 3408 final BasePermission p = mSettings.mPermissions.get(name); 3409 if (p != null) { 3410 return generatePermissionInfo(p, flags); 3411 } 3412 return null; 3413 } 3414 } 3415 3416 @Override 3417 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3418 int flags) { 3419 // reader 3420 synchronized (mPackages) { 3421 if (group != null && !mPermissionGroups.containsKey(group)) { 3422 // This is thrown as NameNotFoundException 3423 return null; 3424 } 3425 3426 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3427 for (BasePermission p : mSettings.mPermissions.values()) { 3428 if (group == null) { 3429 if (p.perm == null || p.perm.info.group == null) { 3430 out.add(generatePermissionInfo(p, flags)); 3431 } 3432 } else { 3433 if (p.perm != null && group.equals(p.perm.info.group)) { 3434 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3435 } 3436 } 3437 } 3438 return new ParceledListSlice<>(out); 3439 } 3440 } 3441 3442 @Override 3443 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3444 // reader 3445 synchronized (mPackages) { 3446 return PackageParser.generatePermissionGroupInfo( 3447 mPermissionGroups.get(name), flags); 3448 } 3449 } 3450 3451 @Override 3452 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3453 // reader 3454 synchronized (mPackages) { 3455 final int N = mPermissionGroups.size(); 3456 ArrayList<PermissionGroupInfo> out 3457 = new ArrayList<PermissionGroupInfo>(N); 3458 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3459 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3460 } 3461 return new ParceledListSlice<>(out); 3462 } 3463 } 3464 3465 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3466 int userId) { 3467 if (!sUserManager.exists(userId)) return null; 3468 PackageSetting ps = mSettings.mPackages.get(packageName); 3469 if (ps != null) { 3470 if (ps.pkg == null) { 3471 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3472 if (pInfo != null) { 3473 return pInfo.applicationInfo; 3474 } 3475 return null; 3476 } 3477 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3478 ps.readUserState(userId), userId); 3479 } 3480 return null; 3481 } 3482 3483 @Override 3484 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3485 if (!sUserManager.exists(userId)) return null; 3486 flags = updateFlagsForApplication(flags, userId, packageName); 3487 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3488 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3489 // writer 3490 synchronized (mPackages) { 3491 PackageParser.Package p = mPackages.get(packageName); 3492 if (DEBUG_PACKAGE_INFO) Log.v( 3493 TAG, "getApplicationInfo " + packageName 3494 + ": " + p); 3495 if (p != null) { 3496 PackageSetting ps = mSettings.mPackages.get(packageName); 3497 if (ps == null) return null; 3498 // Note: isEnabledLP() does not apply here - always return info 3499 return PackageParser.generateApplicationInfo( 3500 p, flags, ps.readUserState(userId), userId); 3501 } 3502 if ("android".equals(packageName)||"system".equals(packageName)) { 3503 return mAndroidApplication; 3504 } 3505 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3506 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3507 } 3508 } 3509 return null; 3510 } 3511 3512 @Override 3513 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3514 final IPackageDataObserver observer) { 3515 mContext.enforceCallingOrSelfPermission( 3516 android.Manifest.permission.CLEAR_APP_CACHE, null); 3517 // Queue up an async operation since clearing cache may take a little while. 3518 mHandler.post(new Runnable() { 3519 public void run() { 3520 mHandler.removeCallbacks(this); 3521 boolean success = true; 3522 synchronized (mInstallLock) { 3523 try { 3524 mInstaller.freeCache(volumeUuid, freeStorageSize); 3525 } catch (InstallerException e) { 3526 Slog.w(TAG, "Couldn't clear application caches: " + e); 3527 success = false; 3528 } 3529 } 3530 if (observer != null) { 3531 try { 3532 observer.onRemoveCompleted(null, success); 3533 } catch (RemoteException e) { 3534 Slog.w(TAG, "RemoveException when invoking call back"); 3535 } 3536 } 3537 } 3538 }); 3539 } 3540 3541 @Override 3542 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3543 final IntentSender pi) { 3544 mContext.enforceCallingOrSelfPermission( 3545 android.Manifest.permission.CLEAR_APP_CACHE, null); 3546 // Queue up an async operation since clearing cache may take a little while. 3547 mHandler.post(new Runnable() { 3548 public void run() { 3549 mHandler.removeCallbacks(this); 3550 boolean success = true; 3551 synchronized (mInstallLock) { 3552 try { 3553 mInstaller.freeCache(volumeUuid, freeStorageSize); 3554 } catch (InstallerException e) { 3555 Slog.w(TAG, "Couldn't clear application caches: " + e); 3556 success = false; 3557 } 3558 } 3559 if(pi != null) { 3560 try { 3561 // Callback via pending intent 3562 int code = success ? 1 : 0; 3563 pi.sendIntent(null, code, null, 3564 null, null); 3565 } catch (SendIntentException e1) { 3566 Slog.i(TAG, "Failed to send pending intent"); 3567 } 3568 } 3569 } 3570 }); 3571 } 3572 3573 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3574 synchronized (mInstallLock) { 3575 try { 3576 mInstaller.freeCache(volumeUuid, freeStorageSize); 3577 } catch (InstallerException e) { 3578 throw new IOException("Failed to free enough space", e); 3579 } 3580 } 3581 } 3582 3583 /** 3584 * Update given flags based on encryption status of current user. 3585 */ 3586 private int updateFlags(int flags, int userId) { 3587 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3588 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3589 // Caller expressed an explicit opinion about what encryption 3590 // aware/unaware components they want to see, so fall through and 3591 // give them what they want 3592 } else { 3593 // Caller expressed no opinion, so match based on user state 3594 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 3595 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3596 } else { 3597 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3598 } 3599 } 3600 return flags; 3601 } 3602 3603 private UserManagerInternal getUserManagerInternal() { 3604 if (mUserManagerInternal == null) { 3605 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 3606 } 3607 return mUserManagerInternal; 3608 } 3609 3610 /** 3611 * Update given flags when being used to request {@link PackageInfo}. 3612 */ 3613 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3614 boolean triaged = true; 3615 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3616 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3617 // Caller is asking for component details, so they'd better be 3618 // asking for specific encryption matching behavior, or be triaged 3619 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3620 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3621 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3622 triaged = false; 3623 } 3624 } 3625 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3626 | PackageManager.MATCH_SYSTEM_ONLY 3627 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3628 triaged = false; 3629 } 3630 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3631 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3632 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3633 } 3634 return updateFlags(flags, userId); 3635 } 3636 3637 /** 3638 * Update given flags when being used to request {@link ApplicationInfo}. 3639 */ 3640 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3641 return updateFlagsForPackage(flags, userId, cookie); 3642 } 3643 3644 /** 3645 * Update given flags when being used to request {@link ComponentInfo}. 3646 */ 3647 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3648 if (cookie instanceof Intent) { 3649 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3650 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3651 } 3652 } 3653 3654 boolean triaged = true; 3655 // Caller is asking for component details, so they'd better be 3656 // asking for specific encryption matching behavior, or be triaged 3657 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3658 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3659 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3660 triaged = false; 3661 } 3662 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3663 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3664 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3665 } 3666 3667 return updateFlags(flags, userId); 3668 } 3669 3670 /** 3671 * Update given flags when being used to request {@link ResolveInfo}. 3672 */ 3673 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3674 // Safe mode means we shouldn't match any third-party components 3675 if (mSafeMode) { 3676 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3677 } 3678 3679 return updateFlagsForComponent(flags, userId, cookie); 3680 } 3681 3682 @Override 3683 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3684 if (!sUserManager.exists(userId)) return null; 3685 flags = updateFlagsForComponent(flags, userId, component); 3686 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3687 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3688 synchronized (mPackages) { 3689 PackageParser.Activity a = mActivities.mActivities.get(component); 3690 3691 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3692 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3693 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3694 if (ps == null) return null; 3695 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3696 userId); 3697 } 3698 if (mResolveComponentName.equals(component)) { 3699 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3700 new PackageUserState(), userId); 3701 } 3702 } 3703 return null; 3704 } 3705 3706 @Override 3707 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3708 String resolvedType) { 3709 synchronized (mPackages) { 3710 if (component.equals(mResolveComponentName)) { 3711 // The resolver supports EVERYTHING! 3712 return true; 3713 } 3714 PackageParser.Activity a = mActivities.mActivities.get(component); 3715 if (a == null) { 3716 return false; 3717 } 3718 for (int i=0; i<a.intents.size(); i++) { 3719 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3720 intent.getData(), intent.getCategories(), TAG) >= 0) { 3721 return true; 3722 } 3723 } 3724 return false; 3725 } 3726 } 3727 3728 @Override 3729 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3730 if (!sUserManager.exists(userId)) return null; 3731 flags = updateFlagsForComponent(flags, userId, component); 3732 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3733 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3734 synchronized (mPackages) { 3735 PackageParser.Activity a = mReceivers.mActivities.get(component); 3736 if (DEBUG_PACKAGE_INFO) Log.v( 3737 TAG, "getReceiverInfo " + component + ": " + a); 3738 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3739 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3740 if (ps == null) return null; 3741 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3742 userId); 3743 } 3744 } 3745 return null; 3746 } 3747 3748 @Override 3749 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3750 if (!sUserManager.exists(userId)) return null; 3751 flags = updateFlagsForComponent(flags, userId, component); 3752 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3753 false /* requireFullPermission */, false /* checkShell */, "get service info"); 3754 synchronized (mPackages) { 3755 PackageParser.Service s = mServices.mServices.get(component); 3756 if (DEBUG_PACKAGE_INFO) Log.v( 3757 TAG, "getServiceInfo " + component + ": " + s); 3758 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3759 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3760 if (ps == null) return null; 3761 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3762 userId); 3763 } 3764 } 3765 return null; 3766 } 3767 3768 @Override 3769 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3770 if (!sUserManager.exists(userId)) return null; 3771 flags = updateFlagsForComponent(flags, userId, component); 3772 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3773 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 3774 synchronized (mPackages) { 3775 PackageParser.Provider p = mProviders.mProviders.get(component); 3776 if (DEBUG_PACKAGE_INFO) Log.v( 3777 TAG, "getProviderInfo " + component + ": " + p); 3778 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3779 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3780 if (ps == null) return null; 3781 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3782 userId); 3783 } 3784 } 3785 return null; 3786 } 3787 3788 @Override 3789 public String[] getSystemSharedLibraryNames() { 3790 Set<String> libSet; 3791 synchronized (mPackages) { 3792 libSet = mSharedLibraries.keySet(); 3793 int size = libSet.size(); 3794 if (size > 0) { 3795 String[] libs = new String[size]; 3796 libSet.toArray(libs); 3797 return libs; 3798 } 3799 } 3800 return null; 3801 } 3802 3803 @Override 3804 public @NonNull String getServicesSystemSharedLibraryPackageName() { 3805 synchronized (mPackages) { 3806 return mServicesSystemSharedLibraryPackageName; 3807 } 3808 } 3809 3810 @Override 3811 public @NonNull String getSharedSystemSharedLibraryPackageName() { 3812 synchronized (mPackages) { 3813 return mSharedSystemSharedLibraryPackageName; 3814 } 3815 } 3816 3817 @Override 3818 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 3819 synchronized (mPackages) { 3820 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values()); 3821 3822 final FeatureInfo fi = new FeatureInfo(); 3823 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3824 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3825 res.add(fi); 3826 3827 return new ParceledListSlice<>(res); 3828 } 3829 } 3830 3831 @Override 3832 public boolean hasSystemFeature(String name, int version) { 3833 synchronized (mPackages) { 3834 final FeatureInfo feat = mAvailableFeatures.get(name); 3835 if (feat == null) { 3836 return false; 3837 } else { 3838 return feat.version >= version; 3839 } 3840 } 3841 } 3842 3843 @Override 3844 public int checkPermission(String permName, String pkgName, int userId) { 3845 if (!sUserManager.exists(userId)) { 3846 return PackageManager.PERMISSION_DENIED; 3847 } 3848 3849 synchronized (mPackages) { 3850 final PackageParser.Package p = mPackages.get(pkgName); 3851 if (p != null && p.mExtras != null) { 3852 final PackageSetting ps = (PackageSetting) p.mExtras; 3853 final PermissionsState permissionsState = ps.getPermissionsState(); 3854 if (permissionsState.hasPermission(permName, userId)) { 3855 return PackageManager.PERMISSION_GRANTED; 3856 } 3857 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3858 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3859 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3860 return PackageManager.PERMISSION_GRANTED; 3861 } 3862 } 3863 } 3864 3865 return PackageManager.PERMISSION_DENIED; 3866 } 3867 3868 @Override 3869 public int checkUidPermission(String permName, int uid) { 3870 final int userId = UserHandle.getUserId(uid); 3871 3872 if (!sUserManager.exists(userId)) { 3873 return PackageManager.PERMISSION_DENIED; 3874 } 3875 3876 synchronized (mPackages) { 3877 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3878 if (obj != null) { 3879 final SettingBase ps = (SettingBase) obj; 3880 final PermissionsState permissionsState = ps.getPermissionsState(); 3881 if (permissionsState.hasPermission(permName, userId)) { 3882 return PackageManager.PERMISSION_GRANTED; 3883 } 3884 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3885 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3886 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3887 return PackageManager.PERMISSION_GRANTED; 3888 } 3889 } else { 3890 ArraySet<String> perms = mSystemPermissions.get(uid); 3891 if (perms != null) { 3892 if (perms.contains(permName)) { 3893 return PackageManager.PERMISSION_GRANTED; 3894 } 3895 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3896 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3897 return PackageManager.PERMISSION_GRANTED; 3898 } 3899 } 3900 } 3901 } 3902 3903 return PackageManager.PERMISSION_DENIED; 3904 } 3905 3906 @Override 3907 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3908 if (UserHandle.getCallingUserId() != userId) { 3909 mContext.enforceCallingPermission( 3910 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3911 "isPermissionRevokedByPolicy for user " + userId); 3912 } 3913 3914 if (checkPermission(permission, packageName, userId) 3915 == PackageManager.PERMISSION_GRANTED) { 3916 return false; 3917 } 3918 3919 final long identity = Binder.clearCallingIdentity(); 3920 try { 3921 final int flags = getPermissionFlags(permission, packageName, userId); 3922 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3923 } finally { 3924 Binder.restoreCallingIdentity(identity); 3925 } 3926 } 3927 3928 @Override 3929 public String getPermissionControllerPackageName() { 3930 synchronized (mPackages) { 3931 return mRequiredInstallerPackage; 3932 } 3933 } 3934 3935 /** 3936 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3937 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3938 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3939 * @param message the message to log on security exception 3940 */ 3941 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3942 boolean checkShell, String message) { 3943 if (userId < 0) { 3944 throw new IllegalArgumentException("Invalid userId " + userId); 3945 } 3946 if (checkShell) { 3947 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3948 } 3949 if (userId == UserHandle.getUserId(callingUid)) return; 3950 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3951 if (requireFullPermission) { 3952 mContext.enforceCallingOrSelfPermission( 3953 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3954 } else { 3955 try { 3956 mContext.enforceCallingOrSelfPermission( 3957 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3958 } catch (SecurityException se) { 3959 mContext.enforceCallingOrSelfPermission( 3960 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3961 } 3962 } 3963 } 3964 } 3965 3966 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3967 if (callingUid == Process.SHELL_UID) { 3968 if (userHandle >= 0 3969 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3970 throw new SecurityException("Shell does not have permission to access user " 3971 + userHandle); 3972 } else if (userHandle < 0) { 3973 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3974 + Debug.getCallers(3)); 3975 } 3976 } 3977 } 3978 3979 private BasePermission findPermissionTreeLP(String permName) { 3980 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3981 if (permName.startsWith(bp.name) && 3982 permName.length() > bp.name.length() && 3983 permName.charAt(bp.name.length()) == '.') { 3984 return bp; 3985 } 3986 } 3987 return null; 3988 } 3989 3990 private BasePermission checkPermissionTreeLP(String permName) { 3991 if (permName != null) { 3992 BasePermission bp = findPermissionTreeLP(permName); 3993 if (bp != null) { 3994 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3995 return bp; 3996 } 3997 throw new SecurityException("Calling uid " 3998 + Binder.getCallingUid() 3999 + " is not allowed to add to permission tree " 4000 + bp.name + " owned by uid " + bp.uid); 4001 } 4002 } 4003 throw new SecurityException("No permission tree found for " + permName); 4004 } 4005 4006 static boolean compareStrings(CharSequence s1, CharSequence s2) { 4007 if (s1 == null) { 4008 return s2 == null; 4009 } 4010 if (s2 == null) { 4011 return false; 4012 } 4013 if (s1.getClass() != s2.getClass()) { 4014 return false; 4015 } 4016 return s1.equals(s2); 4017 } 4018 4019 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 4020 if (pi1.icon != pi2.icon) return false; 4021 if (pi1.logo != pi2.logo) return false; 4022 if (pi1.protectionLevel != pi2.protectionLevel) return false; 4023 if (!compareStrings(pi1.name, pi2.name)) return false; 4024 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 4025 // We'll take care of setting this one. 4026 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 4027 // These are not currently stored in settings. 4028 //if (!compareStrings(pi1.group, pi2.group)) return false; 4029 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 4030 //if (pi1.labelRes != pi2.labelRes) return false; 4031 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 4032 return true; 4033 } 4034 4035 int permissionInfoFootprint(PermissionInfo info) { 4036 int size = info.name.length(); 4037 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 4038 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 4039 return size; 4040 } 4041 4042 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 4043 int size = 0; 4044 for (BasePermission perm : mSettings.mPermissions.values()) { 4045 if (perm.uid == tree.uid) { 4046 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 4047 } 4048 } 4049 return size; 4050 } 4051 4052 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 4053 // We calculate the max size of permissions defined by this uid and throw 4054 // if that plus the size of 'info' would exceed our stated maximum. 4055 if (tree.uid != Process.SYSTEM_UID) { 4056 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 4057 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 4058 throw new SecurityException("Permission tree size cap exceeded"); 4059 } 4060 } 4061 } 4062 4063 boolean addPermissionLocked(PermissionInfo info, boolean async) { 4064 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 4065 throw new SecurityException("Label must be specified in permission"); 4066 } 4067 BasePermission tree = checkPermissionTreeLP(info.name); 4068 BasePermission bp = mSettings.mPermissions.get(info.name); 4069 boolean added = bp == null; 4070 boolean changed = true; 4071 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 4072 if (added) { 4073 enforcePermissionCapLocked(info, tree); 4074 bp = new BasePermission(info.name, tree.sourcePackage, 4075 BasePermission.TYPE_DYNAMIC); 4076 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 4077 throw new SecurityException( 4078 "Not allowed to modify non-dynamic permission " 4079 + info.name); 4080 } else { 4081 if (bp.protectionLevel == fixedLevel 4082 && bp.perm.owner.equals(tree.perm.owner) 4083 && bp.uid == tree.uid 4084 && comparePermissionInfos(bp.perm.info, info)) { 4085 changed = false; 4086 } 4087 } 4088 bp.protectionLevel = fixedLevel; 4089 info = new PermissionInfo(info); 4090 info.protectionLevel = fixedLevel; 4091 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 4092 bp.perm.info.packageName = tree.perm.info.packageName; 4093 bp.uid = tree.uid; 4094 if (added) { 4095 mSettings.mPermissions.put(info.name, bp); 4096 } 4097 if (changed) { 4098 if (!async) { 4099 mSettings.writeLPr(); 4100 } else { 4101 scheduleWriteSettingsLocked(); 4102 } 4103 } 4104 return added; 4105 } 4106 4107 @Override 4108 public boolean addPermission(PermissionInfo info) { 4109 synchronized (mPackages) { 4110 return addPermissionLocked(info, false); 4111 } 4112 } 4113 4114 @Override 4115 public boolean addPermissionAsync(PermissionInfo info) { 4116 synchronized (mPackages) { 4117 return addPermissionLocked(info, true); 4118 } 4119 } 4120 4121 @Override 4122 public void removePermission(String name) { 4123 synchronized (mPackages) { 4124 checkPermissionTreeLP(name); 4125 BasePermission bp = mSettings.mPermissions.get(name); 4126 if (bp != null) { 4127 if (bp.type != BasePermission.TYPE_DYNAMIC) { 4128 throw new SecurityException( 4129 "Not allowed to modify non-dynamic permission " 4130 + name); 4131 } 4132 mSettings.mPermissions.remove(name); 4133 mSettings.writeLPr(); 4134 } 4135 } 4136 } 4137 4138 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 4139 BasePermission bp) { 4140 int index = pkg.requestedPermissions.indexOf(bp.name); 4141 if (index == -1) { 4142 throw new SecurityException("Package " + pkg.packageName 4143 + " has not requested permission " + bp.name); 4144 } 4145 if (!bp.isRuntime() && !bp.isDevelopment()) { 4146 throw new SecurityException("Permission " + bp.name 4147 + " is not a changeable permission type"); 4148 } 4149 } 4150 4151 @Override 4152 public void grantRuntimePermission(String packageName, String name, final int userId) { 4153 if (!sUserManager.exists(userId)) { 4154 Log.e(TAG, "No such user:" + userId); 4155 return; 4156 } 4157 4158 mContext.enforceCallingOrSelfPermission( 4159 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 4160 "grantRuntimePermission"); 4161 4162 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4163 true /* requireFullPermission */, true /* checkShell */, 4164 "grantRuntimePermission"); 4165 4166 final int uid; 4167 final SettingBase sb; 4168 4169 synchronized (mPackages) { 4170 final PackageParser.Package pkg = mPackages.get(packageName); 4171 if (pkg == null) { 4172 throw new IllegalArgumentException("Unknown package: " + packageName); 4173 } 4174 4175 final BasePermission bp = mSettings.mPermissions.get(name); 4176 if (bp == null) { 4177 throw new IllegalArgumentException("Unknown permission: " + name); 4178 } 4179 4180 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4181 4182 // If a permission review is required for legacy apps we represent 4183 // their permissions as always granted runtime ones since we need 4184 // to keep the review required permission flag per user while an 4185 // install permission's state is shared across all users. 4186 if (Build.PERMISSIONS_REVIEW_REQUIRED 4187 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4188 && bp.isRuntime()) { 4189 return; 4190 } 4191 4192 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4193 sb = (SettingBase) pkg.mExtras; 4194 if (sb == null) { 4195 throw new IllegalArgumentException("Unknown package: " + packageName); 4196 } 4197 4198 final PermissionsState permissionsState = sb.getPermissionsState(); 4199 4200 final int flags = permissionsState.getPermissionFlags(name, userId); 4201 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4202 throw new SecurityException("Cannot grant system fixed permission " 4203 + name + " for package " + packageName); 4204 } 4205 4206 if (bp.isDevelopment()) { 4207 // Development permissions must be handled specially, since they are not 4208 // normal runtime permissions. For now they apply to all users. 4209 if (permissionsState.grantInstallPermission(bp) != 4210 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4211 scheduleWriteSettingsLocked(); 4212 } 4213 return; 4214 } 4215 4216 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4217 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4218 return; 4219 } 4220 4221 final int result = permissionsState.grantRuntimePermission(bp, userId); 4222 switch (result) { 4223 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4224 return; 4225 } 4226 4227 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4228 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4229 mHandler.post(new Runnable() { 4230 @Override 4231 public void run() { 4232 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4233 } 4234 }); 4235 } 4236 break; 4237 } 4238 4239 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4240 4241 // Not critical if that is lost - app has to request again. 4242 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4243 } 4244 4245 // Only need to do this if user is initialized. Otherwise it's a new user 4246 // and there are no processes running as the user yet and there's no need 4247 // to make an expensive call to remount processes for the changed permissions. 4248 if (READ_EXTERNAL_STORAGE.equals(name) 4249 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4250 final long token = Binder.clearCallingIdentity(); 4251 try { 4252 if (sUserManager.isInitialized(userId)) { 4253 MountServiceInternal mountServiceInternal = LocalServices.getService( 4254 MountServiceInternal.class); 4255 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 4256 } 4257 } finally { 4258 Binder.restoreCallingIdentity(token); 4259 } 4260 } 4261 } 4262 4263 @Override 4264 public void revokeRuntimePermission(String packageName, String name, int userId) { 4265 if (!sUserManager.exists(userId)) { 4266 Log.e(TAG, "No such user:" + userId); 4267 return; 4268 } 4269 4270 mContext.enforceCallingOrSelfPermission( 4271 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4272 "revokeRuntimePermission"); 4273 4274 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4275 true /* requireFullPermission */, true /* checkShell */, 4276 "revokeRuntimePermission"); 4277 4278 final int appId; 4279 4280 synchronized (mPackages) { 4281 final PackageParser.Package pkg = mPackages.get(packageName); 4282 if (pkg == null) { 4283 throw new IllegalArgumentException("Unknown package: " + packageName); 4284 } 4285 4286 final BasePermission bp = mSettings.mPermissions.get(name); 4287 if (bp == null) { 4288 throw new IllegalArgumentException("Unknown permission: " + name); 4289 } 4290 4291 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4292 4293 // If a permission review is required for legacy apps we represent 4294 // their permissions as always granted runtime ones since we need 4295 // to keep the review required permission flag per user while an 4296 // install permission's state is shared across all users. 4297 if (Build.PERMISSIONS_REVIEW_REQUIRED 4298 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4299 && bp.isRuntime()) { 4300 return; 4301 } 4302 4303 SettingBase sb = (SettingBase) pkg.mExtras; 4304 if (sb == null) { 4305 throw new IllegalArgumentException("Unknown package: " + packageName); 4306 } 4307 4308 final PermissionsState permissionsState = sb.getPermissionsState(); 4309 4310 final int flags = permissionsState.getPermissionFlags(name, userId); 4311 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4312 throw new SecurityException("Cannot revoke system fixed permission " 4313 + name + " for package " + packageName); 4314 } 4315 4316 if (bp.isDevelopment()) { 4317 // Development permissions must be handled specially, since they are not 4318 // normal runtime permissions. For now they apply to all users. 4319 if (permissionsState.revokeInstallPermission(bp) != 4320 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4321 scheduleWriteSettingsLocked(); 4322 } 4323 return; 4324 } 4325 4326 if (permissionsState.revokeRuntimePermission(bp, userId) == 4327 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4328 return; 4329 } 4330 4331 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4332 4333 // Critical, after this call app should never have the permission. 4334 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4335 4336 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4337 } 4338 4339 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4340 } 4341 4342 @Override 4343 public void resetRuntimePermissions() { 4344 mContext.enforceCallingOrSelfPermission( 4345 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4346 "revokeRuntimePermission"); 4347 4348 int callingUid = Binder.getCallingUid(); 4349 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4350 mContext.enforceCallingOrSelfPermission( 4351 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4352 "resetRuntimePermissions"); 4353 } 4354 4355 synchronized (mPackages) { 4356 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4357 for (int userId : UserManagerService.getInstance().getUserIds()) { 4358 final int packageCount = mPackages.size(); 4359 for (int i = 0; i < packageCount; i++) { 4360 PackageParser.Package pkg = mPackages.valueAt(i); 4361 if (!(pkg.mExtras instanceof PackageSetting)) { 4362 continue; 4363 } 4364 PackageSetting ps = (PackageSetting) pkg.mExtras; 4365 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4366 } 4367 } 4368 } 4369 } 4370 4371 @Override 4372 public int getPermissionFlags(String name, String packageName, int userId) { 4373 if (!sUserManager.exists(userId)) { 4374 return 0; 4375 } 4376 4377 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4378 4379 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4380 true /* requireFullPermission */, false /* checkShell */, 4381 "getPermissionFlags"); 4382 4383 synchronized (mPackages) { 4384 final PackageParser.Package pkg = mPackages.get(packageName); 4385 if (pkg == null) { 4386 return 0; 4387 } 4388 4389 final BasePermission bp = mSettings.mPermissions.get(name); 4390 if (bp == null) { 4391 return 0; 4392 } 4393 4394 SettingBase sb = (SettingBase) pkg.mExtras; 4395 if (sb == null) { 4396 return 0; 4397 } 4398 4399 PermissionsState permissionsState = sb.getPermissionsState(); 4400 return permissionsState.getPermissionFlags(name, userId); 4401 } 4402 } 4403 4404 @Override 4405 public void updatePermissionFlags(String name, String packageName, int flagMask, 4406 int flagValues, int userId) { 4407 if (!sUserManager.exists(userId)) { 4408 return; 4409 } 4410 4411 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4412 4413 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4414 true /* requireFullPermission */, true /* checkShell */, 4415 "updatePermissionFlags"); 4416 4417 // Only the system can change these flags and nothing else. 4418 if (getCallingUid() != Process.SYSTEM_UID) { 4419 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4420 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4421 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4422 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4423 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4424 } 4425 4426 synchronized (mPackages) { 4427 final PackageParser.Package pkg = mPackages.get(packageName); 4428 if (pkg == null) { 4429 throw new IllegalArgumentException("Unknown package: " + packageName); 4430 } 4431 4432 final BasePermission bp = mSettings.mPermissions.get(name); 4433 if (bp == null) { 4434 throw new IllegalArgumentException("Unknown permission: " + name); 4435 } 4436 4437 SettingBase sb = (SettingBase) pkg.mExtras; 4438 if (sb == null) { 4439 throw new IllegalArgumentException("Unknown package: " + packageName); 4440 } 4441 4442 PermissionsState permissionsState = sb.getPermissionsState(); 4443 4444 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4445 4446 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4447 // Install and runtime permissions are stored in different places, 4448 // so figure out what permission changed and persist the change. 4449 if (permissionsState.getInstallPermissionState(name) != null) { 4450 scheduleWriteSettingsLocked(); 4451 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4452 || hadState) { 4453 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4454 } 4455 } 4456 } 4457 } 4458 4459 /** 4460 * Update the permission flags for all packages and runtime permissions of a user in order 4461 * to allow device or profile owner to remove POLICY_FIXED. 4462 */ 4463 @Override 4464 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4465 if (!sUserManager.exists(userId)) { 4466 return; 4467 } 4468 4469 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4470 4471 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4472 true /* requireFullPermission */, true /* checkShell */, 4473 "updatePermissionFlagsForAllApps"); 4474 4475 // Only the system can change system fixed flags. 4476 if (getCallingUid() != Process.SYSTEM_UID) { 4477 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4478 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4479 } 4480 4481 synchronized (mPackages) { 4482 boolean changed = false; 4483 final int packageCount = mPackages.size(); 4484 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4485 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4486 SettingBase sb = (SettingBase) pkg.mExtras; 4487 if (sb == null) { 4488 continue; 4489 } 4490 PermissionsState permissionsState = sb.getPermissionsState(); 4491 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4492 userId, flagMask, flagValues); 4493 } 4494 if (changed) { 4495 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4496 } 4497 } 4498 } 4499 4500 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4501 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4502 != PackageManager.PERMISSION_GRANTED 4503 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4504 != PackageManager.PERMISSION_GRANTED) { 4505 throw new SecurityException(message + " requires " 4506 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4507 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4508 } 4509 } 4510 4511 @Override 4512 public boolean shouldShowRequestPermissionRationale(String permissionName, 4513 String packageName, int userId) { 4514 if (UserHandle.getCallingUserId() != userId) { 4515 mContext.enforceCallingPermission( 4516 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4517 "canShowRequestPermissionRationale for user " + userId); 4518 } 4519 4520 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4521 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4522 return false; 4523 } 4524 4525 if (checkPermission(permissionName, packageName, userId) 4526 == PackageManager.PERMISSION_GRANTED) { 4527 return false; 4528 } 4529 4530 final int flags; 4531 4532 final long identity = Binder.clearCallingIdentity(); 4533 try { 4534 flags = getPermissionFlags(permissionName, 4535 packageName, userId); 4536 } finally { 4537 Binder.restoreCallingIdentity(identity); 4538 } 4539 4540 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4541 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4542 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4543 4544 if ((flags & fixedFlags) != 0) { 4545 return false; 4546 } 4547 4548 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4549 } 4550 4551 @Override 4552 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4553 mContext.enforceCallingOrSelfPermission( 4554 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4555 "addOnPermissionsChangeListener"); 4556 4557 synchronized (mPackages) { 4558 mOnPermissionChangeListeners.addListenerLocked(listener); 4559 } 4560 } 4561 4562 @Override 4563 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4564 synchronized (mPackages) { 4565 mOnPermissionChangeListeners.removeListenerLocked(listener); 4566 } 4567 } 4568 4569 @Override 4570 public boolean isProtectedBroadcast(String actionName) { 4571 synchronized (mPackages) { 4572 if (mProtectedBroadcasts.contains(actionName)) { 4573 return true; 4574 } else if (actionName != null) { 4575 // TODO: remove these terrible hacks 4576 if (actionName.startsWith("android.net.netmon.lingerExpired") 4577 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4578 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 4579 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 4580 return true; 4581 } 4582 } 4583 } 4584 return false; 4585 } 4586 4587 @Override 4588 public int checkSignatures(String pkg1, String pkg2) { 4589 synchronized (mPackages) { 4590 final PackageParser.Package p1 = mPackages.get(pkg1); 4591 final PackageParser.Package p2 = mPackages.get(pkg2); 4592 if (p1 == null || p1.mExtras == null 4593 || p2 == null || p2.mExtras == null) { 4594 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4595 } 4596 return compareSignatures(p1.mSignatures, p2.mSignatures); 4597 } 4598 } 4599 4600 @Override 4601 public int checkUidSignatures(int uid1, int uid2) { 4602 // Map to base uids. 4603 uid1 = UserHandle.getAppId(uid1); 4604 uid2 = UserHandle.getAppId(uid2); 4605 // reader 4606 synchronized (mPackages) { 4607 Signature[] s1; 4608 Signature[] s2; 4609 Object obj = mSettings.getUserIdLPr(uid1); 4610 if (obj != null) { 4611 if (obj instanceof SharedUserSetting) { 4612 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4613 } else if (obj instanceof PackageSetting) { 4614 s1 = ((PackageSetting)obj).signatures.mSignatures; 4615 } else { 4616 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4617 } 4618 } else { 4619 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4620 } 4621 obj = mSettings.getUserIdLPr(uid2); 4622 if (obj != null) { 4623 if (obj instanceof SharedUserSetting) { 4624 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4625 } else if (obj instanceof PackageSetting) { 4626 s2 = ((PackageSetting)obj).signatures.mSignatures; 4627 } else { 4628 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4629 } 4630 } else { 4631 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4632 } 4633 return compareSignatures(s1, s2); 4634 } 4635 } 4636 4637 /** 4638 * This method should typically only be used when granting or revoking 4639 * permissions, since the app may immediately restart after this call. 4640 * <p> 4641 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 4642 * guard your work against the app being relaunched. 4643 */ 4644 private void killUid(int appId, int userId, String reason) { 4645 final long identity = Binder.clearCallingIdentity(); 4646 try { 4647 IActivityManager am = ActivityManagerNative.getDefault(); 4648 if (am != null) { 4649 try { 4650 am.killUid(appId, userId, reason); 4651 } catch (RemoteException e) { 4652 /* ignore - same process */ 4653 } 4654 } 4655 } finally { 4656 Binder.restoreCallingIdentity(identity); 4657 } 4658 } 4659 4660 /** 4661 * Compares two sets of signatures. Returns: 4662 * <br /> 4663 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4664 * <br /> 4665 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4666 * <br /> 4667 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4668 * <br /> 4669 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4670 * <br /> 4671 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4672 */ 4673 static int compareSignatures(Signature[] s1, Signature[] s2) { 4674 if (s1 == null) { 4675 return s2 == null 4676 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4677 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4678 } 4679 4680 if (s2 == null) { 4681 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4682 } 4683 4684 if (s1.length != s2.length) { 4685 return PackageManager.SIGNATURE_NO_MATCH; 4686 } 4687 4688 // Since both signature sets are of size 1, we can compare without HashSets. 4689 if (s1.length == 1) { 4690 return s1[0].equals(s2[0]) ? 4691 PackageManager.SIGNATURE_MATCH : 4692 PackageManager.SIGNATURE_NO_MATCH; 4693 } 4694 4695 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4696 for (Signature sig : s1) { 4697 set1.add(sig); 4698 } 4699 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4700 for (Signature sig : s2) { 4701 set2.add(sig); 4702 } 4703 // Make sure s2 contains all signatures in s1. 4704 if (set1.equals(set2)) { 4705 return PackageManager.SIGNATURE_MATCH; 4706 } 4707 return PackageManager.SIGNATURE_NO_MATCH; 4708 } 4709 4710 /** 4711 * If the database version for this type of package (internal storage or 4712 * external storage) is less than the version where package signatures 4713 * were updated, return true. 4714 */ 4715 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4716 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4717 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4718 } 4719 4720 /** 4721 * Used for backward compatibility to make sure any packages with 4722 * certificate chains get upgraded to the new style. {@code existingSigs} 4723 * will be in the old format (since they were stored on disk from before the 4724 * system upgrade) and {@code scannedSigs} will be in the newer format. 4725 */ 4726 private int compareSignaturesCompat(PackageSignatures existingSigs, 4727 PackageParser.Package scannedPkg) { 4728 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4729 return PackageManager.SIGNATURE_NO_MATCH; 4730 } 4731 4732 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4733 for (Signature sig : existingSigs.mSignatures) { 4734 existingSet.add(sig); 4735 } 4736 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4737 for (Signature sig : scannedPkg.mSignatures) { 4738 try { 4739 Signature[] chainSignatures = sig.getChainSignatures(); 4740 for (Signature chainSig : chainSignatures) { 4741 scannedCompatSet.add(chainSig); 4742 } 4743 } catch (CertificateEncodingException e) { 4744 scannedCompatSet.add(sig); 4745 } 4746 } 4747 /* 4748 * Make sure the expanded scanned set contains all signatures in the 4749 * existing one. 4750 */ 4751 if (scannedCompatSet.equals(existingSet)) { 4752 // Migrate the old signatures to the new scheme. 4753 existingSigs.assignSignatures(scannedPkg.mSignatures); 4754 // The new KeySets will be re-added later in the scanning process. 4755 synchronized (mPackages) { 4756 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4757 } 4758 return PackageManager.SIGNATURE_MATCH; 4759 } 4760 return PackageManager.SIGNATURE_NO_MATCH; 4761 } 4762 4763 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4764 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4765 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4766 } 4767 4768 private int compareSignaturesRecover(PackageSignatures existingSigs, 4769 PackageParser.Package scannedPkg) { 4770 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4771 return PackageManager.SIGNATURE_NO_MATCH; 4772 } 4773 4774 String msg = null; 4775 try { 4776 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4777 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4778 + scannedPkg.packageName); 4779 return PackageManager.SIGNATURE_MATCH; 4780 } 4781 } catch (CertificateException e) { 4782 msg = e.getMessage(); 4783 } 4784 4785 logCriticalInfo(Log.INFO, 4786 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4787 return PackageManager.SIGNATURE_NO_MATCH; 4788 } 4789 4790 @Override 4791 public List<String> getAllPackages() { 4792 synchronized (mPackages) { 4793 return new ArrayList<String>(mPackages.keySet()); 4794 } 4795 } 4796 4797 @Override 4798 public String[] getPackagesForUid(int uid) { 4799 uid = UserHandle.getAppId(uid); 4800 // reader 4801 synchronized (mPackages) { 4802 Object obj = mSettings.getUserIdLPr(uid); 4803 if (obj instanceof SharedUserSetting) { 4804 final SharedUserSetting sus = (SharedUserSetting) obj; 4805 final int N = sus.packages.size(); 4806 final String[] res = new String[N]; 4807 for (int i = 0; i < N; i++) { 4808 res[i] = sus.packages.valueAt(i).name; 4809 } 4810 return res; 4811 } else if (obj instanceof PackageSetting) { 4812 final PackageSetting ps = (PackageSetting) obj; 4813 return new String[] { ps.name }; 4814 } 4815 } 4816 return null; 4817 } 4818 4819 @Override 4820 public String getNameForUid(int uid) { 4821 // reader 4822 synchronized (mPackages) { 4823 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4824 if (obj instanceof SharedUserSetting) { 4825 final SharedUserSetting sus = (SharedUserSetting) obj; 4826 return sus.name + ":" + sus.userId; 4827 } else if (obj instanceof PackageSetting) { 4828 final PackageSetting ps = (PackageSetting) obj; 4829 return ps.name; 4830 } 4831 } 4832 return null; 4833 } 4834 4835 @Override 4836 public int getUidForSharedUser(String sharedUserName) { 4837 if(sharedUserName == null) { 4838 return -1; 4839 } 4840 // reader 4841 synchronized (mPackages) { 4842 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4843 if (suid == null) { 4844 return -1; 4845 } 4846 return suid.userId; 4847 } 4848 } 4849 4850 @Override 4851 public int getFlagsForUid(int uid) { 4852 synchronized (mPackages) { 4853 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4854 if (obj instanceof SharedUserSetting) { 4855 final SharedUserSetting sus = (SharedUserSetting) obj; 4856 return sus.pkgFlags; 4857 } else if (obj instanceof PackageSetting) { 4858 final PackageSetting ps = (PackageSetting) obj; 4859 return ps.pkgFlags; 4860 } 4861 } 4862 return 0; 4863 } 4864 4865 @Override 4866 public int getPrivateFlagsForUid(int uid) { 4867 synchronized (mPackages) { 4868 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4869 if (obj instanceof SharedUserSetting) { 4870 final SharedUserSetting sus = (SharedUserSetting) obj; 4871 return sus.pkgPrivateFlags; 4872 } else if (obj instanceof PackageSetting) { 4873 final PackageSetting ps = (PackageSetting) obj; 4874 return ps.pkgPrivateFlags; 4875 } 4876 } 4877 return 0; 4878 } 4879 4880 @Override 4881 public boolean isUidPrivileged(int uid) { 4882 uid = UserHandle.getAppId(uid); 4883 // reader 4884 synchronized (mPackages) { 4885 Object obj = mSettings.getUserIdLPr(uid); 4886 if (obj instanceof SharedUserSetting) { 4887 final SharedUserSetting sus = (SharedUserSetting) obj; 4888 final Iterator<PackageSetting> it = sus.packages.iterator(); 4889 while (it.hasNext()) { 4890 if (it.next().isPrivileged()) { 4891 return true; 4892 } 4893 } 4894 } else if (obj instanceof PackageSetting) { 4895 final PackageSetting ps = (PackageSetting) obj; 4896 return ps.isPrivileged(); 4897 } 4898 } 4899 return false; 4900 } 4901 4902 @Override 4903 public String[] getAppOpPermissionPackages(String permissionName) { 4904 synchronized (mPackages) { 4905 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4906 if (pkgs == null) { 4907 return null; 4908 } 4909 return pkgs.toArray(new String[pkgs.size()]); 4910 } 4911 } 4912 4913 @Override 4914 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4915 int flags, int userId) { 4916 try { 4917 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 4918 4919 if (!sUserManager.exists(userId)) return null; 4920 flags = updateFlagsForResolve(flags, userId, intent); 4921 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4922 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 4923 4924 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 4925 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 4926 flags, userId); 4927 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4928 4929 final ResolveInfo bestChoice = 4930 chooseBestActivity(intent, resolvedType, flags, query, userId); 4931 4932 if (isEphemeralAllowed(intent, query, userId)) { 4933 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 4934 final EphemeralResolveInfo ai = 4935 getEphemeralResolveInfo(intent, resolvedType, userId); 4936 if (ai != null) { 4937 if (DEBUG_EPHEMERAL) { 4938 Slog.v(TAG, "Returning an EphemeralResolveInfo"); 4939 } 4940 bestChoice.ephemeralInstaller = mEphemeralInstallerInfo; 4941 bestChoice.ephemeralResolveInfo = ai; 4942 } 4943 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4944 } 4945 return bestChoice; 4946 } finally { 4947 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4948 } 4949 } 4950 4951 @Override 4952 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4953 IntentFilter filter, int match, ComponentName activity) { 4954 final int userId = UserHandle.getCallingUserId(); 4955 if (DEBUG_PREFERRED) { 4956 Log.v(TAG, "setLastChosenActivity intent=" + intent 4957 + " resolvedType=" + resolvedType 4958 + " flags=" + flags 4959 + " filter=" + filter 4960 + " match=" + match 4961 + " activity=" + activity); 4962 filter.dump(new PrintStreamPrinter(System.out), " "); 4963 } 4964 intent.setComponent(null); 4965 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4966 userId); 4967 // Find any earlier preferred or last chosen entries and nuke them 4968 findPreferredActivity(intent, resolvedType, 4969 flags, query, 0, false, true, false, userId); 4970 // Add the new activity as the last chosen for this filter 4971 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4972 "Setting last chosen"); 4973 } 4974 4975 @Override 4976 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4977 final int userId = UserHandle.getCallingUserId(); 4978 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4979 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4980 userId); 4981 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4982 false, false, false, userId); 4983 } 4984 4985 4986 private boolean isEphemeralAllowed( 4987 Intent intent, List<ResolveInfo> resolvedActivites, int userId) { 4988 // Short circuit and return early if possible. 4989 if (DISABLE_EPHEMERAL_APPS) { 4990 return false; 4991 } 4992 final int callingUser = UserHandle.getCallingUserId(); 4993 if (callingUser != UserHandle.USER_SYSTEM) { 4994 return false; 4995 } 4996 if (mEphemeralResolverConnection == null) { 4997 return false; 4998 } 4999 if (intent.getComponent() != null) { 5000 return false; 5001 } 5002 if (intent.getPackage() != null) { 5003 return false; 5004 } 5005 final boolean isWebUri = hasWebURI(intent); 5006 if (!isWebUri) { 5007 return false; 5008 } 5009 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 5010 synchronized (mPackages) { 5011 final int count = resolvedActivites.size(); 5012 for (int n = 0; n < count; n++) { 5013 ResolveInfo info = resolvedActivites.get(n); 5014 String packageName = info.activityInfo.packageName; 5015 PackageSetting ps = mSettings.mPackages.get(packageName); 5016 if (ps != null) { 5017 // Try to get the status from User settings first 5018 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5019 int status = (int) (packedStatus >> 32); 5020 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 5021 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5022 if (DEBUG_EPHEMERAL) { 5023 Slog.v(TAG, "DENY ephemeral apps;" 5024 + " pkg: " + packageName + ", status: " + status); 5025 } 5026 return false; 5027 } 5028 } 5029 } 5030 } 5031 // We've exhausted all ways to deny ephemeral application; let the system look for them. 5032 return true; 5033 } 5034 5035 private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType, 5036 int userId) { 5037 final int ephemeralPrefixMask = Global.getInt(mContext.getContentResolver(), 5038 Global.EPHEMERAL_HASH_PREFIX_MASK, DEFAULT_EPHEMERAL_HASH_PREFIX_MASK); 5039 final int ephemeralPrefixCount = Global.getInt(mContext.getContentResolver(), 5040 Global.EPHEMERAL_HASH_PREFIX_COUNT, DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT); 5041 final EphemeralDigest digest = new EphemeralDigest(intent.getData(), ephemeralPrefixMask, 5042 ephemeralPrefixCount); 5043 final int[] shaPrefix = digest.getDigestPrefix(); 5044 final byte[][] digestBytes = digest.getDigestBytes(); 5045 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 5046 mEphemeralResolverConnection.getEphemeralResolveInfoList( 5047 shaPrefix, ephemeralPrefixMask); 5048 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 5049 // No hash prefix match; there are no ephemeral apps for this domain. 5050 return null; 5051 } 5052 5053 // Go in reverse order so we match the narrowest scope first. 5054 for (int i = shaPrefix.length - 1; i >= 0 ; --i) { 5055 for (EphemeralResolveInfo ephemeralApplication : ephemeralResolveInfoList) { 5056 if (!Arrays.equals(digestBytes[i], ephemeralApplication.getDigestBytes())) { 5057 continue; 5058 } 5059 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 5060 // No filters; this should never happen. 5061 if (filters.isEmpty()) { 5062 continue; 5063 } 5064 // We have a domain match; resolve the filters to see if anything matches. 5065 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 5066 for (int j = filters.size() - 1; j >= 0; --j) { 5067 final EphemeralResolveIntentInfo intentInfo = 5068 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 5069 ephemeralResolver.addFilter(intentInfo); 5070 } 5071 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 5072 intent, resolvedType, false /*defaultOnly*/, userId); 5073 if (!matchedResolveInfoList.isEmpty()) { 5074 return matchedResolveInfoList.get(0); 5075 } 5076 } 5077 } 5078 // Hash or filter mis-match; no ephemeral apps for this domain. 5079 return null; 5080 } 5081 5082 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 5083 int flags, List<ResolveInfo> query, int userId) { 5084 if (query != null) { 5085 final int N = query.size(); 5086 if (N == 1) { 5087 return query.get(0); 5088 } else if (N > 1) { 5089 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 5090 // If there is more than one activity with the same priority, 5091 // then let the user decide between them. 5092 ResolveInfo r0 = query.get(0); 5093 ResolveInfo r1 = query.get(1); 5094 if (DEBUG_INTENT_MATCHING || debug) { 5095 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 5096 + r1.activityInfo.name + "=" + r1.priority); 5097 } 5098 // If the first activity has a higher priority, or a different 5099 // default, then it is always desirable to pick it. 5100 if (r0.priority != r1.priority 5101 || r0.preferredOrder != r1.preferredOrder 5102 || r0.isDefault != r1.isDefault) { 5103 return query.get(0); 5104 } 5105 // If we have saved a preference for a preferred activity for 5106 // this Intent, use that. 5107 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 5108 flags, query, r0.priority, true, false, debug, userId); 5109 if (ri != null) { 5110 return ri; 5111 } 5112 ri = new ResolveInfo(mResolveInfo); 5113 ri.activityInfo = new ActivityInfo(ri.activityInfo); 5114 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 5115 // If all of the options come from the same package, show the application's 5116 // label and icon instead of the generic resolver's. 5117 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 5118 // and then throw away the ResolveInfo itself, meaning that the caller loses 5119 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 5120 // a fallback for this case; we only set the target package's resources on 5121 // the ResolveInfo, not the ActivityInfo. 5122 final String intentPackage = intent.getPackage(); 5123 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 5124 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 5125 ri.resolvePackageName = intentPackage; 5126 if (userNeedsBadging(userId)) { 5127 ri.noResourceId = true; 5128 } else { 5129 ri.icon = appi.icon; 5130 } 5131 ri.iconResourceId = appi.icon; 5132 ri.labelRes = appi.labelRes; 5133 } 5134 ri.activityInfo.applicationInfo = new ApplicationInfo( 5135 ri.activityInfo.applicationInfo); 5136 if (userId != 0) { 5137 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 5138 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 5139 } 5140 // Make sure that the resolver is displayable in car mode 5141 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 5142 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 5143 return ri; 5144 } 5145 } 5146 return null; 5147 } 5148 5149 /** 5150 * Return true if the given list is not empty and all of its contents have 5151 * an activityInfo with the given package name. 5152 */ 5153 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 5154 if (ArrayUtils.isEmpty(list)) { 5155 return false; 5156 } 5157 for (int i = 0, N = list.size(); i < N; i++) { 5158 final ResolveInfo ri = list.get(i); 5159 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 5160 if (ai == null || !packageName.equals(ai.packageName)) { 5161 return false; 5162 } 5163 } 5164 return true; 5165 } 5166 5167 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 5168 int flags, List<ResolveInfo> query, boolean debug, int userId) { 5169 final int N = query.size(); 5170 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 5171 .get(userId); 5172 // Get the list of persistent preferred activities that handle the intent 5173 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 5174 List<PersistentPreferredActivity> pprefs = ppir != null 5175 ? ppir.queryIntent(intent, resolvedType, 5176 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5177 : null; 5178 if (pprefs != null && pprefs.size() > 0) { 5179 final int M = pprefs.size(); 5180 for (int i=0; i<M; i++) { 5181 final PersistentPreferredActivity ppa = pprefs.get(i); 5182 if (DEBUG_PREFERRED || debug) { 5183 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 5184 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 5185 + "\n component=" + ppa.mComponent); 5186 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5187 } 5188 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 5189 flags | MATCH_DISABLED_COMPONENTS, userId); 5190 if (DEBUG_PREFERRED || debug) { 5191 Slog.v(TAG, "Found persistent preferred activity:"); 5192 if (ai != null) { 5193 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5194 } else { 5195 Slog.v(TAG, " null"); 5196 } 5197 } 5198 if (ai == null) { 5199 // This previously registered persistent preferred activity 5200 // component is no longer known. Ignore it and do NOT remove it. 5201 continue; 5202 } 5203 for (int j=0; j<N; j++) { 5204 final ResolveInfo ri = query.get(j); 5205 if (!ri.activityInfo.applicationInfo.packageName 5206 .equals(ai.applicationInfo.packageName)) { 5207 continue; 5208 } 5209 if (!ri.activityInfo.name.equals(ai.name)) { 5210 continue; 5211 } 5212 // Found a persistent preference that can handle the intent. 5213 if (DEBUG_PREFERRED || debug) { 5214 Slog.v(TAG, "Returning persistent preferred activity: " + 5215 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5216 } 5217 return ri; 5218 } 5219 } 5220 } 5221 return null; 5222 } 5223 5224 // TODO: handle preferred activities missing while user has amnesia 5225 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5226 List<ResolveInfo> query, int priority, boolean always, 5227 boolean removeMatches, boolean debug, int userId) { 5228 if (!sUserManager.exists(userId)) return null; 5229 flags = updateFlagsForResolve(flags, userId, intent); 5230 // writer 5231 synchronized (mPackages) { 5232 if (intent.getSelector() != null) { 5233 intent = intent.getSelector(); 5234 } 5235 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 5236 5237 // Try to find a matching persistent preferred activity. 5238 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5239 debug, userId); 5240 5241 // If a persistent preferred activity matched, use it. 5242 if (pri != null) { 5243 return pri; 5244 } 5245 5246 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5247 // Get the list of preferred activities that handle the intent 5248 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5249 List<PreferredActivity> prefs = pir != null 5250 ? pir.queryIntent(intent, resolvedType, 5251 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5252 : null; 5253 if (prefs != null && prefs.size() > 0) { 5254 boolean changed = false; 5255 try { 5256 // First figure out how good the original match set is. 5257 // We will only allow preferred activities that came 5258 // from the same match quality. 5259 int match = 0; 5260 5261 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5262 5263 final int N = query.size(); 5264 for (int j=0; j<N; j++) { 5265 final ResolveInfo ri = query.get(j); 5266 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5267 + ": 0x" + Integer.toHexString(match)); 5268 if (ri.match > match) { 5269 match = ri.match; 5270 } 5271 } 5272 5273 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5274 + Integer.toHexString(match)); 5275 5276 match &= IntentFilter.MATCH_CATEGORY_MASK; 5277 final int M = prefs.size(); 5278 for (int i=0; i<M; i++) { 5279 final PreferredActivity pa = prefs.get(i); 5280 if (DEBUG_PREFERRED || debug) { 5281 Slog.v(TAG, "Checking PreferredActivity ds=" 5282 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5283 + "\n component=" + pa.mPref.mComponent); 5284 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5285 } 5286 if (pa.mPref.mMatch != match) { 5287 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5288 + Integer.toHexString(pa.mPref.mMatch)); 5289 continue; 5290 } 5291 // If it's not an "always" type preferred activity and that's what we're 5292 // looking for, skip it. 5293 if (always && !pa.mPref.mAlways) { 5294 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5295 continue; 5296 } 5297 final ActivityInfo ai = getActivityInfo( 5298 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5299 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5300 userId); 5301 if (DEBUG_PREFERRED || debug) { 5302 Slog.v(TAG, "Found preferred activity:"); 5303 if (ai != null) { 5304 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5305 } else { 5306 Slog.v(TAG, " null"); 5307 } 5308 } 5309 if (ai == null) { 5310 // This previously registered preferred activity 5311 // component is no longer known. Most likely an update 5312 // to the app was installed and in the new version this 5313 // component no longer exists. Clean it up by removing 5314 // it from the preferred activities list, and skip it. 5315 Slog.w(TAG, "Removing dangling preferred activity: " 5316 + pa.mPref.mComponent); 5317 pir.removeFilter(pa); 5318 changed = true; 5319 continue; 5320 } 5321 for (int j=0; j<N; j++) { 5322 final ResolveInfo ri = query.get(j); 5323 if (!ri.activityInfo.applicationInfo.packageName 5324 .equals(ai.applicationInfo.packageName)) { 5325 continue; 5326 } 5327 if (!ri.activityInfo.name.equals(ai.name)) { 5328 continue; 5329 } 5330 5331 if (removeMatches) { 5332 pir.removeFilter(pa); 5333 changed = true; 5334 if (DEBUG_PREFERRED) { 5335 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 5336 } 5337 break; 5338 } 5339 5340 // Okay we found a previously set preferred or last chosen app. 5341 // If the result set is different from when this 5342 // was created, we need to clear it and re-ask the 5343 // user their preference, if we're looking for an "always" type entry. 5344 if (always && !pa.mPref.sameSet(query)) { 5345 Slog.i(TAG, "Result set changed, dropping preferred activity for " 5346 + intent + " type " + resolvedType); 5347 if (DEBUG_PREFERRED) { 5348 Slog.v(TAG, "Removing preferred activity since set changed " 5349 + pa.mPref.mComponent); 5350 } 5351 pir.removeFilter(pa); 5352 // Re-add the filter as a "last chosen" entry (!always) 5353 PreferredActivity lastChosen = new PreferredActivity( 5354 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5355 pir.addFilter(lastChosen); 5356 changed = true; 5357 return null; 5358 } 5359 5360 // Yay! Either the set matched or we're looking for the last chosen 5361 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5362 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5363 return ri; 5364 } 5365 } 5366 } finally { 5367 if (changed) { 5368 if (DEBUG_PREFERRED) { 5369 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5370 } 5371 scheduleWritePackageRestrictionsLocked(userId); 5372 } 5373 } 5374 } 5375 } 5376 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5377 return null; 5378 } 5379 5380 /* 5381 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5382 */ 5383 @Override 5384 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5385 int targetUserId) { 5386 mContext.enforceCallingOrSelfPermission( 5387 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5388 List<CrossProfileIntentFilter> matches = 5389 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5390 if (matches != null) { 5391 int size = matches.size(); 5392 for (int i = 0; i < size; i++) { 5393 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5394 } 5395 } 5396 if (hasWebURI(intent)) { 5397 // cross-profile app linking works only towards the parent. 5398 final UserInfo parent = getProfileParent(sourceUserId); 5399 synchronized(mPackages) { 5400 int flags = updateFlagsForResolve(0, parent.id, intent); 5401 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5402 intent, resolvedType, flags, sourceUserId, parent.id); 5403 return xpDomainInfo != null; 5404 } 5405 } 5406 return false; 5407 } 5408 5409 private UserInfo getProfileParent(int userId) { 5410 final long identity = Binder.clearCallingIdentity(); 5411 try { 5412 return sUserManager.getProfileParent(userId); 5413 } finally { 5414 Binder.restoreCallingIdentity(identity); 5415 } 5416 } 5417 5418 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5419 String resolvedType, int userId) { 5420 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5421 if (resolver != null) { 5422 return resolver.queryIntent(intent, resolvedType, false, userId); 5423 } 5424 return null; 5425 } 5426 5427 @Override 5428 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5429 String resolvedType, int flags, int userId) { 5430 try { 5431 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5432 5433 return new ParceledListSlice<>( 5434 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5435 } finally { 5436 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5437 } 5438 } 5439 5440 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5441 String resolvedType, int flags, int userId) { 5442 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5443 flags = updateFlagsForResolve(flags, userId, intent); 5444 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5445 false /* requireFullPermission */, false /* checkShell */, 5446 "query intent activities"); 5447 ComponentName comp = intent.getComponent(); 5448 if (comp == null) { 5449 if (intent.getSelector() != null) { 5450 intent = intent.getSelector(); 5451 comp = intent.getComponent(); 5452 } 5453 } 5454 5455 if (comp != null) { 5456 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5457 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5458 if (ai != null) { 5459 final ResolveInfo ri = new ResolveInfo(); 5460 ri.activityInfo = ai; 5461 list.add(ri); 5462 } 5463 return list; 5464 } 5465 5466 // reader 5467 synchronized (mPackages) { 5468 final String pkgName = intent.getPackage(); 5469 if (pkgName == null) { 5470 List<CrossProfileIntentFilter> matchingFilters = 5471 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5472 // Check for results that need to skip the current profile. 5473 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5474 resolvedType, flags, userId); 5475 if (xpResolveInfo != null) { 5476 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 5477 result.add(xpResolveInfo); 5478 return filterIfNotSystemUser(result, userId); 5479 } 5480 5481 // Check for results in the current profile. 5482 List<ResolveInfo> result = mActivities.queryIntent( 5483 intent, resolvedType, flags, userId); 5484 result = filterIfNotSystemUser(result, userId); 5485 5486 // Check for cross profile results. 5487 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5488 xpResolveInfo = queryCrossProfileIntents( 5489 matchingFilters, intent, resolvedType, flags, userId, 5490 hasNonNegativePriorityResult); 5491 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5492 boolean isVisibleToUser = filterIfNotSystemUser( 5493 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5494 if (isVisibleToUser) { 5495 result.add(xpResolveInfo); 5496 Collections.sort(result, mResolvePrioritySorter); 5497 } 5498 } 5499 if (hasWebURI(intent)) { 5500 CrossProfileDomainInfo xpDomainInfo = null; 5501 final UserInfo parent = getProfileParent(userId); 5502 if (parent != null) { 5503 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5504 flags, userId, parent.id); 5505 } 5506 if (xpDomainInfo != null) { 5507 if (xpResolveInfo != null) { 5508 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5509 // in the result. 5510 result.remove(xpResolveInfo); 5511 } 5512 if (result.size() == 0) { 5513 result.add(xpDomainInfo.resolveInfo); 5514 return result; 5515 } 5516 } else if (result.size() <= 1) { 5517 return result; 5518 } 5519 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 5520 xpDomainInfo, userId); 5521 Collections.sort(result, mResolvePrioritySorter); 5522 } 5523 return result; 5524 } 5525 final PackageParser.Package pkg = mPackages.get(pkgName); 5526 if (pkg != null) { 5527 return filterIfNotSystemUser( 5528 mActivities.queryIntentForPackage( 5529 intent, resolvedType, flags, pkg.activities, userId), 5530 userId); 5531 } 5532 return new ArrayList<ResolveInfo>(); 5533 } 5534 } 5535 5536 private static class CrossProfileDomainInfo { 5537 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5538 ResolveInfo resolveInfo; 5539 /* Best domain verification status of the activities found in the other profile */ 5540 int bestDomainVerificationStatus; 5541 } 5542 5543 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5544 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5545 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5546 sourceUserId)) { 5547 return null; 5548 } 5549 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5550 resolvedType, flags, parentUserId); 5551 5552 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5553 return null; 5554 } 5555 CrossProfileDomainInfo result = null; 5556 int size = resultTargetUser.size(); 5557 for (int i = 0; i < size; i++) { 5558 ResolveInfo riTargetUser = resultTargetUser.get(i); 5559 // Intent filter verification is only for filters that specify a host. So don't return 5560 // those that handle all web uris. 5561 if (riTargetUser.handleAllWebDataURI) { 5562 continue; 5563 } 5564 String packageName = riTargetUser.activityInfo.packageName; 5565 PackageSetting ps = mSettings.mPackages.get(packageName); 5566 if (ps == null) { 5567 continue; 5568 } 5569 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5570 int status = (int)(verificationState >> 32); 5571 if (result == null) { 5572 result = new CrossProfileDomainInfo(); 5573 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5574 sourceUserId, parentUserId); 5575 result.bestDomainVerificationStatus = status; 5576 } else { 5577 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5578 result.bestDomainVerificationStatus); 5579 } 5580 } 5581 // Don't consider matches with status NEVER across profiles. 5582 if (result != null && result.bestDomainVerificationStatus 5583 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5584 return null; 5585 } 5586 return result; 5587 } 5588 5589 /** 5590 * Verification statuses are ordered from the worse to the best, except for 5591 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5592 */ 5593 private int bestDomainVerificationStatus(int status1, int status2) { 5594 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5595 return status2; 5596 } 5597 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5598 return status1; 5599 } 5600 return (int) MathUtils.max(status1, status2); 5601 } 5602 5603 private boolean isUserEnabled(int userId) { 5604 long callingId = Binder.clearCallingIdentity(); 5605 try { 5606 UserInfo userInfo = sUserManager.getUserInfo(userId); 5607 return userInfo != null && userInfo.isEnabled(); 5608 } finally { 5609 Binder.restoreCallingIdentity(callingId); 5610 } 5611 } 5612 5613 /** 5614 * Filter out activities with systemUserOnly flag set, when current user is not System. 5615 * 5616 * @return filtered list 5617 */ 5618 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5619 if (userId == UserHandle.USER_SYSTEM) { 5620 return resolveInfos; 5621 } 5622 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5623 ResolveInfo info = resolveInfos.get(i); 5624 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5625 resolveInfos.remove(i); 5626 } 5627 } 5628 return resolveInfos; 5629 } 5630 5631 /** 5632 * @param resolveInfos list of resolve infos in descending priority order 5633 * @return if the list contains a resolve info with non-negative priority 5634 */ 5635 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5636 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5637 } 5638 5639 private static boolean hasWebURI(Intent intent) { 5640 if (intent.getData() == null) { 5641 return false; 5642 } 5643 final String scheme = intent.getScheme(); 5644 if (TextUtils.isEmpty(scheme)) { 5645 return false; 5646 } 5647 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5648 } 5649 5650 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5651 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5652 int userId) { 5653 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5654 5655 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5656 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5657 candidates.size()); 5658 } 5659 5660 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5661 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5662 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5663 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5664 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5665 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5666 5667 synchronized (mPackages) { 5668 final int count = candidates.size(); 5669 // First, try to use linked apps. Partition the candidates into four lists: 5670 // one for the final results, one for the "do not use ever", one for "undefined status" 5671 // and finally one for "browser app type". 5672 for (int n=0; n<count; n++) { 5673 ResolveInfo info = candidates.get(n); 5674 String packageName = info.activityInfo.packageName; 5675 PackageSetting ps = mSettings.mPackages.get(packageName); 5676 if (ps != null) { 5677 // Add to the special match all list (Browser use case) 5678 if (info.handleAllWebDataURI) { 5679 matchAllList.add(info); 5680 continue; 5681 } 5682 // Try to get the status from User settings first 5683 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5684 int status = (int)(packedStatus >> 32); 5685 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5686 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5687 if (DEBUG_DOMAIN_VERIFICATION) { 5688 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5689 + " : linkgen=" + linkGeneration); 5690 } 5691 // Use link-enabled generation as preferredOrder, i.e. 5692 // prefer newly-enabled over earlier-enabled. 5693 info.preferredOrder = linkGeneration; 5694 alwaysList.add(info); 5695 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5696 if (DEBUG_DOMAIN_VERIFICATION) { 5697 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5698 } 5699 neverList.add(info); 5700 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5701 if (DEBUG_DOMAIN_VERIFICATION) { 5702 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5703 } 5704 alwaysAskList.add(info); 5705 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5706 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5707 if (DEBUG_DOMAIN_VERIFICATION) { 5708 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5709 } 5710 undefinedList.add(info); 5711 } 5712 } 5713 } 5714 5715 // We'll want to include browser possibilities in a few cases 5716 boolean includeBrowser = false; 5717 5718 // First try to add the "always" resolution(s) for the current user, if any 5719 if (alwaysList.size() > 0) { 5720 result.addAll(alwaysList); 5721 } else { 5722 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5723 result.addAll(undefinedList); 5724 // Maybe add one for the other profile. 5725 if (xpDomainInfo != null && ( 5726 xpDomainInfo.bestDomainVerificationStatus 5727 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5728 result.add(xpDomainInfo.resolveInfo); 5729 } 5730 includeBrowser = true; 5731 } 5732 5733 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5734 // If there were 'always' entries their preferred order has been set, so we also 5735 // back that off to make the alternatives equivalent 5736 if (alwaysAskList.size() > 0) { 5737 for (ResolveInfo i : result) { 5738 i.preferredOrder = 0; 5739 } 5740 result.addAll(alwaysAskList); 5741 includeBrowser = true; 5742 } 5743 5744 if (includeBrowser) { 5745 // Also add browsers (all of them or only the default one) 5746 if (DEBUG_DOMAIN_VERIFICATION) { 5747 Slog.v(TAG, " ...including browsers in candidate set"); 5748 } 5749 if ((matchFlags & MATCH_ALL) != 0) { 5750 result.addAll(matchAllList); 5751 } else { 5752 // Browser/generic handling case. If there's a default browser, go straight 5753 // to that (but only if there is no other higher-priority match). 5754 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5755 int maxMatchPrio = 0; 5756 ResolveInfo defaultBrowserMatch = null; 5757 final int numCandidates = matchAllList.size(); 5758 for (int n = 0; n < numCandidates; n++) { 5759 ResolveInfo info = matchAllList.get(n); 5760 // track the highest overall match priority... 5761 if (info.priority > maxMatchPrio) { 5762 maxMatchPrio = info.priority; 5763 } 5764 // ...and the highest-priority default browser match 5765 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5766 if (defaultBrowserMatch == null 5767 || (defaultBrowserMatch.priority < info.priority)) { 5768 if (debug) { 5769 Slog.v(TAG, "Considering default browser match " + info); 5770 } 5771 defaultBrowserMatch = info; 5772 } 5773 } 5774 } 5775 if (defaultBrowserMatch != null 5776 && defaultBrowserMatch.priority >= maxMatchPrio 5777 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5778 { 5779 if (debug) { 5780 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5781 } 5782 result.add(defaultBrowserMatch); 5783 } else { 5784 result.addAll(matchAllList); 5785 } 5786 } 5787 5788 // If there is nothing selected, add all candidates and remove the ones that the user 5789 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5790 if (result.size() == 0) { 5791 result.addAll(candidates); 5792 result.removeAll(neverList); 5793 } 5794 } 5795 } 5796 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5797 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5798 result.size()); 5799 for (ResolveInfo info : result) { 5800 Slog.v(TAG, " + " + info.activityInfo); 5801 } 5802 } 5803 return result; 5804 } 5805 5806 // Returns a packed value as a long: 5807 // 5808 // high 'int'-sized word: link status: undefined/ask/never/always. 5809 // low 'int'-sized word: relative priority among 'always' results. 5810 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5811 long result = ps.getDomainVerificationStatusForUser(userId); 5812 // if none available, get the master status 5813 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5814 if (ps.getIntentFilterVerificationInfo() != null) { 5815 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5816 } 5817 } 5818 return result; 5819 } 5820 5821 private ResolveInfo querySkipCurrentProfileIntents( 5822 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5823 int flags, int sourceUserId) { 5824 if (matchingFilters != null) { 5825 int size = matchingFilters.size(); 5826 for (int i = 0; i < size; i ++) { 5827 CrossProfileIntentFilter filter = matchingFilters.get(i); 5828 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5829 // Checking if there are activities in the target user that can handle the 5830 // intent. 5831 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5832 resolvedType, flags, sourceUserId); 5833 if (resolveInfo != null) { 5834 return resolveInfo; 5835 } 5836 } 5837 } 5838 } 5839 return null; 5840 } 5841 5842 // Return matching ResolveInfo in target user if any. 5843 private ResolveInfo queryCrossProfileIntents( 5844 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5845 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5846 if (matchingFilters != null) { 5847 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5848 // match the same intent. For performance reasons, it is better not to 5849 // run queryIntent twice for the same userId 5850 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5851 int size = matchingFilters.size(); 5852 for (int i = 0; i < size; i++) { 5853 CrossProfileIntentFilter filter = matchingFilters.get(i); 5854 int targetUserId = filter.getTargetUserId(); 5855 boolean skipCurrentProfile = 5856 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5857 boolean skipCurrentProfileIfNoMatchFound = 5858 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5859 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5860 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5861 // Checking if there are activities in the target user that can handle the 5862 // intent. 5863 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5864 resolvedType, flags, sourceUserId); 5865 if (resolveInfo != null) return resolveInfo; 5866 alreadyTriedUserIds.put(targetUserId, true); 5867 } 5868 } 5869 } 5870 return null; 5871 } 5872 5873 /** 5874 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5875 * will forward the intent to the filter's target user. 5876 * Otherwise, returns null. 5877 */ 5878 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5879 String resolvedType, int flags, int sourceUserId) { 5880 int targetUserId = filter.getTargetUserId(); 5881 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5882 resolvedType, flags, targetUserId); 5883 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5884 // If all the matches in the target profile are suspended, return null. 5885 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5886 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5887 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5888 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5889 targetUserId); 5890 } 5891 } 5892 } 5893 return null; 5894 } 5895 5896 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5897 int sourceUserId, int targetUserId) { 5898 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5899 long ident = Binder.clearCallingIdentity(); 5900 boolean targetIsProfile; 5901 try { 5902 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5903 } finally { 5904 Binder.restoreCallingIdentity(ident); 5905 } 5906 String className; 5907 if (targetIsProfile) { 5908 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5909 } else { 5910 className = FORWARD_INTENT_TO_PARENT; 5911 } 5912 ComponentName forwardingActivityComponentName = new ComponentName( 5913 mAndroidApplication.packageName, className); 5914 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5915 sourceUserId); 5916 if (!targetIsProfile) { 5917 forwardingActivityInfo.showUserIcon = targetUserId; 5918 forwardingResolveInfo.noResourceId = true; 5919 } 5920 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5921 forwardingResolveInfo.priority = 0; 5922 forwardingResolveInfo.preferredOrder = 0; 5923 forwardingResolveInfo.match = 0; 5924 forwardingResolveInfo.isDefault = true; 5925 forwardingResolveInfo.filter = filter; 5926 forwardingResolveInfo.targetUserId = targetUserId; 5927 return forwardingResolveInfo; 5928 } 5929 5930 @Override 5931 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5932 Intent[] specifics, String[] specificTypes, Intent intent, 5933 String resolvedType, int flags, int userId) { 5934 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 5935 specificTypes, intent, resolvedType, flags, userId)); 5936 } 5937 5938 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 5939 Intent[] specifics, String[] specificTypes, Intent intent, 5940 String resolvedType, int flags, int userId) { 5941 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5942 flags = updateFlagsForResolve(flags, userId, intent); 5943 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5944 false /* requireFullPermission */, false /* checkShell */, 5945 "query intent activity options"); 5946 final String resultsAction = intent.getAction(); 5947 5948 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 5949 | PackageManager.GET_RESOLVED_FILTER, userId); 5950 5951 if (DEBUG_INTENT_MATCHING) { 5952 Log.v(TAG, "Query " + intent + ": " + results); 5953 } 5954 5955 int specificsPos = 0; 5956 int N; 5957 5958 // todo: note that the algorithm used here is O(N^2). This 5959 // isn't a problem in our current environment, but if we start running 5960 // into situations where we have more than 5 or 10 matches then this 5961 // should probably be changed to something smarter... 5962 5963 // First we go through and resolve each of the specific items 5964 // that were supplied, taking care of removing any corresponding 5965 // duplicate items in the generic resolve list. 5966 if (specifics != null) { 5967 for (int i=0; i<specifics.length; i++) { 5968 final Intent sintent = specifics[i]; 5969 if (sintent == null) { 5970 continue; 5971 } 5972 5973 if (DEBUG_INTENT_MATCHING) { 5974 Log.v(TAG, "Specific #" + i + ": " + sintent); 5975 } 5976 5977 String action = sintent.getAction(); 5978 if (resultsAction != null && resultsAction.equals(action)) { 5979 // If this action was explicitly requested, then don't 5980 // remove things that have it. 5981 action = null; 5982 } 5983 5984 ResolveInfo ri = null; 5985 ActivityInfo ai = null; 5986 5987 ComponentName comp = sintent.getComponent(); 5988 if (comp == null) { 5989 ri = resolveIntent( 5990 sintent, 5991 specificTypes != null ? specificTypes[i] : null, 5992 flags, userId); 5993 if (ri == null) { 5994 continue; 5995 } 5996 if (ri == mResolveInfo) { 5997 // ACK! Must do something better with this. 5998 } 5999 ai = ri.activityInfo; 6000 comp = new ComponentName(ai.applicationInfo.packageName, 6001 ai.name); 6002 } else { 6003 ai = getActivityInfo(comp, flags, userId); 6004 if (ai == null) { 6005 continue; 6006 } 6007 } 6008 6009 // Look for any generic query activities that are duplicates 6010 // of this specific one, and remove them from the results. 6011 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 6012 N = results.size(); 6013 int j; 6014 for (j=specificsPos; j<N; j++) { 6015 ResolveInfo sri = results.get(j); 6016 if ((sri.activityInfo.name.equals(comp.getClassName()) 6017 && sri.activityInfo.applicationInfo.packageName.equals( 6018 comp.getPackageName())) 6019 || (action != null && sri.filter.matchAction(action))) { 6020 results.remove(j); 6021 if (DEBUG_INTENT_MATCHING) Log.v( 6022 TAG, "Removing duplicate item from " + j 6023 + " due to specific " + specificsPos); 6024 if (ri == null) { 6025 ri = sri; 6026 } 6027 j--; 6028 N--; 6029 } 6030 } 6031 6032 // Add this specific item to its proper place. 6033 if (ri == null) { 6034 ri = new ResolveInfo(); 6035 ri.activityInfo = ai; 6036 } 6037 results.add(specificsPos, ri); 6038 ri.specificIndex = i; 6039 specificsPos++; 6040 } 6041 } 6042 6043 // Now we go through the remaining generic results and remove any 6044 // duplicate actions that are found here. 6045 N = results.size(); 6046 for (int i=specificsPos; i<N-1; i++) { 6047 final ResolveInfo rii = results.get(i); 6048 if (rii.filter == null) { 6049 continue; 6050 } 6051 6052 // Iterate over all of the actions of this result's intent 6053 // filter... typically this should be just one. 6054 final Iterator<String> it = rii.filter.actionsIterator(); 6055 if (it == null) { 6056 continue; 6057 } 6058 while (it.hasNext()) { 6059 final String action = it.next(); 6060 if (resultsAction != null && resultsAction.equals(action)) { 6061 // If this action was explicitly requested, then don't 6062 // remove things that have it. 6063 continue; 6064 } 6065 for (int j=i+1; j<N; j++) { 6066 final ResolveInfo rij = results.get(j); 6067 if (rij.filter != null && rij.filter.hasAction(action)) { 6068 results.remove(j); 6069 if (DEBUG_INTENT_MATCHING) Log.v( 6070 TAG, "Removing duplicate item from " + j 6071 + " due to action " + action + " at " + i); 6072 j--; 6073 N--; 6074 } 6075 } 6076 } 6077 6078 // If the caller didn't request filter information, drop it now 6079 // so we don't have to marshall/unmarshall it. 6080 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6081 rii.filter = null; 6082 } 6083 } 6084 6085 // Filter out the caller activity if so requested. 6086 if (caller != null) { 6087 N = results.size(); 6088 for (int i=0; i<N; i++) { 6089 ActivityInfo ainfo = results.get(i).activityInfo; 6090 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 6091 && caller.getClassName().equals(ainfo.name)) { 6092 results.remove(i); 6093 break; 6094 } 6095 } 6096 } 6097 6098 // If the caller didn't request filter information, 6099 // drop them now so we don't have to 6100 // marshall/unmarshall it. 6101 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6102 N = results.size(); 6103 for (int i=0; i<N; i++) { 6104 results.get(i).filter = null; 6105 } 6106 } 6107 6108 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 6109 return results; 6110 } 6111 6112 @Override 6113 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 6114 String resolvedType, int flags, int userId) { 6115 return new ParceledListSlice<>( 6116 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 6117 } 6118 6119 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 6120 String resolvedType, int flags, int userId) { 6121 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6122 flags = updateFlagsForResolve(flags, userId, intent); 6123 ComponentName comp = intent.getComponent(); 6124 if (comp == null) { 6125 if (intent.getSelector() != null) { 6126 intent = intent.getSelector(); 6127 comp = intent.getComponent(); 6128 } 6129 } 6130 if (comp != null) { 6131 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6132 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 6133 if (ai != null) { 6134 ResolveInfo ri = new ResolveInfo(); 6135 ri.activityInfo = ai; 6136 list.add(ri); 6137 } 6138 return list; 6139 } 6140 6141 // reader 6142 synchronized (mPackages) { 6143 String pkgName = intent.getPackage(); 6144 if (pkgName == null) { 6145 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 6146 } 6147 final PackageParser.Package pkg = mPackages.get(pkgName); 6148 if (pkg != null) { 6149 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 6150 userId); 6151 } 6152 return Collections.emptyList(); 6153 } 6154 } 6155 6156 @Override 6157 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 6158 if (!sUserManager.exists(userId)) return null; 6159 flags = updateFlagsForResolve(flags, userId, intent); 6160 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 6161 if (query != null) { 6162 if (query.size() >= 1) { 6163 // If there is more than one service with the same priority, 6164 // just arbitrarily pick the first one. 6165 return query.get(0); 6166 } 6167 } 6168 return null; 6169 } 6170 6171 @Override 6172 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 6173 String resolvedType, int flags, int userId) { 6174 return new ParceledListSlice<>( 6175 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 6176 } 6177 6178 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 6179 String resolvedType, int flags, int userId) { 6180 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6181 flags = updateFlagsForResolve(flags, userId, intent); 6182 ComponentName comp = intent.getComponent(); 6183 if (comp == null) { 6184 if (intent.getSelector() != null) { 6185 intent = intent.getSelector(); 6186 comp = intent.getComponent(); 6187 } 6188 } 6189 if (comp != null) { 6190 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6191 final ServiceInfo si = getServiceInfo(comp, flags, userId); 6192 if (si != null) { 6193 final ResolveInfo ri = new ResolveInfo(); 6194 ri.serviceInfo = si; 6195 list.add(ri); 6196 } 6197 return list; 6198 } 6199 6200 // reader 6201 synchronized (mPackages) { 6202 String pkgName = intent.getPackage(); 6203 if (pkgName == null) { 6204 return mServices.queryIntent(intent, resolvedType, flags, userId); 6205 } 6206 final PackageParser.Package pkg = mPackages.get(pkgName); 6207 if (pkg != null) { 6208 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 6209 userId); 6210 } 6211 return Collections.emptyList(); 6212 } 6213 } 6214 6215 @Override 6216 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 6217 String resolvedType, int flags, int userId) { 6218 return new ParceledListSlice<>( 6219 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 6220 } 6221 6222 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 6223 Intent intent, String resolvedType, int flags, int userId) { 6224 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6225 flags = updateFlagsForResolve(flags, userId, intent); 6226 ComponentName comp = intent.getComponent(); 6227 if (comp == null) { 6228 if (intent.getSelector() != null) { 6229 intent = intent.getSelector(); 6230 comp = intent.getComponent(); 6231 } 6232 } 6233 if (comp != null) { 6234 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6235 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 6236 if (pi != null) { 6237 final ResolveInfo ri = new ResolveInfo(); 6238 ri.providerInfo = pi; 6239 list.add(ri); 6240 } 6241 return list; 6242 } 6243 6244 // reader 6245 synchronized (mPackages) { 6246 String pkgName = intent.getPackage(); 6247 if (pkgName == null) { 6248 return mProviders.queryIntent(intent, resolvedType, flags, userId); 6249 } 6250 final PackageParser.Package pkg = mPackages.get(pkgName); 6251 if (pkg != null) { 6252 return mProviders.queryIntentForPackage( 6253 intent, resolvedType, flags, pkg.providers, userId); 6254 } 6255 return Collections.emptyList(); 6256 } 6257 } 6258 6259 @Override 6260 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 6261 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6262 flags = updateFlagsForPackage(flags, userId, null); 6263 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6264 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6265 true /* requireFullPermission */, false /* checkShell */, 6266 "get installed packages"); 6267 6268 // writer 6269 synchronized (mPackages) { 6270 ArrayList<PackageInfo> list; 6271 if (listUninstalled) { 6272 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 6273 for (PackageSetting ps : mSettings.mPackages.values()) { 6274 final PackageInfo pi; 6275 if (ps.pkg != null) { 6276 pi = generatePackageInfo(ps, flags, userId); 6277 } else { 6278 pi = generatePackageInfo(ps, flags, userId); 6279 } 6280 if (pi != null) { 6281 list.add(pi); 6282 } 6283 } 6284 } else { 6285 list = new ArrayList<PackageInfo>(mPackages.size()); 6286 for (PackageParser.Package p : mPackages.values()) { 6287 final PackageInfo pi = 6288 generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 6289 if (pi != null) { 6290 list.add(pi); 6291 } 6292 } 6293 } 6294 6295 return new ParceledListSlice<PackageInfo>(list); 6296 } 6297 } 6298 6299 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 6300 String[] permissions, boolean[] tmp, int flags, int userId) { 6301 int numMatch = 0; 6302 final PermissionsState permissionsState = ps.getPermissionsState(); 6303 for (int i=0; i<permissions.length; i++) { 6304 final String permission = permissions[i]; 6305 if (permissionsState.hasPermission(permission, userId)) { 6306 tmp[i] = true; 6307 numMatch++; 6308 } else { 6309 tmp[i] = false; 6310 } 6311 } 6312 if (numMatch == 0) { 6313 return; 6314 } 6315 final PackageInfo pi; 6316 if (ps.pkg != null) { 6317 pi = generatePackageInfo(ps, flags, userId); 6318 } else { 6319 pi = generatePackageInfo(ps, flags, userId); 6320 } 6321 // The above might return null in cases of uninstalled apps or install-state 6322 // skew across users/profiles. 6323 if (pi != null) { 6324 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 6325 if (numMatch == permissions.length) { 6326 pi.requestedPermissions = permissions; 6327 } else { 6328 pi.requestedPermissions = new String[numMatch]; 6329 numMatch = 0; 6330 for (int i=0; i<permissions.length; i++) { 6331 if (tmp[i]) { 6332 pi.requestedPermissions[numMatch] = permissions[i]; 6333 numMatch++; 6334 } 6335 } 6336 } 6337 } 6338 list.add(pi); 6339 } 6340 } 6341 6342 @Override 6343 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 6344 String[] permissions, int flags, int userId) { 6345 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6346 flags = updateFlagsForPackage(flags, userId, permissions); 6347 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6348 6349 // writer 6350 synchronized (mPackages) { 6351 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 6352 boolean[] tmpBools = new boolean[permissions.length]; 6353 if (listUninstalled) { 6354 for (PackageSetting ps : mSettings.mPackages.values()) { 6355 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 6356 } 6357 } else { 6358 for (PackageParser.Package pkg : mPackages.values()) { 6359 PackageSetting ps = (PackageSetting)pkg.mExtras; 6360 if (ps != null) { 6361 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6362 userId); 6363 } 6364 } 6365 } 6366 6367 return new ParceledListSlice<PackageInfo>(list); 6368 } 6369 } 6370 6371 @Override 6372 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 6373 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6374 flags = updateFlagsForApplication(flags, userId, null); 6375 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6376 6377 // writer 6378 synchronized (mPackages) { 6379 ArrayList<ApplicationInfo> list; 6380 if (listUninstalled) { 6381 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 6382 for (PackageSetting ps : mSettings.mPackages.values()) { 6383 ApplicationInfo ai; 6384 if (ps.pkg != null) { 6385 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 6386 ps.readUserState(userId), userId); 6387 } else { 6388 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 6389 } 6390 if (ai != null) { 6391 list.add(ai); 6392 } 6393 } 6394 } else { 6395 list = new ArrayList<ApplicationInfo>(mPackages.size()); 6396 for (PackageParser.Package p : mPackages.values()) { 6397 if (p.mExtras != null) { 6398 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6399 ((PackageSetting)p.mExtras).readUserState(userId), userId); 6400 if (ai != null) { 6401 list.add(ai); 6402 } 6403 } 6404 } 6405 } 6406 6407 return new ParceledListSlice<ApplicationInfo>(list); 6408 } 6409 } 6410 6411 @Override 6412 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 6413 if (DISABLE_EPHEMERAL_APPS) { 6414 return null; 6415 } 6416 6417 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6418 "getEphemeralApplications"); 6419 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6420 true /* requireFullPermission */, false /* checkShell */, 6421 "getEphemeralApplications"); 6422 synchronized (mPackages) { 6423 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 6424 .getEphemeralApplicationsLPw(userId); 6425 if (ephemeralApps != null) { 6426 return new ParceledListSlice<>(ephemeralApps); 6427 } 6428 } 6429 return null; 6430 } 6431 6432 @Override 6433 public boolean isEphemeralApplication(String packageName, int userId) { 6434 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6435 true /* requireFullPermission */, false /* checkShell */, 6436 "isEphemeral"); 6437 if (DISABLE_EPHEMERAL_APPS) { 6438 return false; 6439 } 6440 6441 if (!isCallerSameApp(packageName)) { 6442 return false; 6443 } 6444 synchronized (mPackages) { 6445 PackageParser.Package pkg = mPackages.get(packageName); 6446 if (pkg != null) { 6447 return pkg.applicationInfo.isEphemeralApp(); 6448 } 6449 } 6450 return false; 6451 } 6452 6453 @Override 6454 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6455 if (DISABLE_EPHEMERAL_APPS) { 6456 return null; 6457 } 6458 6459 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6460 true /* requireFullPermission */, false /* checkShell */, 6461 "getCookie"); 6462 if (!isCallerSameApp(packageName)) { 6463 return null; 6464 } 6465 synchronized (mPackages) { 6466 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6467 packageName, userId); 6468 } 6469 } 6470 6471 @Override 6472 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6473 if (DISABLE_EPHEMERAL_APPS) { 6474 return true; 6475 } 6476 6477 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6478 true /* requireFullPermission */, true /* checkShell */, 6479 "setCookie"); 6480 if (!isCallerSameApp(packageName)) { 6481 return false; 6482 } 6483 synchronized (mPackages) { 6484 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6485 packageName, cookie, userId); 6486 } 6487 } 6488 6489 @Override 6490 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6491 if (DISABLE_EPHEMERAL_APPS) { 6492 return null; 6493 } 6494 6495 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6496 "getEphemeralApplicationIcon"); 6497 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6498 true /* requireFullPermission */, false /* checkShell */, 6499 "getEphemeralApplicationIcon"); 6500 synchronized (mPackages) { 6501 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6502 packageName, userId); 6503 } 6504 } 6505 6506 private boolean isCallerSameApp(String packageName) { 6507 PackageParser.Package pkg = mPackages.get(packageName); 6508 return pkg != null 6509 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6510 } 6511 6512 @Override 6513 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 6514 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 6515 } 6516 6517 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 6518 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6519 6520 // reader 6521 synchronized (mPackages) { 6522 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6523 final int userId = UserHandle.getCallingUserId(); 6524 while (i.hasNext()) { 6525 final PackageParser.Package p = i.next(); 6526 if (p.applicationInfo == null) continue; 6527 6528 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 6529 && !p.applicationInfo.isDirectBootAware(); 6530 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 6531 && p.applicationInfo.isDirectBootAware(); 6532 6533 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6534 && (!mSafeMode || isSystemApp(p)) 6535 && (matchesUnaware || matchesAware)) { 6536 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6537 if (ps != null) { 6538 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6539 ps.readUserState(userId), userId); 6540 if (ai != null) { 6541 finalList.add(ai); 6542 } 6543 } 6544 } 6545 } 6546 } 6547 6548 return finalList; 6549 } 6550 6551 @Override 6552 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6553 if (!sUserManager.exists(userId)) return null; 6554 flags = updateFlagsForComponent(flags, userId, name); 6555 // reader 6556 synchronized (mPackages) { 6557 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6558 PackageSetting ps = provider != null 6559 ? mSettings.mPackages.get(provider.owner.packageName) 6560 : null; 6561 return ps != null 6562 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6563 ? PackageParser.generateProviderInfo(provider, flags, 6564 ps.readUserState(userId), userId) 6565 : null; 6566 } 6567 } 6568 6569 /** 6570 * @deprecated 6571 */ 6572 @Deprecated 6573 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6574 // reader 6575 synchronized (mPackages) { 6576 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6577 .entrySet().iterator(); 6578 final int userId = UserHandle.getCallingUserId(); 6579 while (i.hasNext()) { 6580 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6581 PackageParser.Provider p = entry.getValue(); 6582 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6583 6584 if (ps != null && p.syncable 6585 && (!mSafeMode || (p.info.applicationInfo.flags 6586 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6587 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6588 ps.readUserState(userId), userId); 6589 if (info != null) { 6590 outNames.add(entry.getKey()); 6591 outInfo.add(info); 6592 } 6593 } 6594 } 6595 } 6596 } 6597 6598 @Override 6599 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6600 int uid, int flags) { 6601 final int userId = processName != null ? UserHandle.getUserId(uid) 6602 : UserHandle.getCallingUserId(); 6603 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6604 flags = updateFlagsForComponent(flags, userId, processName); 6605 6606 ArrayList<ProviderInfo> finalList = null; 6607 // reader 6608 synchronized (mPackages) { 6609 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6610 while (i.hasNext()) { 6611 final PackageParser.Provider p = i.next(); 6612 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6613 if (ps != null && p.info.authority != null 6614 && (processName == null 6615 || (p.info.processName.equals(processName) 6616 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6617 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6618 if (finalList == null) { 6619 finalList = new ArrayList<ProviderInfo>(3); 6620 } 6621 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6622 ps.readUserState(userId), userId); 6623 if (info != null) { 6624 finalList.add(info); 6625 } 6626 } 6627 } 6628 } 6629 6630 if (finalList != null) { 6631 Collections.sort(finalList, mProviderInitOrderSorter); 6632 return new ParceledListSlice<ProviderInfo>(finalList); 6633 } 6634 6635 return ParceledListSlice.emptyList(); 6636 } 6637 6638 @Override 6639 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6640 // reader 6641 synchronized (mPackages) { 6642 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6643 return PackageParser.generateInstrumentationInfo(i, flags); 6644 } 6645 } 6646 6647 @Override 6648 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 6649 String targetPackage, int flags) { 6650 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 6651 } 6652 6653 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 6654 int flags) { 6655 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 6656 6657 // reader 6658 synchronized (mPackages) { 6659 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6660 while (i.hasNext()) { 6661 final PackageParser.Instrumentation p = i.next(); 6662 if (targetPackage == null 6663 || targetPackage.equals(p.info.targetPackage)) { 6664 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6665 flags); 6666 if (ii != null) { 6667 finalList.add(ii); 6668 } 6669 } 6670 } 6671 } 6672 6673 return finalList; 6674 } 6675 6676 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6677 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6678 if (overlays == null) { 6679 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6680 return; 6681 } 6682 for (PackageParser.Package opkg : overlays.values()) { 6683 // Not much to do if idmap fails: we already logged the error 6684 // and we certainly don't want to abort installation of pkg simply 6685 // because an overlay didn't fit properly. For these reasons, 6686 // ignore the return value of createIdmapForPackagePairLI. 6687 createIdmapForPackagePairLI(pkg, opkg); 6688 } 6689 } 6690 6691 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6692 PackageParser.Package opkg) { 6693 if (!opkg.mTrustedOverlay) { 6694 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6695 opkg.baseCodePath + ": overlay not trusted"); 6696 return false; 6697 } 6698 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6699 if (overlaySet == null) { 6700 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6701 opkg.baseCodePath + " but target package has no known overlays"); 6702 return false; 6703 } 6704 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6705 // TODO: generate idmap for split APKs 6706 try { 6707 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6708 } catch (InstallerException e) { 6709 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6710 + opkg.baseCodePath); 6711 return false; 6712 } 6713 PackageParser.Package[] overlayArray = 6714 overlaySet.values().toArray(new PackageParser.Package[0]); 6715 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6716 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6717 return p1.mOverlayPriority - p2.mOverlayPriority; 6718 } 6719 }; 6720 Arrays.sort(overlayArray, cmp); 6721 6722 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6723 int i = 0; 6724 for (PackageParser.Package p : overlayArray) { 6725 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6726 } 6727 return true; 6728 } 6729 6730 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6731 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6732 try { 6733 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6734 } finally { 6735 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6736 } 6737 } 6738 6739 private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6740 final File[] files = dir.listFiles(); 6741 if (ArrayUtils.isEmpty(files)) { 6742 Log.d(TAG, "No files in app dir " + dir); 6743 return; 6744 } 6745 6746 if (DEBUG_PACKAGE_SCANNING) { 6747 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6748 + " flags=0x" + Integer.toHexString(parseFlags)); 6749 } 6750 6751 for (File file : files) { 6752 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6753 && !PackageInstallerService.isStageName(file.getName()); 6754 if (!isPackage) { 6755 // Ignore entries which are not packages 6756 continue; 6757 } 6758 try { 6759 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6760 scanFlags, currentTime, null); 6761 } catch (PackageManagerException e) { 6762 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6763 6764 // Delete invalid userdata apps 6765 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6766 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6767 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6768 removeCodePathLI(file); 6769 } 6770 } 6771 } 6772 } 6773 6774 private static File getSettingsProblemFile() { 6775 File dataDir = Environment.getDataDirectory(); 6776 File systemDir = new File(dataDir, "system"); 6777 File fname = new File(systemDir, "uiderrors.txt"); 6778 return fname; 6779 } 6780 6781 static void reportSettingsProblem(int priority, String msg) { 6782 logCriticalInfo(priority, msg); 6783 } 6784 6785 static void logCriticalInfo(int priority, String msg) { 6786 Slog.println(priority, TAG, msg); 6787 EventLogTags.writePmCriticalInfo(msg); 6788 try { 6789 File fname = getSettingsProblemFile(); 6790 FileOutputStream out = new FileOutputStream(fname, true); 6791 PrintWriter pw = new FastPrintWriter(out); 6792 SimpleDateFormat formatter = new SimpleDateFormat(); 6793 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6794 pw.println(dateString + ": " + msg); 6795 pw.close(); 6796 FileUtils.setPermissions( 6797 fname.toString(), 6798 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6799 -1, -1); 6800 } catch (java.io.IOException e) { 6801 } 6802 } 6803 6804 private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) { 6805 if (srcFile.isDirectory()) { 6806 final File baseFile = new File(pkg.baseCodePath); 6807 long maxModifiedTime = baseFile.lastModified(); 6808 if (pkg.splitCodePaths != null) { 6809 for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) { 6810 final File splitFile = new File(pkg.splitCodePaths[i]); 6811 maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified()); 6812 } 6813 } 6814 return maxModifiedTime; 6815 } 6816 return srcFile.lastModified(); 6817 } 6818 6819 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6820 final int policyFlags) throws PackageManagerException { 6821 if (ps != null 6822 && ps.codePath.equals(srcFile) 6823 && ps.timeStamp == getLastModifiedTime(pkg, srcFile) 6824 && !isCompatSignatureUpdateNeeded(pkg) 6825 && !isRecoverSignatureUpdateNeeded(pkg)) { 6826 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6827 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6828 ArraySet<PublicKey> signingKs; 6829 synchronized (mPackages) { 6830 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6831 } 6832 if (ps.signatures.mSignatures != null 6833 && ps.signatures.mSignatures.length != 0 6834 && signingKs != null) { 6835 // Optimization: reuse the existing cached certificates 6836 // if the package appears to be unchanged. 6837 pkg.mSignatures = ps.signatures.mSignatures; 6838 pkg.mSigningKeys = signingKs; 6839 return; 6840 } 6841 6842 Slog.w(TAG, "PackageSetting for " + ps.name 6843 + " is missing signatures. Collecting certs again to recover them."); 6844 } else { 6845 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6846 } 6847 6848 try { 6849 PackageParser.collectCertificates(pkg, policyFlags); 6850 } catch (PackageParserException e) { 6851 throw PackageManagerException.from(e); 6852 } 6853 } 6854 6855 /** 6856 * Traces a package scan. 6857 * @see #scanPackageLI(File, int, int, long, UserHandle) 6858 */ 6859 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 6860 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6861 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6862 try { 6863 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6864 } finally { 6865 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6866 } 6867 } 6868 6869 /** 6870 * Scans a package and returns the newly parsed package. 6871 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6872 */ 6873 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6874 long currentTime, UserHandle user) throws PackageManagerException { 6875 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6876 PackageParser pp = new PackageParser(); 6877 pp.setSeparateProcesses(mSeparateProcesses); 6878 pp.setOnlyCoreApps(mOnlyCore); 6879 pp.setDisplayMetrics(mMetrics); 6880 6881 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6882 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6883 } 6884 6885 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 6886 final PackageParser.Package pkg; 6887 try { 6888 pkg = pp.parsePackage(scanFile, parseFlags); 6889 } catch (PackageParserException e) { 6890 throw PackageManagerException.from(e); 6891 } finally { 6892 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6893 } 6894 6895 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6896 } 6897 6898 /** 6899 * Scans a package and returns the newly parsed package. 6900 * @throws PackageManagerException on a parse error. 6901 */ 6902 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6903 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 6904 throws PackageManagerException { 6905 // If the package has children and this is the first dive in the function 6906 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6907 // packages (parent and children) would be successfully scanned before the 6908 // actual scan since scanning mutates internal state and we want to atomically 6909 // install the package and its children. 6910 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6911 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6912 scanFlags |= SCAN_CHECK_ONLY; 6913 } 6914 } else { 6915 scanFlags &= ~SCAN_CHECK_ONLY; 6916 } 6917 6918 // Scan the parent 6919 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 6920 scanFlags, currentTime, user); 6921 6922 // Scan the children 6923 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6924 for (int i = 0; i < childCount; i++) { 6925 PackageParser.Package childPackage = pkg.childPackages.get(i); 6926 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 6927 currentTime, user); 6928 } 6929 6930 6931 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6932 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 6933 } 6934 6935 return scannedPkg; 6936 } 6937 6938 /** 6939 * Scans a package and returns the newly parsed package. 6940 * @throws PackageManagerException on a parse error. 6941 */ 6942 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6943 int policyFlags, int scanFlags, long currentTime, UserHandle user) 6944 throws PackageManagerException { 6945 PackageSetting ps = null; 6946 PackageSetting updatedPkg; 6947 // reader 6948 synchronized (mPackages) { 6949 // Look to see if we already know about this package. 6950 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6951 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6952 // This package has been renamed to its original name. Let's 6953 // use that. 6954 ps = mSettings.peekPackageLPr(oldName); 6955 } 6956 // If there was no original package, see one for the real package name. 6957 if (ps == null) { 6958 ps = mSettings.peekPackageLPr(pkg.packageName); 6959 } 6960 // Check to see if this package could be hiding/updating a system 6961 // package. Must look for it either under the original or real 6962 // package name depending on our state. 6963 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6964 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6965 6966 // If this is a package we don't know about on the system partition, we 6967 // may need to remove disabled child packages on the system partition 6968 // or may need to not add child packages if the parent apk is updated 6969 // on the data partition and no longer defines this child package. 6970 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6971 // If this is a parent package for an updated system app and this system 6972 // app got an OTA update which no longer defines some of the child packages 6973 // we have to prune them from the disabled system packages. 6974 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6975 if (disabledPs != null) { 6976 final int scannedChildCount = (pkg.childPackages != null) 6977 ? pkg.childPackages.size() : 0; 6978 final int disabledChildCount = disabledPs.childPackageNames != null 6979 ? disabledPs.childPackageNames.size() : 0; 6980 for (int i = 0; i < disabledChildCount; i++) { 6981 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6982 boolean disabledPackageAvailable = false; 6983 for (int j = 0; j < scannedChildCount; j++) { 6984 PackageParser.Package childPkg = pkg.childPackages.get(j); 6985 if (childPkg.packageName.equals(disabledChildPackageName)) { 6986 disabledPackageAvailable = true; 6987 break; 6988 } 6989 } 6990 if (!disabledPackageAvailable) { 6991 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6992 } 6993 } 6994 } 6995 } 6996 } 6997 6998 boolean updatedPkgBetter = false; 6999 // First check if this is a system package that may involve an update 7000 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 7001 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 7002 // it needs to drop FLAG_PRIVILEGED. 7003 if (locationIsPrivileged(scanFile)) { 7004 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7005 } else { 7006 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7007 } 7008 7009 if (ps != null && !ps.codePath.equals(scanFile)) { 7010 // The path has changed from what was last scanned... check the 7011 // version of the new path against what we have stored to determine 7012 // what to do. 7013 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 7014 if (pkg.mVersionCode <= ps.versionCode) { 7015 // The system package has been updated and the code path does not match 7016 // Ignore entry. Skip it. 7017 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 7018 + " ignored: updated version " + ps.versionCode 7019 + " better than this " + pkg.mVersionCode); 7020 if (!updatedPkg.codePath.equals(scanFile)) { 7021 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 7022 + ps.name + " changing from " + updatedPkg.codePathString 7023 + " to " + scanFile); 7024 updatedPkg.codePath = scanFile; 7025 updatedPkg.codePathString = scanFile.toString(); 7026 updatedPkg.resourcePath = scanFile; 7027 updatedPkg.resourcePathString = scanFile.toString(); 7028 } 7029 updatedPkg.pkg = pkg; 7030 updatedPkg.versionCode = pkg.mVersionCode; 7031 7032 // Update the disabled system child packages to point to the package too. 7033 final int childCount = updatedPkg.childPackageNames != null 7034 ? updatedPkg.childPackageNames.size() : 0; 7035 for (int i = 0; i < childCount; i++) { 7036 String childPackageName = updatedPkg.childPackageNames.get(i); 7037 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 7038 childPackageName); 7039 if (updatedChildPkg != null) { 7040 updatedChildPkg.pkg = pkg; 7041 updatedChildPkg.versionCode = pkg.mVersionCode; 7042 } 7043 } 7044 7045 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 7046 + scanFile + " ignored: updated version " + ps.versionCode 7047 + " better than this " + pkg.mVersionCode); 7048 } else { 7049 // The current app on the system partition is better than 7050 // what we have updated to on the data partition; switch 7051 // back to the system partition version. 7052 // At this point, its safely assumed that package installation for 7053 // apps in system partition will go through. If not there won't be a working 7054 // version of the app 7055 // writer 7056 synchronized (mPackages) { 7057 // Just remove the loaded entries from package lists. 7058 mPackages.remove(ps.name); 7059 } 7060 7061 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7062 + " reverting from " + ps.codePathString 7063 + ": new version " + pkg.mVersionCode 7064 + " better than installed " + ps.versionCode); 7065 7066 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7067 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7068 synchronized (mInstallLock) { 7069 args.cleanUpResourcesLI(); 7070 } 7071 synchronized (mPackages) { 7072 mSettings.enableSystemPackageLPw(ps.name); 7073 } 7074 updatedPkgBetter = true; 7075 } 7076 } 7077 } 7078 7079 if (updatedPkg != null) { 7080 // An updated system app will not have the PARSE_IS_SYSTEM flag set 7081 // initially 7082 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 7083 7084 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 7085 // flag set initially 7086 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 7087 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 7088 } 7089 } 7090 7091 // Verify certificates against what was last scanned 7092 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 7093 7094 /* 7095 * A new system app appeared, but we already had a non-system one of the 7096 * same name installed earlier. 7097 */ 7098 boolean shouldHideSystemApp = false; 7099 if (updatedPkg == null && ps != null 7100 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 7101 /* 7102 * Check to make sure the signatures match first. If they don't, 7103 * wipe the installed application and its data. 7104 */ 7105 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 7106 != PackageManager.SIGNATURE_MATCH) { 7107 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 7108 + " signatures don't match existing userdata copy; removing"); 7109 try (PackageFreezer freezer = freezePackage(pkg.packageName, 7110 "scanPackageInternalLI")) { 7111 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 7112 } 7113 ps = null; 7114 } else { 7115 /* 7116 * If the newly-added system app is an older version than the 7117 * already installed version, hide it. It will be scanned later 7118 * and re-added like an update. 7119 */ 7120 if (pkg.mVersionCode <= ps.versionCode) { 7121 shouldHideSystemApp = true; 7122 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 7123 + " but new version " + pkg.mVersionCode + " better than installed " 7124 + ps.versionCode + "; hiding system"); 7125 } else { 7126 /* 7127 * The newly found system app is a newer version that the 7128 * one previously installed. Simply remove the 7129 * already-installed application and replace it with our own 7130 * while keeping the application data. 7131 */ 7132 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7133 + " reverting from " + ps.codePathString + ": new version " 7134 + pkg.mVersionCode + " better than installed " + ps.versionCode); 7135 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7136 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7137 synchronized (mInstallLock) { 7138 args.cleanUpResourcesLI(); 7139 } 7140 } 7141 } 7142 } 7143 7144 // The apk is forward locked (not public) if its code and resources 7145 // are kept in different files. (except for app in either system or 7146 // vendor path). 7147 // TODO grab this value from PackageSettings 7148 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7149 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 7150 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 7151 } 7152 } 7153 7154 // TODO: extend to support forward-locked splits 7155 String resourcePath = null; 7156 String baseResourcePath = null; 7157 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 7158 if (ps != null && ps.resourcePathString != null) { 7159 resourcePath = ps.resourcePathString; 7160 baseResourcePath = ps.resourcePathString; 7161 } else { 7162 // Should not happen at all. Just log an error. 7163 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 7164 } 7165 } else { 7166 resourcePath = pkg.codePath; 7167 baseResourcePath = pkg.baseCodePath; 7168 } 7169 7170 // Set application objects path explicitly. 7171 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 7172 pkg.setApplicationInfoCodePath(pkg.codePath); 7173 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 7174 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 7175 pkg.setApplicationInfoResourcePath(resourcePath); 7176 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 7177 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 7178 7179 // Note that we invoke the following method only if we are about to unpack an application 7180 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 7181 | SCAN_UPDATE_SIGNATURE, currentTime, user); 7182 7183 /* 7184 * If the system app should be overridden by a previously installed 7185 * data, hide the system app now and let the /data/app scan pick it up 7186 * again. 7187 */ 7188 if (shouldHideSystemApp) { 7189 synchronized (mPackages) { 7190 mSettings.disableSystemPackageLPw(pkg.packageName, true); 7191 } 7192 } 7193 7194 return scannedPkg; 7195 } 7196 7197 private static String fixProcessName(String defProcessName, 7198 String processName, int uid) { 7199 if (processName == null) { 7200 return defProcessName; 7201 } 7202 return processName; 7203 } 7204 7205 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 7206 throws PackageManagerException { 7207 if (pkgSetting.signatures.mSignatures != null) { 7208 // Already existing package. Make sure signatures match 7209 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 7210 == PackageManager.SIGNATURE_MATCH; 7211 if (!match) { 7212 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 7213 == PackageManager.SIGNATURE_MATCH; 7214 } 7215 if (!match) { 7216 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 7217 == PackageManager.SIGNATURE_MATCH; 7218 } 7219 if (!match) { 7220 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 7221 + pkg.packageName + " signatures do not match the " 7222 + "previously installed version; ignoring!"); 7223 } 7224 } 7225 7226 // Check for shared user signatures 7227 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 7228 // Already existing package. Make sure signatures match 7229 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7230 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 7231 if (!match) { 7232 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 7233 == PackageManager.SIGNATURE_MATCH; 7234 } 7235 if (!match) { 7236 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 7237 == PackageManager.SIGNATURE_MATCH; 7238 } 7239 if (!match) { 7240 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 7241 "Package " + pkg.packageName 7242 + " has no signatures that match those in shared user " 7243 + pkgSetting.sharedUser.name + "; ignoring!"); 7244 } 7245 } 7246 } 7247 7248 /** 7249 * Enforces that only the system UID or root's UID can call a method exposed 7250 * via Binder. 7251 * 7252 * @param message used as message if SecurityException is thrown 7253 * @throws SecurityException if the caller is not system or root 7254 */ 7255 private static final void enforceSystemOrRoot(String message) { 7256 final int uid = Binder.getCallingUid(); 7257 if (uid != Process.SYSTEM_UID && uid != 0) { 7258 throw new SecurityException(message); 7259 } 7260 } 7261 7262 @Override 7263 public void performFstrimIfNeeded() { 7264 enforceSystemOrRoot("Only the system can request fstrim"); 7265 7266 // Before everything else, see whether we need to fstrim. 7267 try { 7268 IMountService ms = PackageHelper.getMountService(); 7269 if (ms != null) { 7270 final boolean isUpgrade = isUpgrade(); 7271 boolean doTrim = isUpgrade; 7272 if (doTrim) { 7273 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 7274 } else { 7275 final long interval = android.provider.Settings.Global.getLong( 7276 mContext.getContentResolver(), 7277 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 7278 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 7279 if (interval > 0) { 7280 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 7281 if (timeSinceLast > interval) { 7282 doTrim = true; 7283 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 7284 + "; running immediately"); 7285 } 7286 } 7287 } 7288 if (doTrim) { 7289 if (!isFirstBoot()) { 7290 try { 7291 ActivityManagerNative.getDefault().showBootMessage( 7292 mContext.getResources().getString( 7293 R.string.android_upgrading_fstrim), true); 7294 } catch (RemoteException e) { 7295 } 7296 } 7297 ms.runMaintenance(); 7298 } 7299 } else { 7300 Slog.e(TAG, "Mount service unavailable!"); 7301 } 7302 } catch (RemoteException e) { 7303 // Can't happen; MountService is local 7304 } 7305 } 7306 7307 @Override 7308 public void updatePackagesIfNeeded() { 7309 enforceSystemOrRoot("Only the system can request package update"); 7310 7311 // We need to re-extract after an OTA. 7312 boolean causeUpgrade = isUpgrade(); 7313 7314 // First boot or factory reset. 7315 // Note: we also handle devices that are upgrading to N right now as if it is their 7316 // first boot, as they do not have profile data. 7317 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 7318 7319 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 7320 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 7321 7322 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 7323 return; 7324 } 7325 7326 List<PackageParser.Package> pkgs; 7327 synchronized (mPackages) { 7328 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 7329 } 7330 7331 final long startTime = System.nanoTime(); 7332 final int[] stats = performDexOpt(pkgs, mIsPreNUpgrade /* showDialog */, 7333 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT)); 7334 7335 final int elapsedTimeSeconds = 7336 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 7337 7338 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 7339 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 7340 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 7341 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 7342 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 7343 } 7344 7345 /** 7346 * Performs dexopt on the set of packages in {@code packages} and returns an int array 7347 * containing statistics about the invocation. The array consists of three elements, 7348 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 7349 * and {@code numberOfPackagesFailed}. 7350 */ 7351 private int[] performDexOpt(List<PackageParser.Package> pkgs, boolean showDialog, 7352 String compilerFilter) { 7353 7354 int numberOfPackagesVisited = 0; 7355 int numberOfPackagesOptimized = 0; 7356 int numberOfPackagesSkipped = 0; 7357 int numberOfPackagesFailed = 0; 7358 final int numberOfPackagesToDexopt = pkgs.size(); 7359 7360 for (PackageParser.Package pkg : pkgs) { 7361 numberOfPackagesVisited++; 7362 7363 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 7364 if (DEBUG_DEXOPT) { 7365 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 7366 } 7367 numberOfPackagesSkipped++; 7368 continue; 7369 } 7370 7371 if (DEBUG_DEXOPT) { 7372 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 7373 numberOfPackagesToDexopt + ": " + pkg.packageName); 7374 } 7375 7376 if (showDialog) { 7377 try { 7378 ActivityManagerNative.getDefault().showBootMessage( 7379 mContext.getResources().getString(R.string.android_upgrading_apk, 7380 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 7381 } catch (RemoteException e) { 7382 } 7383 } 7384 7385 // checkProfiles is false to avoid merging profiles during boot which 7386 // might interfere with background compilation (b/28612421). 7387 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 7388 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 7389 // trade-off worth doing to save boot time work. 7390 int dexOptStatus = performDexOptTraced(pkg.packageName, 7391 false /* checkProfiles */, 7392 compilerFilter, 7393 false /* force */); 7394 switch (dexOptStatus) { 7395 case PackageDexOptimizer.DEX_OPT_PERFORMED: 7396 numberOfPackagesOptimized++; 7397 break; 7398 case PackageDexOptimizer.DEX_OPT_SKIPPED: 7399 numberOfPackagesSkipped++; 7400 break; 7401 case PackageDexOptimizer.DEX_OPT_FAILED: 7402 numberOfPackagesFailed++; 7403 break; 7404 default: 7405 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 7406 break; 7407 } 7408 } 7409 7410 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 7411 numberOfPackagesFailed }; 7412 } 7413 7414 @Override 7415 public void notifyPackageUse(String packageName, int reason) { 7416 synchronized (mPackages) { 7417 PackageParser.Package p = mPackages.get(packageName); 7418 if (p == null) { 7419 return; 7420 } 7421 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 7422 } 7423 } 7424 7425 // TODO: this is not used nor needed. Delete it. 7426 @Override 7427 public boolean performDexOptIfNeeded(String packageName) { 7428 int dexOptStatus = performDexOptTraced(packageName, 7429 false /* checkProfiles */, getFullCompilerFilter(), false /* force */); 7430 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7431 } 7432 7433 @Override 7434 public boolean performDexOpt(String packageName, 7435 boolean checkProfiles, int compileReason, boolean force) { 7436 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7437 getCompilerFilterForReason(compileReason), force); 7438 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7439 } 7440 7441 @Override 7442 public boolean performDexOptMode(String packageName, 7443 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7444 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7445 targetCompilerFilter, force); 7446 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7447 } 7448 7449 private int performDexOptTraced(String packageName, 7450 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7451 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7452 try { 7453 return performDexOptInternal(packageName, checkProfiles, 7454 targetCompilerFilter, force); 7455 } finally { 7456 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7457 } 7458 } 7459 7460 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 7461 // if the package can now be considered up to date for the given filter. 7462 private int performDexOptInternal(String packageName, 7463 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7464 PackageParser.Package p; 7465 synchronized (mPackages) { 7466 p = mPackages.get(packageName); 7467 if (p == null) { 7468 // Package could not be found. Report failure. 7469 return PackageDexOptimizer.DEX_OPT_FAILED; 7470 } 7471 mPackageUsage.write(false); 7472 } 7473 long callingId = Binder.clearCallingIdentity(); 7474 try { 7475 synchronized (mInstallLock) { 7476 return performDexOptInternalWithDependenciesLI(p, checkProfiles, 7477 targetCompilerFilter, force); 7478 } 7479 } finally { 7480 Binder.restoreCallingIdentity(callingId); 7481 } 7482 } 7483 7484 public ArraySet<String> getOptimizablePackages() { 7485 ArraySet<String> pkgs = new ArraySet<String>(); 7486 synchronized (mPackages) { 7487 for (PackageParser.Package p : mPackages.values()) { 7488 if (PackageDexOptimizer.canOptimizePackage(p)) { 7489 pkgs.add(p.packageName); 7490 } 7491 } 7492 } 7493 return pkgs; 7494 } 7495 7496 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7497 boolean checkProfiles, String targetCompilerFilter, 7498 boolean force) { 7499 // Select the dex optimizer based on the force parameter. 7500 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7501 // allocate an object here. 7502 PackageDexOptimizer pdo = force 7503 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7504 : mPackageDexOptimizer; 7505 7506 // Optimize all dependencies first. Note: we ignore the return value and march on 7507 // on errors. 7508 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7509 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 7510 if (!deps.isEmpty()) { 7511 for (PackageParser.Package depPackage : deps) { 7512 // TODO: Analyze and investigate if we (should) profile libraries. 7513 // Currently this will do a full compilation of the library by default. 7514 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 7515 false /* checkProfiles */, 7516 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY)); 7517 } 7518 } 7519 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 7520 targetCompilerFilter); 7521 } 7522 7523 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7524 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7525 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7526 Set<String> collectedNames = new HashSet<>(); 7527 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7528 7529 retValue.remove(p); 7530 7531 return retValue; 7532 } else { 7533 return Collections.emptyList(); 7534 } 7535 } 7536 7537 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7538 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7539 if (!collectedNames.contains(p.packageName)) { 7540 collectedNames.add(p.packageName); 7541 collected.add(p); 7542 7543 if (p.usesLibraries != null) { 7544 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7545 } 7546 if (p.usesOptionalLibraries != null) { 7547 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7548 collectedNames); 7549 } 7550 } 7551 } 7552 7553 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7554 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7555 for (String libName : libs) { 7556 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7557 if (libPkg != null) { 7558 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7559 } 7560 } 7561 } 7562 7563 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7564 synchronized (mPackages) { 7565 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7566 if (lib != null && lib.apk != null) { 7567 return mPackages.get(lib.apk); 7568 } 7569 } 7570 return null; 7571 } 7572 7573 public void shutdown() { 7574 mPackageUsage.write(true); 7575 } 7576 7577 @Override 7578 public void dumpProfiles(String packageName) { 7579 PackageParser.Package pkg; 7580 synchronized (mPackages) { 7581 pkg = mPackages.get(packageName); 7582 if (pkg == null) { 7583 throw new IllegalArgumentException("Unknown package: " + packageName); 7584 } 7585 } 7586 /* Only the shell, root, or the app user should be able to dump profiles. */ 7587 int callingUid = Binder.getCallingUid(); 7588 if (callingUid != Process.SHELL_UID && 7589 callingUid != Process.ROOT_UID && 7590 callingUid != pkg.applicationInfo.uid) { 7591 throw new SecurityException("dumpProfiles"); 7592 } 7593 7594 synchronized (mInstallLock) { 7595 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 7596 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 7597 try { 7598 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly(); 7599 String gid = Integer.toString(sharedGid); 7600 String codePaths = TextUtils.join(";", allCodePaths); 7601 mInstaller.dumpProfiles(gid, packageName, codePaths); 7602 } catch (InstallerException e) { 7603 Slog.w(TAG, "Failed to dump profiles", e); 7604 } 7605 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7606 } 7607 } 7608 7609 @Override 7610 public void forceDexOpt(String packageName) { 7611 enforceSystemOrRoot("forceDexOpt"); 7612 7613 PackageParser.Package pkg; 7614 synchronized (mPackages) { 7615 pkg = mPackages.get(packageName); 7616 if (pkg == null) { 7617 throw new IllegalArgumentException("Unknown package: " + packageName); 7618 } 7619 } 7620 7621 synchronized (mInstallLock) { 7622 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7623 7624 // Whoever is calling forceDexOpt wants a fully compiled package. 7625 // Don't use profiles since that may cause compilation to be skipped. 7626 final int res = performDexOptInternalWithDependenciesLI(pkg, 7627 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7628 true /* force */); 7629 7630 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7631 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7632 throw new IllegalStateException("Failed to dexopt: " + res); 7633 } 7634 } 7635 } 7636 7637 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7638 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7639 Slog.w(TAG, "Unable to update from " + oldPkg.name 7640 + " to " + newPkg.packageName 7641 + ": old package not in system partition"); 7642 return false; 7643 } else if (mPackages.get(oldPkg.name) != null) { 7644 Slog.w(TAG, "Unable to update from " + oldPkg.name 7645 + " to " + newPkg.packageName 7646 + ": old package still exists"); 7647 return false; 7648 } 7649 return true; 7650 } 7651 7652 void removeCodePathLI(File codePath) { 7653 if (codePath.isDirectory()) { 7654 try { 7655 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7656 } catch (InstallerException e) { 7657 Slog.w(TAG, "Failed to remove code path", e); 7658 } 7659 } else { 7660 codePath.delete(); 7661 } 7662 } 7663 7664 private int[] resolveUserIds(int userId) { 7665 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 7666 } 7667 7668 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7669 if (pkg == null) { 7670 Slog.wtf(TAG, "Package was null!", new Throwable()); 7671 return; 7672 } 7673 clearAppDataLeafLIF(pkg, userId, flags); 7674 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7675 for (int i = 0; i < childCount; i++) { 7676 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7677 } 7678 } 7679 7680 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7681 final PackageSetting ps; 7682 synchronized (mPackages) { 7683 ps = mSettings.mPackages.get(pkg.packageName); 7684 } 7685 for (int realUserId : resolveUserIds(userId)) { 7686 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7687 try { 7688 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7689 ceDataInode); 7690 } catch (InstallerException e) { 7691 Slog.w(TAG, String.valueOf(e)); 7692 } 7693 } 7694 } 7695 7696 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7697 if (pkg == null) { 7698 Slog.wtf(TAG, "Package was null!", new Throwable()); 7699 return; 7700 } 7701 destroyAppDataLeafLIF(pkg, userId, flags); 7702 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7703 for (int i = 0; i < childCount; i++) { 7704 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7705 } 7706 } 7707 7708 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7709 final PackageSetting ps; 7710 synchronized (mPackages) { 7711 ps = mSettings.mPackages.get(pkg.packageName); 7712 } 7713 for (int realUserId : resolveUserIds(userId)) { 7714 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7715 try { 7716 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7717 ceDataInode); 7718 } catch (InstallerException e) { 7719 Slog.w(TAG, String.valueOf(e)); 7720 } 7721 } 7722 } 7723 7724 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 7725 if (pkg == null) { 7726 Slog.wtf(TAG, "Package was null!", new Throwable()); 7727 return; 7728 } 7729 destroyAppProfilesLeafLIF(pkg); 7730 destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */); 7731 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7732 for (int i = 0; i < childCount; i++) { 7733 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 7734 destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId, 7735 true /* removeBaseMarker */); 7736 } 7737 } 7738 7739 private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId, 7740 boolean removeBaseMarker) { 7741 if (pkg.isForwardLocked()) { 7742 return; 7743 } 7744 7745 for (String path : pkg.getAllCodePathsExcludingResourceOnly()) { 7746 try { 7747 path = PackageManagerServiceUtils.realpath(new File(path)); 7748 } catch (IOException e) { 7749 // TODO: Should we return early here ? 7750 Slog.w(TAG, "Failed to get canonical path", e); 7751 continue; 7752 } 7753 7754 final String useMarker = path.replace('/', '@'); 7755 for (int realUserId : resolveUserIds(userId)) { 7756 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId); 7757 if (removeBaseMarker) { 7758 File foreignUseMark = new File(profileDir, useMarker); 7759 if (foreignUseMark.exists()) { 7760 if (!foreignUseMark.delete()) { 7761 Slog.w(TAG, "Unable to delete foreign user mark for package: " 7762 + pkg.packageName); 7763 } 7764 } 7765 } 7766 7767 File[] markers = profileDir.listFiles(); 7768 if (markers != null) { 7769 final String searchString = "@" + pkg.packageName + "@"; 7770 // We also delete all markers that contain the package name we're 7771 // uninstalling. These are associated with secondary dex-files belonging 7772 // to the package. Reconstructing the path of these dex files is messy 7773 // in general. 7774 for (File marker : markers) { 7775 if (marker.getName().indexOf(searchString) > 0) { 7776 if (!marker.delete()) { 7777 Slog.w(TAG, "Unable to delete foreign user mark for package: " 7778 + pkg.packageName); 7779 } 7780 } 7781 } 7782 } 7783 } 7784 } 7785 } 7786 7787 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 7788 try { 7789 mInstaller.destroyAppProfiles(pkg.packageName); 7790 } catch (InstallerException e) { 7791 Slog.w(TAG, String.valueOf(e)); 7792 } 7793 } 7794 7795 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 7796 if (pkg == null) { 7797 Slog.wtf(TAG, "Package was null!", new Throwable()); 7798 return; 7799 } 7800 clearAppProfilesLeafLIF(pkg); 7801 // We don't remove the base foreign use marker when clearing profiles because 7802 // we will rename it when the app is updated. Unlike the actual profile contents, 7803 // the foreign use marker is good across installs. 7804 destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */); 7805 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7806 for (int i = 0; i < childCount; i++) { 7807 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 7808 } 7809 } 7810 7811 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 7812 try { 7813 mInstaller.clearAppProfiles(pkg.packageName); 7814 } catch (InstallerException e) { 7815 Slog.w(TAG, String.valueOf(e)); 7816 } 7817 } 7818 7819 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7820 long lastUpdateTime) { 7821 // Set parent install/update time 7822 PackageSetting ps = (PackageSetting) pkg.mExtras; 7823 if (ps != null) { 7824 ps.firstInstallTime = firstInstallTime; 7825 ps.lastUpdateTime = lastUpdateTime; 7826 } 7827 // Set children install/update time 7828 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7829 for (int i = 0; i < childCount; i++) { 7830 PackageParser.Package childPkg = pkg.childPackages.get(i); 7831 ps = (PackageSetting) childPkg.mExtras; 7832 if (ps != null) { 7833 ps.firstInstallTime = firstInstallTime; 7834 ps.lastUpdateTime = lastUpdateTime; 7835 } 7836 } 7837 } 7838 7839 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7840 PackageParser.Package changingLib) { 7841 if (file.path != null) { 7842 usesLibraryFiles.add(file.path); 7843 return; 7844 } 7845 PackageParser.Package p = mPackages.get(file.apk); 7846 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7847 // If we are doing this while in the middle of updating a library apk, 7848 // then we need to make sure to use that new apk for determining the 7849 // dependencies here. (We haven't yet finished committing the new apk 7850 // to the package manager state.) 7851 if (p == null || p.packageName.equals(changingLib.packageName)) { 7852 p = changingLib; 7853 } 7854 } 7855 if (p != null) { 7856 usesLibraryFiles.addAll(p.getAllCodePaths()); 7857 } 7858 } 7859 7860 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7861 PackageParser.Package changingLib) throws PackageManagerException { 7862 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7863 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7864 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7865 for (int i=0; i<N; i++) { 7866 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7867 if (file == null) { 7868 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7869 "Package " + pkg.packageName + " requires unavailable shared library " 7870 + pkg.usesLibraries.get(i) + "; failing!"); 7871 } 7872 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7873 } 7874 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7875 for (int i=0; i<N; i++) { 7876 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7877 if (file == null) { 7878 Slog.w(TAG, "Package " + pkg.packageName 7879 + " desires unavailable shared library " 7880 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7881 } else { 7882 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7883 } 7884 } 7885 N = usesLibraryFiles.size(); 7886 if (N > 0) { 7887 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7888 } else { 7889 pkg.usesLibraryFiles = null; 7890 } 7891 } 7892 } 7893 7894 private static boolean hasString(List<String> list, List<String> which) { 7895 if (list == null) { 7896 return false; 7897 } 7898 for (int i=list.size()-1; i>=0; i--) { 7899 for (int j=which.size()-1; j>=0; j--) { 7900 if (which.get(j).equals(list.get(i))) { 7901 return true; 7902 } 7903 } 7904 } 7905 return false; 7906 } 7907 7908 private void updateAllSharedLibrariesLPw() { 7909 for (PackageParser.Package pkg : mPackages.values()) { 7910 try { 7911 updateSharedLibrariesLPw(pkg, null); 7912 } catch (PackageManagerException e) { 7913 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7914 } 7915 } 7916 } 7917 7918 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7919 PackageParser.Package changingPkg) { 7920 ArrayList<PackageParser.Package> res = null; 7921 for (PackageParser.Package pkg : mPackages.values()) { 7922 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7923 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7924 if (res == null) { 7925 res = new ArrayList<PackageParser.Package>(); 7926 } 7927 res.add(pkg); 7928 try { 7929 updateSharedLibrariesLPw(pkg, changingPkg); 7930 } catch (PackageManagerException e) { 7931 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7932 } 7933 } 7934 } 7935 return res; 7936 } 7937 7938 /** 7939 * Derive the value of the {@code cpuAbiOverride} based on the provided 7940 * value and an optional stored value from the package settings. 7941 */ 7942 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7943 String cpuAbiOverride = null; 7944 7945 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7946 cpuAbiOverride = null; 7947 } else if (abiOverride != null) { 7948 cpuAbiOverride = abiOverride; 7949 } else if (settings != null) { 7950 cpuAbiOverride = settings.cpuAbiOverrideString; 7951 } 7952 7953 return cpuAbiOverride; 7954 } 7955 7956 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 7957 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 7958 throws PackageManagerException { 7959 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7960 // If the package has children and this is the first dive in the function 7961 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7962 // whether all packages (parent and children) would be successfully scanned 7963 // before the actual scan since scanning mutates internal state and we want 7964 // to atomically install the package and its children. 7965 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7966 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7967 scanFlags |= SCAN_CHECK_ONLY; 7968 } 7969 } else { 7970 scanFlags &= ~SCAN_CHECK_ONLY; 7971 } 7972 7973 final PackageParser.Package scannedPkg; 7974 try { 7975 // Scan the parent 7976 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 7977 // Scan the children 7978 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7979 for (int i = 0; i < childCount; i++) { 7980 PackageParser.Package childPkg = pkg.childPackages.get(i); 7981 scanPackageLI(childPkg, policyFlags, 7982 scanFlags, currentTime, user); 7983 } 7984 } finally { 7985 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7986 } 7987 7988 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7989 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 7990 } 7991 7992 return scannedPkg; 7993 } 7994 7995 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 7996 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7997 boolean success = false; 7998 try { 7999 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 8000 currentTime, user); 8001 success = true; 8002 return res; 8003 } finally { 8004 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 8005 // DELETE_DATA_ON_FAILURES is only used by frozen paths 8006 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 8007 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 8008 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 8009 } 8010 } 8011 } 8012 8013 /** 8014 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 8015 */ 8016 private static boolean apkHasCode(String fileName) { 8017 StrictJarFile jarFile = null; 8018 try { 8019 jarFile = new StrictJarFile(fileName, 8020 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 8021 return jarFile.findEntry("classes.dex") != null; 8022 } catch (IOException ignore) { 8023 } finally { 8024 try { 8025 jarFile.close(); 8026 } catch (IOException ignore) {} 8027 } 8028 return false; 8029 } 8030 8031 /** 8032 * Enforces code policy for the package. This ensures that if an APK has 8033 * declared hasCode="true" in its manifest that the APK actually contains 8034 * code. 8035 * 8036 * @throws PackageManagerException If bytecode could not be found when it should exist 8037 */ 8038 private static void enforceCodePolicy(PackageParser.Package pkg) 8039 throws PackageManagerException { 8040 final boolean shouldHaveCode = 8041 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 8042 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 8043 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8044 "Package " + pkg.baseCodePath + " code is missing"); 8045 } 8046 8047 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 8048 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 8049 final boolean splitShouldHaveCode = 8050 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 8051 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 8052 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8053 "Package " + pkg.splitCodePaths[i] + " code is missing"); 8054 } 8055 } 8056 } 8057 } 8058 8059 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 8060 final int policyFlags, final int scanFlags, long currentTime, UserHandle user) 8061 throws PackageManagerException { 8062 final File scanFile = new File(pkg.codePath); 8063 if (pkg.applicationInfo.getCodePath() == null || 8064 pkg.applicationInfo.getResourcePath() == null) { 8065 // Bail out. The resource and code paths haven't been set. 8066 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8067 "Code and resource paths haven't been set correctly"); 8068 } 8069 8070 // Apply policy 8071 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 8072 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 8073 if (pkg.applicationInfo.isDirectBootAware()) { 8074 // we're direct boot aware; set for all components 8075 for (PackageParser.Service s : pkg.services) { 8076 s.info.encryptionAware = s.info.directBootAware = true; 8077 } 8078 for (PackageParser.Provider p : pkg.providers) { 8079 p.info.encryptionAware = p.info.directBootAware = true; 8080 } 8081 for (PackageParser.Activity a : pkg.activities) { 8082 a.info.encryptionAware = a.info.directBootAware = true; 8083 } 8084 for (PackageParser.Activity r : pkg.receivers) { 8085 r.info.encryptionAware = r.info.directBootAware = true; 8086 } 8087 } 8088 } else { 8089 // Only allow system apps to be flagged as core apps. 8090 pkg.coreApp = false; 8091 // clear flags not applicable to regular apps 8092 pkg.applicationInfo.privateFlags &= 8093 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 8094 pkg.applicationInfo.privateFlags &= 8095 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 8096 } 8097 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 8098 8099 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 8100 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 8101 } 8102 8103 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 8104 enforceCodePolicy(pkg); 8105 } 8106 8107 if (mCustomResolverComponentName != null && 8108 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 8109 setUpCustomResolverActivity(pkg); 8110 } 8111 8112 if (pkg.packageName.equals("android")) { 8113 synchronized (mPackages) { 8114 if (mAndroidApplication != null) { 8115 Slog.w(TAG, "*************************************************"); 8116 Slog.w(TAG, "Core android package being redefined. Skipping."); 8117 Slog.w(TAG, " file=" + scanFile); 8118 Slog.w(TAG, "*************************************************"); 8119 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 8120 "Core android package being redefined. Skipping."); 8121 } 8122 8123 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8124 // Set up information for our fall-back user intent resolution activity. 8125 mPlatformPackage = pkg; 8126 pkg.mVersionCode = mSdkVersion; 8127 mAndroidApplication = pkg.applicationInfo; 8128 8129 if (!mResolverReplaced) { 8130 mResolveActivity.applicationInfo = mAndroidApplication; 8131 mResolveActivity.name = ResolverActivity.class.getName(); 8132 mResolveActivity.packageName = mAndroidApplication.packageName; 8133 mResolveActivity.processName = "system:ui"; 8134 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8135 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 8136 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 8137 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 8138 mResolveActivity.exported = true; 8139 mResolveActivity.enabled = true; 8140 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 8141 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 8142 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 8143 | ActivityInfo.CONFIG_SCREEN_LAYOUT 8144 | ActivityInfo.CONFIG_ORIENTATION 8145 | ActivityInfo.CONFIG_KEYBOARD 8146 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 8147 mResolveInfo.activityInfo = mResolveActivity; 8148 mResolveInfo.priority = 0; 8149 mResolveInfo.preferredOrder = 0; 8150 mResolveInfo.match = 0; 8151 mResolveComponentName = new ComponentName( 8152 mAndroidApplication.packageName, mResolveActivity.name); 8153 } 8154 } 8155 } 8156 } 8157 8158 if (DEBUG_PACKAGE_SCANNING) { 8159 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8160 Log.d(TAG, "Scanning package " + pkg.packageName); 8161 } 8162 8163 synchronized (mPackages) { 8164 if (mPackages.containsKey(pkg.packageName) 8165 || mSharedLibraries.containsKey(pkg.packageName)) { 8166 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 8167 "Application package " + pkg.packageName 8168 + " already installed. Skipping duplicate."); 8169 } 8170 8171 // If we're only installing presumed-existing packages, require that the 8172 // scanned APK is both already known and at the path previously established 8173 // for it. Previously unknown packages we pick up normally, but if we have an 8174 // a priori expectation about this package's install presence, enforce it. 8175 // With a singular exception for new system packages. When an OTA contains 8176 // a new system package, we allow the codepath to change from a system location 8177 // to the user-installed location. If we don't allow this change, any newer, 8178 // user-installed version of the application will be ignored. 8179 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 8180 if (mExpectingBetter.containsKey(pkg.packageName)) { 8181 logCriticalInfo(Log.WARN, 8182 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 8183 } else { 8184 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 8185 if (known != null) { 8186 if (DEBUG_PACKAGE_SCANNING) { 8187 Log.d(TAG, "Examining " + pkg.codePath 8188 + " and requiring known paths " + known.codePathString 8189 + " & " + known.resourcePathString); 8190 } 8191 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 8192 || !pkg.applicationInfo.getResourcePath().equals( 8193 known.resourcePathString)) { 8194 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 8195 "Application package " + pkg.packageName 8196 + " found at " + pkg.applicationInfo.getCodePath() 8197 + " but expected at " + known.codePathString 8198 + "; ignoring."); 8199 } 8200 } 8201 } 8202 } 8203 } 8204 8205 // Initialize package source and resource directories 8206 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 8207 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 8208 8209 SharedUserSetting suid = null; 8210 PackageSetting pkgSetting = null; 8211 8212 if (!isSystemApp(pkg)) { 8213 // Only system apps can use these features. 8214 pkg.mOriginalPackages = null; 8215 pkg.mRealPackage = null; 8216 pkg.mAdoptPermissions = null; 8217 } 8218 8219 // Getting the package setting may have a side-effect, so if we 8220 // are only checking if scan would succeed, stash a copy of the 8221 // old setting to restore at the end. 8222 PackageSetting nonMutatedPs = null; 8223 8224 // writer 8225 synchronized (mPackages) { 8226 if (pkg.mSharedUserId != null) { 8227 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 8228 if (suid == null) { 8229 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8230 "Creating application package " + pkg.packageName 8231 + " for shared user failed"); 8232 } 8233 if (DEBUG_PACKAGE_SCANNING) { 8234 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8235 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 8236 + "): packages=" + suid.packages); 8237 } 8238 } 8239 8240 // Check if we are renaming from an original package name. 8241 PackageSetting origPackage = null; 8242 String realName = null; 8243 if (pkg.mOriginalPackages != null) { 8244 // This package may need to be renamed to a previously 8245 // installed name. Let's check on that... 8246 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 8247 if (pkg.mOriginalPackages.contains(renamed)) { 8248 // This package had originally been installed as the 8249 // original name, and we have already taken care of 8250 // transitioning to the new one. Just update the new 8251 // one to continue using the old name. 8252 realName = pkg.mRealPackage; 8253 if (!pkg.packageName.equals(renamed)) { 8254 // Callers into this function may have already taken 8255 // care of renaming the package; only do it here if 8256 // it is not already done. 8257 pkg.setPackageName(renamed); 8258 } 8259 8260 } else { 8261 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 8262 if ((origPackage = mSettings.peekPackageLPr( 8263 pkg.mOriginalPackages.get(i))) != null) { 8264 // We do have the package already installed under its 8265 // original name... should we use it? 8266 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 8267 // New package is not compatible with original. 8268 origPackage = null; 8269 continue; 8270 } else if (origPackage.sharedUser != null) { 8271 // Make sure uid is compatible between packages. 8272 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 8273 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 8274 + " to " + pkg.packageName + ": old uid " 8275 + origPackage.sharedUser.name 8276 + " differs from " + pkg.mSharedUserId); 8277 origPackage = null; 8278 continue; 8279 } 8280 // TODO: Add case when shared user id is added [b/28144775] 8281 } else { 8282 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 8283 + pkg.packageName + " to old name " + origPackage.name); 8284 } 8285 break; 8286 } 8287 } 8288 } 8289 } 8290 8291 if (mTransferedPackages.contains(pkg.packageName)) { 8292 Slog.w(TAG, "Package " + pkg.packageName 8293 + " was transferred to another, but its .apk remains"); 8294 } 8295 8296 // See comments in nonMutatedPs declaration 8297 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8298 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 8299 if (foundPs != null) { 8300 nonMutatedPs = new PackageSetting(foundPs); 8301 } 8302 } 8303 8304 // Just create the setting, don't add it yet. For already existing packages 8305 // the PkgSetting exists already and doesn't have to be created. 8306 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 8307 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 8308 pkg.applicationInfo.primaryCpuAbi, 8309 pkg.applicationInfo.secondaryCpuAbi, 8310 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 8311 user, false); 8312 if (pkgSetting == null) { 8313 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8314 "Creating application package " + pkg.packageName + " failed"); 8315 } 8316 8317 if (pkgSetting.origPackage != null) { 8318 // If we are first transitioning from an original package, 8319 // fix up the new package's name now. We need to do this after 8320 // looking up the package under its new name, so getPackageLP 8321 // can take care of fiddling things correctly. 8322 pkg.setPackageName(origPackage.name); 8323 8324 // File a report about this. 8325 String msg = "New package " + pkgSetting.realName 8326 + " renamed to replace old package " + pkgSetting.name; 8327 reportSettingsProblem(Log.WARN, msg); 8328 8329 // Make a note of it. 8330 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8331 mTransferedPackages.add(origPackage.name); 8332 } 8333 8334 // No longer need to retain this. 8335 pkgSetting.origPackage = null; 8336 } 8337 8338 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 8339 // Make a note of it. 8340 mTransferedPackages.add(pkg.packageName); 8341 } 8342 8343 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 8344 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 8345 } 8346 8347 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8348 // Check all shared libraries and map to their actual file path. 8349 // We only do this here for apps not on a system dir, because those 8350 // are the only ones that can fail an install due to this. We 8351 // will take care of the system apps by updating all of their 8352 // library paths after the scan is done. 8353 updateSharedLibrariesLPw(pkg, null); 8354 } 8355 8356 if (mFoundPolicyFile) { 8357 SELinuxMMAC.assignSeinfoValue(pkg); 8358 } 8359 8360 pkg.applicationInfo.uid = pkgSetting.appId; 8361 pkg.mExtras = pkgSetting; 8362 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 8363 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 8364 // We just determined the app is signed correctly, so bring 8365 // over the latest parsed certs. 8366 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8367 } else { 8368 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8369 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8370 "Package " + pkg.packageName + " upgrade keys do not match the " 8371 + "previously installed version"); 8372 } else { 8373 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8374 String msg = "System package " + pkg.packageName 8375 + " signature changed; retaining data."; 8376 reportSettingsProblem(Log.WARN, msg); 8377 } 8378 } 8379 } else { 8380 try { 8381 verifySignaturesLP(pkgSetting, pkg); 8382 // We just determined the app is signed correctly, so bring 8383 // over the latest parsed certs. 8384 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8385 } catch (PackageManagerException e) { 8386 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8387 throw e; 8388 } 8389 // The signature has changed, but this package is in the system 8390 // image... let's recover! 8391 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8392 // However... if this package is part of a shared user, but it 8393 // doesn't match the signature of the shared user, let's fail. 8394 // What this means is that you can't change the signatures 8395 // associated with an overall shared user, which doesn't seem all 8396 // that unreasonable. 8397 if (pkgSetting.sharedUser != null) { 8398 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8399 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 8400 throw new PackageManagerException( 8401 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 8402 "Signature mismatch for shared user: " 8403 + pkgSetting.sharedUser); 8404 } 8405 } 8406 // File a report about this. 8407 String msg = "System package " + pkg.packageName 8408 + " signature changed; retaining data."; 8409 reportSettingsProblem(Log.WARN, msg); 8410 } 8411 } 8412 // Verify that this new package doesn't have any content providers 8413 // that conflict with existing packages. Only do this if the 8414 // package isn't already installed, since we don't want to break 8415 // things that are installed. 8416 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 8417 final int N = pkg.providers.size(); 8418 int i; 8419 for (i=0; i<N; i++) { 8420 PackageParser.Provider p = pkg.providers.get(i); 8421 if (p.info.authority != null) { 8422 String names[] = p.info.authority.split(";"); 8423 for (int j = 0; j < names.length; j++) { 8424 if (mProvidersByAuthority.containsKey(names[j])) { 8425 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8426 final String otherPackageName = 8427 ((other != null && other.getComponentName() != null) ? 8428 other.getComponentName().getPackageName() : "?"); 8429 throw new PackageManagerException( 8430 INSTALL_FAILED_CONFLICTING_PROVIDER, 8431 "Can't install because provider name " + names[j] 8432 + " (in package " + pkg.applicationInfo.packageName 8433 + ") is already used by " + otherPackageName); 8434 } 8435 } 8436 } 8437 } 8438 } 8439 8440 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 8441 // This package wants to adopt ownership of permissions from 8442 // another package. 8443 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 8444 final String origName = pkg.mAdoptPermissions.get(i); 8445 final PackageSetting orig = mSettings.peekPackageLPr(origName); 8446 if (orig != null) { 8447 if (verifyPackageUpdateLPr(orig, pkg)) { 8448 Slog.i(TAG, "Adopting permissions from " + origName + " to " 8449 + pkg.packageName); 8450 mSettings.transferPermissionsLPw(origName, pkg.packageName); 8451 } 8452 } 8453 } 8454 } 8455 } 8456 8457 final String pkgName = pkg.packageName; 8458 8459 final long scanFileTime = getLastModifiedTime(pkg, scanFile); 8460 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 8461 pkg.applicationInfo.processName = fixProcessName( 8462 pkg.applicationInfo.packageName, 8463 pkg.applicationInfo.processName, 8464 pkg.applicationInfo.uid); 8465 8466 if (pkg != mPlatformPackage) { 8467 // Get all of our default paths setup 8468 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 8469 } 8470 8471 final String path = scanFile.getPath(); 8472 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 8473 8474 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 8475 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 8476 8477 // Some system apps still use directory structure for native libraries 8478 // in which case we might end up not detecting abi solely based on apk 8479 // structure. Try to detect abi based on directory structure. 8480 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 8481 pkg.applicationInfo.primaryCpuAbi == null) { 8482 setBundledAppAbisAndRoots(pkg, pkgSetting); 8483 setNativeLibraryPaths(pkg); 8484 } 8485 8486 } else { 8487 if ((scanFlags & SCAN_MOVE) != 0) { 8488 // We haven't run dex-opt for this move (since we've moved the compiled output too) 8489 // but we already have this packages package info in the PackageSetting. We just 8490 // use that and derive the native library path based on the new codepath. 8491 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 8492 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 8493 } 8494 8495 // Set native library paths again. For moves, the path will be updated based on the 8496 // ABIs we've determined above. For non-moves, the path will be updated based on the 8497 // ABIs we determined during compilation, but the path will depend on the final 8498 // package path (after the rename away from the stage path). 8499 setNativeLibraryPaths(pkg); 8500 } 8501 8502 // This is a special case for the "system" package, where the ABI is 8503 // dictated by the zygote configuration (and init.rc). We should keep track 8504 // of this ABI so that we can deal with "normal" applications that run under 8505 // the same UID correctly. 8506 if (mPlatformPackage == pkg) { 8507 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 8508 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 8509 } 8510 8511 // If there's a mismatch between the abi-override in the package setting 8512 // and the abiOverride specified for the install. Warn about this because we 8513 // would've already compiled the app without taking the package setting into 8514 // account. 8515 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 8516 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 8517 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 8518 " for package " + pkg.packageName); 8519 } 8520 } 8521 8522 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8523 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8524 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 8525 8526 // Copy the derived override back to the parsed package, so that we can 8527 // update the package settings accordingly. 8528 pkg.cpuAbiOverride = cpuAbiOverride; 8529 8530 if (DEBUG_ABI_SELECTION) { 8531 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 8532 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 8533 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 8534 } 8535 8536 // Push the derived path down into PackageSettings so we know what to 8537 // clean up at uninstall time. 8538 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 8539 8540 if (DEBUG_ABI_SELECTION) { 8541 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 8542 " primary=" + pkg.applicationInfo.primaryCpuAbi + 8543 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 8544 } 8545 8546 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 8547 // We don't do this here during boot because we can do it all 8548 // at once after scanning all existing packages. 8549 // 8550 // We also do this *before* we perform dexopt on this package, so that 8551 // we can avoid redundant dexopts, and also to make sure we've got the 8552 // code and package path correct. 8553 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 8554 pkg, true /* boot complete */); 8555 } 8556 8557 if (mFactoryTest && pkg.requestedPermissions.contains( 8558 android.Manifest.permission.FACTORY_TEST)) { 8559 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 8560 } 8561 8562 ArrayList<PackageParser.Package> clientLibPkgs = null; 8563 8564 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8565 if (nonMutatedPs != null) { 8566 synchronized (mPackages) { 8567 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 8568 } 8569 } 8570 return pkg; 8571 } 8572 8573 // Only privileged apps and updated privileged apps can add child packages. 8574 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 8575 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 8576 throw new PackageManagerException("Only privileged apps and updated " 8577 + "privileged apps can add child packages. Ignoring package " 8578 + pkg.packageName); 8579 } 8580 final int childCount = pkg.childPackages.size(); 8581 for (int i = 0; i < childCount; i++) { 8582 PackageParser.Package childPkg = pkg.childPackages.get(i); 8583 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 8584 childPkg.packageName)) { 8585 throw new PackageManagerException("Cannot override a child package of " 8586 + "another disabled system app. Ignoring package " + pkg.packageName); 8587 } 8588 } 8589 } 8590 8591 // writer 8592 synchronized (mPackages) { 8593 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8594 // Only system apps can add new shared libraries. 8595 if (pkg.libraryNames != null) { 8596 for (int i=0; i<pkg.libraryNames.size(); i++) { 8597 String name = pkg.libraryNames.get(i); 8598 boolean allowed = false; 8599 if (pkg.isUpdatedSystemApp()) { 8600 // New library entries can only be added through the 8601 // system image. This is important to get rid of a lot 8602 // of nasty edge cases: for example if we allowed a non- 8603 // system update of the app to add a library, then uninstalling 8604 // the update would make the library go away, and assumptions 8605 // we made such as through app install filtering would now 8606 // have allowed apps on the device which aren't compatible 8607 // with it. Better to just have the restriction here, be 8608 // conservative, and create many fewer cases that can negatively 8609 // impact the user experience. 8610 final PackageSetting sysPs = mSettings 8611 .getDisabledSystemPkgLPr(pkg.packageName); 8612 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 8613 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 8614 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 8615 allowed = true; 8616 break; 8617 } 8618 } 8619 } 8620 } else { 8621 allowed = true; 8622 } 8623 if (allowed) { 8624 if (!mSharedLibraries.containsKey(name)) { 8625 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 8626 } else if (!name.equals(pkg.packageName)) { 8627 Slog.w(TAG, "Package " + pkg.packageName + " library " 8628 + name + " already exists; skipping"); 8629 } 8630 } else { 8631 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 8632 + name + " that is not declared on system image; skipping"); 8633 } 8634 } 8635 if ((scanFlags & SCAN_BOOTING) == 0) { 8636 // If we are not booting, we need to update any applications 8637 // that are clients of our shared library. If we are booting, 8638 // this will all be done once the scan is complete. 8639 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 8640 } 8641 } 8642 } 8643 } 8644 8645 if ((scanFlags & SCAN_BOOTING) != 0) { 8646 // No apps can run during boot scan, so they don't need to be frozen 8647 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 8648 // Caller asked to not kill app, so it's probably not frozen 8649 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 8650 // Caller asked us to ignore frozen check for some reason; they 8651 // probably didn't know the package name 8652 } else { 8653 // We're doing major surgery on this package, so it better be frozen 8654 // right now to keep it from launching 8655 checkPackageFrozen(pkgName); 8656 } 8657 8658 // Also need to kill any apps that are dependent on the library. 8659 if (clientLibPkgs != null) { 8660 for (int i=0; i<clientLibPkgs.size(); i++) { 8661 PackageParser.Package clientPkg = clientLibPkgs.get(i); 8662 killApplication(clientPkg.applicationInfo.packageName, 8663 clientPkg.applicationInfo.uid, "update lib"); 8664 } 8665 } 8666 8667 // Make sure we're not adding any bogus keyset info 8668 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8669 ksms.assertScannedPackageValid(pkg); 8670 8671 // writer 8672 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 8673 8674 boolean createIdmapFailed = false; 8675 synchronized (mPackages) { 8676 // We don't expect installation to fail beyond this point 8677 8678 if (pkgSetting.pkg != null) { 8679 // Note that |user| might be null during the initial boot scan. If a codePath 8680 // for an app has changed during a boot scan, it's due to an app update that's 8681 // part of the system partition and marker changes must be applied to all users. 8682 maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, 8683 (user != null) ? user : UserHandle.ALL); 8684 } 8685 8686 // Add the new setting to mSettings 8687 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 8688 // Add the new setting to mPackages 8689 mPackages.put(pkg.applicationInfo.packageName, pkg); 8690 // Make sure we don't accidentally delete its data. 8691 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 8692 while (iter.hasNext()) { 8693 PackageCleanItem item = iter.next(); 8694 if (pkgName.equals(item.packageName)) { 8695 iter.remove(); 8696 } 8697 } 8698 8699 // Take care of first install / last update times. 8700 if (currentTime != 0) { 8701 if (pkgSetting.firstInstallTime == 0) { 8702 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8703 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 8704 pkgSetting.lastUpdateTime = currentTime; 8705 } 8706 } else if (pkgSetting.firstInstallTime == 0) { 8707 // We need *something*. Take time time stamp of the file. 8708 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8709 } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8710 if (scanFileTime != pkgSetting.timeStamp) { 8711 // A package on the system image has changed; consider this 8712 // to be an update. 8713 pkgSetting.lastUpdateTime = scanFileTime; 8714 } 8715 } 8716 8717 // Add the package's KeySets to the global KeySetManagerService 8718 ksms.addScannedPackageLPw(pkg); 8719 8720 int N = pkg.providers.size(); 8721 StringBuilder r = null; 8722 int i; 8723 for (i=0; i<N; i++) { 8724 PackageParser.Provider p = pkg.providers.get(i); 8725 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 8726 p.info.processName, pkg.applicationInfo.uid); 8727 mProviders.addProvider(p); 8728 p.syncable = p.info.isSyncable; 8729 if (p.info.authority != null) { 8730 String names[] = p.info.authority.split(";"); 8731 p.info.authority = null; 8732 for (int j = 0; j < names.length; j++) { 8733 if (j == 1 && p.syncable) { 8734 // We only want the first authority for a provider to possibly be 8735 // syncable, so if we already added this provider using a different 8736 // authority clear the syncable flag. We copy the provider before 8737 // changing it because the mProviders object contains a reference 8738 // to a provider that we don't want to change. 8739 // Only do this for the second authority since the resulting provider 8740 // object can be the same for all future authorities for this provider. 8741 p = new PackageParser.Provider(p); 8742 p.syncable = false; 8743 } 8744 if (!mProvidersByAuthority.containsKey(names[j])) { 8745 mProvidersByAuthority.put(names[j], p); 8746 if (p.info.authority == null) { 8747 p.info.authority = names[j]; 8748 } else { 8749 p.info.authority = p.info.authority + ";" + names[j]; 8750 } 8751 if (DEBUG_PACKAGE_SCANNING) { 8752 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8753 Log.d(TAG, "Registered content provider: " + names[j] 8754 + ", className = " + p.info.name + ", isSyncable = " 8755 + p.info.isSyncable); 8756 } 8757 } else { 8758 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8759 Slog.w(TAG, "Skipping provider name " + names[j] + 8760 " (in package " + pkg.applicationInfo.packageName + 8761 "): name already used by " 8762 + ((other != null && other.getComponentName() != null) 8763 ? other.getComponentName().getPackageName() : "?")); 8764 } 8765 } 8766 } 8767 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8768 if (r == null) { 8769 r = new StringBuilder(256); 8770 } else { 8771 r.append(' '); 8772 } 8773 r.append(p.info.name); 8774 } 8775 } 8776 if (r != null) { 8777 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8778 } 8779 8780 N = pkg.services.size(); 8781 r = null; 8782 for (i=0; i<N; i++) { 8783 PackageParser.Service s = pkg.services.get(i); 8784 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8785 s.info.processName, pkg.applicationInfo.uid); 8786 mServices.addService(s); 8787 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8788 if (r == null) { 8789 r = new StringBuilder(256); 8790 } else { 8791 r.append(' '); 8792 } 8793 r.append(s.info.name); 8794 } 8795 } 8796 if (r != null) { 8797 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8798 } 8799 8800 N = pkg.receivers.size(); 8801 r = null; 8802 for (i=0; i<N; i++) { 8803 PackageParser.Activity a = pkg.receivers.get(i); 8804 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8805 a.info.processName, pkg.applicationInfo.uid); 8806 mReceivers.addActivity(a, "receiver"); 8807 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8808 if (r == null) { 8809 r = new StringBuilder(256); 8810 } else { 8811 r.append(' '); 8812 } 8813 r.append(a.info.name); 8814 } 8815 } 8816 if (r != null) { 8817 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8818 } 8819 8820 N = pkg.activities.size(); 8821 r = null; 8822 for (i=0; i<N; i++) { 8823 PackageParser.Activity a = pkg.activities.get(i); 8824 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8825 a.info.processName, pkg.applicationInfo.uid); 8826 mActivities.addActivity(a, "activity"); 8827 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8828 if (r == null) { 8829 r = new StringBuilder(256); 8830 } else { 8831 r.append(' '); 8832 } 8833 r.append(a.info.name); 8834 } 8835 } 8836 if (r != null) { 8837 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8838 } 8839 8840 N = pkg.permissionGroups.size(); 8841 r = null; 8842 for (i=0; i<N; i++) { 8843 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8844 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8845 if (cur == null) { 8846 mPermissionGroups.put(pg.info.name, pg); 8847 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8848 if (r == null) { 8849 r = new StringBuilder(256); 8850 } else { 8851 r.append(' '); 8852 } 8853 r.append(pg.info.name); 8854 } 8855 } else { 8856 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8857 + pg.info.packageName + " ignored: original from " 8858 + cur.info.packageName); 8859 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8860 if (r == null) { 8861 r = new StringBuilder(256); 8862 } else { 8863 r.append(' '); 8864 } 8865 r.append("DUP:"); 8866 r.append(pg.info.name); 8867 } 8868 } 8869 } 8870 if (r != null) { 8871 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8872 } 8873 8874 N = pkg.permissions.size(); 8875 r = null; 8876 for (i=0; i<N; i++) { 8877 PackageParser.Permission p = pkg.permissions.get(i); 8878 8879 // Assume by default that we did not install this permission into the system. 8880 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8881 8882 // Now that permission groups have a special meaning, we ignore permission 8883 // groups for legacy apps to prevent unexpected behavior. In particular, 8884 // permissions for one app being granted to someone just becase they happen 8885 // to be in a group defined by another app (before this had no implications). 8886 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8887 p.group = mPermissionGroups.get(p.info.group); 8888 // Warn for a permission in an unknown group. 8889 if (p.info.group != null && p.group == null) { 8890 Slog.w(TAG, "Permission " + p.info.name + " from package " 8891 + p.info.packageName + " in an unknown group " + p.info.group); 8892 } 8893 } 8894 8895 ArrayMap<String, BasePermission> permissionMap = 8896 p.tree ? mSettings.mPermissionTrees 8897 : mSettings.mPermissions; 8898 BasePermission bp = permissionMap.get(p.info.name); 8899 8900 // Allow system apps to redefine non-system permissions 8901 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8902 final boolean currentOwnerIsSystem = (bp.perm != null 8903 && isSystemApp(bp.perm.owner)); 8904 if (isSystemApp(p.owner)) { 8905 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8906 // It's a built-in permission and no owner, take ownership now 8907 bp.packageSetting = pkgSetting; 8908 bp.perm = p; 8909 bp.uid = pkg.applicationInfo.uid; 8910 bp.sourcePackage = p.info.packageName; 8911 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8912 } else if (!currentOwnerIsSystem) { 8913 String msg = "New decl " + p.owner + " of permission " 8914 + p.info.name + " is system; overriding " + bp.sourcePackage; 8915 reportSettingsProblem(Log.WARN, msg); 8916 bp = null; 8917 } 8918 } 8919 } 8920 8921 if (bp == null) { 8922 bp = new BasePermission(p.info.name, p.info.packageName, 8923 BasePermission.TYPE_NORMAL); 8924 permissionMap.put(p.info.name, bp); 8925 } 8926 8927 if (bp.perm == null) { 8928 if (bp.sourcePackage == null 8929 || bp.sourcePackage.equals(p.info.packageName)) { 8930 BasePermission tree = findPermissionTreeLP(p.info.name); 8931 if (tree == null 8932 || tree.sourcePackage.equals(p.info.packageName)) { 8933 bp.packageSetting = pkgSetting; 8934 bp.perm = p; 8935 bp.uid = pkg.applicationInfo.uid; 8936 bp.sourcePackage = p.info.packageName; 8937 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8938 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8939 if (r == null) { 8940 r = new StringBuilder(256); 8941 } else { 8942 r.append(' '); 8943 } 8944 r.append(p.info.name); 8945 } 8946 } else { 8947 Slog.w(TAG, "Permission " + p.info.name + " from package " 8948 + p.info.packageName + " ignored: base tree " 8949 + tree.name + " is from package " 8950 + tree.sourcePackage); 8951 } 8952 } else { 8953 Slog.w(TAG, "Permission " + p.info.name + " from package " 8954 + p.info.packageName + " ignored: original from " 8955 + bp.sourcePackage); 8956 } 8957 } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8958 if (r == null) { 8959 r = new StringBuilder(256); 8960 } else { 8961 r.append(' '); 8962 } 8963 r.append("DUP:"); 8964 r.append(p.info.name); 8965 } 8966 if (bp.perm == p) { 8967 bp.protectionLevel = p.info.protectionLevel; 8968 } 8969 } 8970 8971 if (r != null) { 8972 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 8973 } 8974 8975 N = pkg.instrumentation.size(); 8976 r = null; 8977 for (i=0; i<N; i++) { 8978 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8979 a.info.packageName = pkg.applicationInfo.packageName; 8980 a.info.sourceDir = pkg.applicationInfo.sourceDir; 8981 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 8982 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 8983 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 8984 a.info.dataDir = pkg.applicationInfo.dataDir; 8985 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 8986 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 8987 8988 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 8989 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 8990 mInstrumentation.put(a.getComponentName(), a); 8991 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8992 if (r == null) { 8993 r = new StringBuilder(256); 8994 } else { 8995 r.append(' '); 8996 } 8997 r.append(a.info.name); 8998 } 8999 } 9000 if (r != null) { 9001 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 9002 } 9003 9004 if (pkg.protectedBroadcasts != null) { 9005 N = pkg.protectedBroadcasts.size(); 9006 for (i=0; i<N; i++) { 9007 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 9008 } 9009 } 9010 9011 pkgSetting.setTimeStamp(scanFileTime); 9012 9013 // Create idmap files for pairs of (packages, overlay packages). 9014 // Note: "android", ie framework-res.apk, is handled by native layers. 9015 if (pkg.mOverlayTarget != null) { 9016 // This is an overlay package. 9017 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 9018 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 9019 mOverlays.put(pkg.mOverlayTarget, 9020 new ArrayMap<String, PackageParser.Package>()); 9021 } 9022 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 9023 map.put(pkg.packageName, pkg); 9024 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 9025 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 9026 createIdmapFailed = true; 9027 } 9028 } 9029 } else if (mOverlays.containsKey(pkg.packageName) && 9030 !pkg.packageName.equals("android")) { 9031 // This is a regular package, with one or more known overlay packages. 9032 createIdmapsForPackageLI(pkg); 9033 } 9034 } 9035 9036 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9037 9038 if (createIdmapFailed) { 9039 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 9040 "scanPackageLI failed to createIdmap"); 9041 } 9042 return pkg; 9043 } 9044 9045 private void maybeRenameForeignDexMarkers(PackageParser.Package existing, 9046 PackageParser.Package update, UserHandle user) { 9047 if (existing.applicationInfo == null || update.applicationInfo == null) { 9048 // This isn't due to an app installation. 9049 return; 9050 } 9051 9052 final File oldCodePath = new File(existing.applicationInfo.getCodePath()); 9053 final File newCodePath = new File(update.applicationInfo.getCodePath()); 9054 9055 // The codePath hasn't changed, so there's nothing for us to do. 9056 if (Objects.equals(oldCodePath, newCodePath)) { 9057 return; 9058 } 9059 9060 File canonicalNewCodePath; 9061 try { 9062 canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath)); 9063 } catch (IOException e) { 9064 Slog.w(TAG, "Failed to get canonical path.", e); 9065 return; 9066 } 9067 9068 // This is a bit of a hack. The oldCodePath doesn't exist at this point (because 9069 // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume 9070 // that the last component of the path (i.e, the name) doesn't need canonicalization 9071 // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now 9072 // but may change in the future. Hopefully this function won't exist at that point. 9073 final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(), 9074 oldCodePath.getName()); 9075 9076 // Calculate the prefixes of the markers. These are just the paths with "/" replaced 9077 // with "@". 9078 String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@'); 9079 if (!oldMarkerPrefix.endsWith("@")) { 9080 oldMarkerPrefix += "@"; 9081 } 9082 String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@'); 9083 if (!newMarkerPrefix.endsWith("@")) { 9084 newMarkerPrefix += "@"; 9085 } 9086 9087 List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly(); 9088 List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size()); 9089 for (String updatedPath : updatedPaths) { 9090 String updatedPathName = new File(updatedPath).getName(); 9091 markerSuffixes.add(updatedPathName.replace('/', '@')); 9092 } 9093 9094 for (int userId : resolveUserIds(user.getIdentifier())) { 9095 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId); 9096 9097 for (String markerSuffix : markerSuffixes) { 9098 File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix); 9099 File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix); 9100 if (oldForeignUseMark.exists()) { 9101 try { 9102 Os.rename(oldForeignUseMark.getAbsolutePath(), 9103 newForeignUseMark.getAbsolutePath()); 9104 } catch (ErrnoException e) { 9105 Slog.w(TAG, "Failed to rename foreign use marker", e); 9106 oldForeignUseMark.delete(); 9107 } 9108 } 9109 } 9110 } 9111 } 9112 9113 /** 9114 * Derive the ABI of a non-system package located at {@code scanFile}. This information 9115 * is derived purely on the basis of the contents of {@code scanFile} and 9116 * {@code cpuAbiOverride}. 9117 * 9118 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 9119 */ 9120 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 9121 String cpuAbiOverride, boolean extractLibs) 9122 throws PackageManagerException { 9123 // TODO: We can probably be smarter about this stuff. For installed apps, 9124 // we can calculate this information at install time once and for all. For 9125 // system apps, we can probably assume that this information doesn't change 9126 // after the first boot scan. As things stand, we do lots of unnecessary work. 9127 9128 // Give ourselves some initial paths; we'll come back for another 9129 // pass once we've determined ABI below. 9130 setNativeLibraryPaths(pkg); 9131 9132 // We would never need to extract libs for forward-locked and external packages, 9133 // since the container service will do it for us. We shouldn't attempt to 9134 // extract libs from system app when it was not updated. 9135 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 9136 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 9137 extractLibs = false; 9138 } 9139 9140 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 9141 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 9142 9143 NativeLibraryHelper.Handle handle = null; 9144 try { 9145 handle = NativeLibraryHelper.Handle.create(pkg); 9146 // TODO(multiArch): This can be null for apps that didn't go through the 9147 // usual installation process. We can calculate it again, like we 9148 // do during install time. 9149 // 9150 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 9151 // unnecessary. 9152 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 9153 9154 // Null out the abis so that they can be recalculated. 9155 pkg.applicationInfo.primaryCpuAbi = null; 9156 pkg.applicationInfo.secondaryCpuAbi = null; 9157 if (isMultiArch(pkg.applicationInfo)) { 9158 // Warn if we've set an abiOverride for multi-lib packages.. 9159 // By definition, we need to copy both 32 and 64 bit libraries for 9160 // such packages. 9161 if (pkg.cpuAbiOverride != null 9162 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 9163 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 9164 } 9165 9166 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 9167 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 9168 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 9169 if (extractLibs) { 9170 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9171 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 9172 useIsaSpecificSubdirs); 9173 } else { 9174 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 9175 } 9176 } 9177 9178 maybeThrowExceptionForMultiArchCopy( 9179 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 9180 9181 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 9182 if (extractLibs) { 9183 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9184 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 9185 useIsaSpecificSubdirs); 9186 } else { 9187 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 9188 } 9189 } 9190 9191 maybeThrowExceptionForMultiArchCopy( 9192 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 9193 9194 if (abi64 >= 0) { 9195 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 9196 } 9197 9198 if (abi32 >= 0) { 9199 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 9200 if (abi64 >= 0) { 9201 if (pkg.use32bitAbi) { 9202 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 9203 pkg.applicationInfo.primaryCpuAbi = abi; 9204 } else { 9205 pkg.applicationInfo.secondaryCpuAbi = abi; 9206 } 9207 } else { 9208 pkg.applicationInfo.primaryCpuAbi = abi; 9209 } 9210 } 9211 9212 } else { 9213 String[] abiList = (cpuAbiOverride != null) ? 9214 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 9215 9216 // Enable gross and lame hacks for apps that are built with old 9217 // SDK tools. We must scan their APKs for renderscript bitcode and 9218 // not launch them if it's present. Don't bother checking on devices 9219 // that don't have 64 bit support. 9220 boolean needsRenderScriptOverride = false; 9221 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 9222 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 9223 abiList = Build.SUPPORTED_32_BIT_ABIS; 9224 needsRenderScriptOverride = true; 9225 } 9226 9227 final int copyRet; 9228 if (extractLibs) { 9229 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9230 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 9231 } else { 9232 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 9233 } 9234 9235 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 9236 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 9237 "Error unpackaging native libs for app, errorCode=" + copyRet); 9238 } 9239 9240 if (copyRet >= 0) { 9241 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 9242 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 9243 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 9244 } else if (needsRenderScriptOverride) { 9245 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 9246 } 9247 } 9248 } catch (IOException ioe) { 9249 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 9250 } finally { 9251 IoUtils.closeQuietly(handle); 9252 } 9253 9254 // Now that we've calculated the ABIs and determined if it's an internal app, 9255 // we will go ahead and populate the nativeLibraryPath. 9256 setNativeLibraryPaths(pkg); 9257 } 9258 9259 /** 9260 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 9261 * i.e, so that all packages can be run inside a single process if required. 9262 * 9263 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 9264 * this function will either try and make the ABI for all packages in {@code packagesForUser} 9265 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 9266 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 9267 * updating a package that belongs to a shared user. 9268 * 9269 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 9270 * adds unnecessary complexity. 9271 */ 9272 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 9273 PackageParser.Package scannedPackage, boolean bootComplete) { 9274 String requiredInstructionSet = null; 9275 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 9276 requiredInstructionSet = VMRuntime.getInstructionSet( 9277 scannedPackage.applicationInfo.primaryCpuAbi); 9278 } 9279 9280 PackageSetting requirer = null; 9281 for (PackageSetting ps : packagesForUser) { 9282 // If packagesForUser contains scannedPackage, we skip it. This will happen 9283 // when scannedPackage is an update of an existing package. Without this check, 9284 // we will never be able to change the ABI of any package belonging to a shared 9285 // user, even if it's compatible with other packages. 9286 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9287 if (ps.primaryCpuAbiString == null) { 9288 continue; 9289 } 9290 9291 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 9292 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 9293 // We have a mismatch between instruction sets (say arm vs arm64) warn about 9294 // this but there's not much we can do. 9295 String errorMessage = "Instruction set mismatch, " 9296 + ((requirer == null) ? "[caller]" : requirer) 9297 + " requires " + requiredInstructionSet + " whereas " + ps 9298 + " requires " + instructionSet; 9299 Slog.w(TAG, errorMessage); 9300 } 9301 9302 if (requiredInstructionSet == null) { 9303 requiredInstructionSet = instructionSet; 9304 requirer = ps; 9305 } 9306 } 9307 } 9308 9309 if (requiredInstructionSet != null) { 9310 String adjustedAbi; 9311 if (requirer != null) { 9312 // requirer != null implies that either scannedPackage was null or that scannedPackage 9313 // did not require an ABI, in which case we have to adjust scannedPackage to match 9314 // the ABI of the set (which is the same as requirer's ABI) 9315 adjustedAbi = requirer.primaryCpuAbiString; 9316 if (scannedPackage != null) { 9317 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 9318 } 9319 } else { 9320 // requirer == null implies that we're updating all ABIs in the set to 9321 // match scannedPackage. 9322 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 9323 } 9324 9325 for (PackageSetting ps : packagesForUser) { 9326 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9327 if (ps.primaryCpuAbiString != null) { 9328 continue; 9329 } 9330 9331 ps.primaryCpuAbiString = adjustedAbi; 9332 if (ps.pkg != null && ps.pkg.applicationInfo != null && 9333 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 9334 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 9335 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 9336 + " (requirer=" 9337 + (requirer == null ? "null" : requirer.pkg.packageName) 9338 + ", scannedPackage=" 9339 + (scannedPackage != null ? scannedPackage.packageName : "null") 9340 + ")"); 9341 try { 9342 mInstaller.rmdex(ps.codePathString, 9343 getDexCodeInstructionSet(getPreferredInstructionSet())); 9344 } catch (InstallerException ignored) { 9345 } 9346 } 9347 } 9348 } 9349 } 9350 } 9351 9352 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 9353 synchronized (mPackages) { 9354 mResolverReplaced = true; 9355 // Set up information for custom user intent resolution activity. 9356 mResolveActivity.applicationInfo = pkg.applicationInfo; 9357 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 9358 mResolveActivity.packageName = pkg.applicationInfo.packageName; 9359 mResolveActivity.processName = pkg.applicationInfo.packageName; 9360 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9361 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9362 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9363 mResolveActivity.theme = 0; 9364 mResolveActivity.exported = true; 9365 mResolveActivity.enabled = true; 9366 mResolveInfo.activityInfo = mResolveActivity; 9367 mResolveInfo.priority = 0; 9368 mResolveInfo.preferredOrder = 0; 9369 mResolveInfo.match = 0; 9370 mResolveComponentName = mCustomResolverComponentName; 9371 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 9372 mResolveComponentName); 9373 } 9374 } 9375 9376 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 9377 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 9378 9379 // Set up information for ephemeral installer activity 9380 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 9381 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 9382 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 9383 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 9384 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9385 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9386 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9387 mEphemeralInstallerActivity.theme = 0; 9388 mEphemeralInstallerActivity.exported = true; 9389 mEphemeralInstallerActivity.enabled = true; 9390 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 9391 mEphemeralInstallerInfo.priority = 0; 9392 mEphemeralInstallerInfo.preferredOrder = 0; 9393 mEphemeralInstallerInfo.match = 0; 9394 9395 if (DEBUG_EPHEMERAL) { 9396 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 9397 } 9398 } 9399 9400 private static String calculateBundledApkRoot(final String codePathString) { 9401 final File codePath = new File(codePathString); 9402 final File codeRoot; 9403 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 9404 codeRoot = Environment.getRootDirectory(); 9405 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 9406 codeRoot = Environment.getOemDirectory(); 9407 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 9408 codeRoot = Environment.getVendorDirectory(); 9409 } else { 9410 // Unrecognized code path; take its top real segment as the apk root: 9411 // e.g. /something/app/blah.apk => /something 9412 try { 9413 File f = codePath.getCanonicalFile(); 9414 File parent = f.getParentFile(); // non-null because codePath is a file 9415 File tmp; 9416 while ((tmp = parent.getParentFile()) != null) { 9417 f = parent; 9418 parent = tmp; 9419 } 9420 codeRoot = f; 9421 Slog.w(TAG, "Unrecognized code path " 9422 + codePath + " - using " + codeRoot); 9423 } catch (IOException e) { 9424 // Can't canonicalize the code path -- shenanigans? 9425 Slog.w(TAG, "Can't canonicalize code path " + codePath); 9426 return Environment.getRootDirectory().getPath(); 9427 } 9428 } 9429 return codeRoot.getPath(); 9430 } 9431 9432 /** 9433 * Derive and set the location of native libraries for the given package, 9434 * which varies depending on where and how the package was installed. 9435 */ 9436 private void setNativeLibraryPaths(PackageParser.Package pkg) { 9437 final ApplicationInfo info = pkg.applicationInfo; 9438 final String codePath = pkg.codePath; 9439 final File codeFile = new File(codePath); 9440 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 9441 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 9442 9443 info.nativeLibraryRootDir = null; 9444 info.nativeLibraryRootRequiresIsa = false; 9445 info.nativeLibraryDir = null; 9446 info.secondaryNativeLibraryDir = null; 9447 9448 if (isApkFile(codeFile)) { 9449 // Monolithic install 9450 if (bundledApp) { 9451 // If "/system/lib64/apkname" exists, assume that is the per-package 9452 // native library directory to use; otherwise use "/system/lib/apkname". 9453 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 9454 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 9455 getPrimaryInstructionSet(info)); 9456 9457 // This is a bundled system app so choose the path based on the ABI. 9458 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 9459 // is just the default path. 9460 final String apkName = deriveCodePathName(codePath); 9461 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 9462 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 9463 apkName).getAbsolutePath(); 9464 9465 if (info.secondaryCpuAbi != null) { 9466 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 9467 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 9468 secondaryLibDir, apkName).getAbsolutePath(); 9469 } 9470 } else if (asecApp) { 9471 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 9472 .getAbsolutePath(); 9473 } else { 9474 final String apkName = deriveCodePathName(codePath); 9475 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 9476 .getAbsolutePath(); 9477 } 9478 9479 info.nativeLibraryRootRequiresIsa = false; 9480 info.nativeLibraryDir = info.nativeLibraryRootDir; 9481 } else { 9482 // Cluster install 9483 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 9484 info.nativeLibraryRootRequiresIsa = true; 9485 9486 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 9487 getPrimaryInstructionSet(info)).getAbsolutePath(); 9488 9489 if (info.secondaryCpuAbi != null) { 9490 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 9491 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 9492 } 9493 } 9494 } 9495 9496 /** 9497 * Calculate the abis and roots for a bundled app. These can uniquely 9498 * be determined from the contents of the system partition, i.e whether 9499 * it contains 64 or 32 bit shared libraries etc. We do not validate any 9500 * of this information, and instead assume that the system was built 9501 * sensibly. 9502 */ 9503 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 9504 PackageSetting pkgSetting) { 9505 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 9506 9507 // If "/system/lib64/apkname" exists, assume that is the per-package 9508 // native library directory to use; otherwise use "/system/lib/apkname". 9509 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 9510 setBundledAppAbi(pkg, apkRoot, apkName); 9511 // pkgSetting might be null during rescan following uninstall of updates 9512 // to a bundled app, so accommodate that possibility. The settings in 9513 // that case will be established later from the parsed package. 9514 // 9515 // If the settings aren't null, sync them up with what we've just derived. 9516 // note that apkRoot isn't stored in the package settings. 9517 if (pkgSetting != null) { 9518 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9519 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9520 } 9521 } 9522 9523 /** 9524 * Deduces the ABI of a bundled app and sets the relevant fields on the 9525 * parsed pkg object. 9526 * 9527 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 9528 * under which system libraries are installed. 9529 * @param apkName the name of the installed package. 9530 */ 9531 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 9532 final File codeFile = new File(pkg.codePath); 9533 9534 final boolean has64BitLibs; 9535 final boolean has32BitLibs; 9536 if (isApkFile(codeFile)) { 9537 // Monolithic install 9538 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 9539 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 9540 } else { 9541 // Cluster install 9542 final File rootDir = new File(codeFile, LIB_DIR_NAME); 9543 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 9544 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 9545 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 9546 has64BitLibs = (new File(rootDir, isa)).exists(); 9547 } else { 9548 has64BitLibs = false; 9549 } 9550 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 9551 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 9552 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 9553 has32BitLibs = (new File(rootDir, isa)).exists(); 9554 } else { 9555 has32BitLibs = false; 9556 } 9557 } 9558 9559 if (has64BitLibs && !has32BitLibs) { 9560 // The package has 64 bit libs, but not 32 bit libs. Its primary 9561 // ABI should be 64 bit. We can safely assume here that the bundled 9562 // native libraries correspond to the most preferred ABI in the list. 9563 9564 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9565 pkg.applicationInfo.secondaryCpuAbi = null; 9566 } else if (has32BitLibs && !has64BitLibs) { 9567 // The package has 32 bit libs but not 64 bit libs. Its primary 9568 // ABI should be 32 bit. 9569 9570 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9571 pkg.applicationInfo.secondaryCpuAbi = null; 9572 } else if (has32BitLibs && has64BitLibs) { 9573 // The application has both 64 and 32 bit bundled libraries. We check 9574 // here that the app declares multiArch support, and warn if it doesn't. 9575 // 9576 // We will be lenient here and record both ABIs. The primary will be the 9577 // ABI that's higher on the list, i.e, a device that's configured to prefer 9578 // 64 bit apps will see a 64 bit primary ABI, 9579 9580 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 9581 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 9582 } 9583 9584 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 9585 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9586 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9587 } else { 9588 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9589 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9590 } 9591 } else { 9592 pkg.applicationInfo.primaryCpuAbi = null; 9593 pkg.applicationInfo.secondaryCpuAbi = null; 9594 } 9595 } 9596 9597 private void killApplication(String pkgName, int appId, String reason) { 9598 killApplication(pkgName, appId, UserHandle.USER_ALL, reason); 9599 } 9600 9601 private void killApplication(String pkgName, int appId, int userId, String reason) { 9602 // Request the ActivityManager to kill the process(only for existing packages) 9603 // so that we do not end up in a confused state while the user is still using the older 9604 // version of the application while the new one gets installed. 9605 final long token = Binder.clearCallingIdentity(); 9606 try { 9607 IActivityManager am = ActivityManagerNative.getDefault(); 9608 if (am != null) { 9609 try { 9610 am.killApplication(pkgName, appId, userId, reason); 9611 } catch (RemoteException e) { 9612 } 9613 } 9614 } finally { 9615 Binder.restoreCallingIdentity(token); 9616 } 9617 } 9618 9619 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 9620 // Remove the parent package setting 9621 PackageSetting ps = (PackageSetting) pkg.mExtras; 9622 if (ps != null) { 9623 removePackageLI(ps, chatty); 9624 } 9625 // Remove the child package setting 9626 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9627 for (int i = 0; i < childCount; i++) { 9628 PackageParser.Package childPkg = pkg.childPackages.get(i); 9629 ps = (PackageSetting) childPkg.mExtras; 9630 if (ps != null) { 9631 removePackageLI(ps, chatty); 9632 } 9633 } 9634 } 9635 9636 void removePackageLI(PackageSetting ps, boolean chatty) { 9637 if (DEBUG_INSTALL) { 9638 if (chatty) 9639 Log.d(TAG, "Removing package " + ps.name); 9640 } 9641 9642 // writer 9643 synchronized (mPackages) { 9644 mPackages.remove(ps.name); 9645 final PackageParser.Package pkg = ps.pkg; 9646 if (pkg != null) { 9647 cleanPackageDataStructuresLILPw(pkg, chatty); 9648 } 9649 } 9650 } 9651 9652 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 9653 if (DEBUG_INSTALL) { 9654 if (chatty) 9655 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 9656 } 9657 9658 // writer 9659 synchronized (mPackages) { 9660 // Remove the parent package 9661 mPackages.remove(pkg.applicationInfo.packageName); 9662 cleanPackageDataStructuresLILPw(pkg, chatty); 9663 9664 // Remove the child packages 9665 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9666 for (int i = 0; i < childCount; i++) { 9667 PackageParser.Package childPkg = pkg.childPackages.get(i); 9668 mPackages.remove(childPkg.applicationInfo.packageName); 9669 cleanPackageDataStructuresLILPw(childPkg, chatty); 9670 } 9671 } 9672 } 9673 9674 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 9675 int N = pkg.providers.size(); 9676 StringBuilder r = null; 9677 int i; 9678 for (i=0; i<N; i++) { 9679 PackageParser.Provider p = pkg.providers.get(i); 9680 mProviders.removeProvider(p); 9681 if (p.info.authority == null) { 9682 9683 /* There was another ContentProvider with this authority when 9684 * this app was installed so this authority is null, 9685 * Ignore it as we don't have to unregister the provider. 9686 */ 9687 continue; 9688 } 9689 String names[] = p.info.authority.split(";"); 9690 for (int j = 0; j < names.length; j++) { 9691 if (mProvidersByAuthority.get(names[j]) == p) { 9692 mProvidersByAuthority.remove(names[j]); 9693 if (DEBUG_REMOVE) { 9694 if (chatty) 9695 Log.d(TAG, "Unregistered content provider: " + names[j] 9696 + ", className = " + p.info.name + ", isSyncable = " 9697 + p.info.isSyncable); 9698 } 9699 } 9700 } 9701 if (DEBUG_REMOVE && chatty) { 9702 if (r == null) { 9703 r = new StringBuilder(256); 9704 } else { 9705 r.append(' '); 9706 } 9707 r.append(p.info.name); 9708 } 9709 } 9710 if (r != null) { 9711 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 9712 } 9713 9714 N = pkg.services.size(); 9715 r = null; 9716 for (i=0; i<N; i++) { 9717 PackageParser.Service s = pkg.services.get(i); 9718 mServices.removeService(s); 9719 if (chatty) { 9720 if (r == null) { 9721 r = new StringBuilder(256); 9722 } else { 9723 r.append(' '); 9724 } 9725 r.append(s.info.name); 9726 } 9727 } 9728 if (r != null) { 9729 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 9730 } 9731 9732 N = pkg.receivers.size(); 9733 r = null; 9734 for (i=0; i<N; i++) { 9735 PackageParser.Activity a = pkg.receivers.get(i); 9736 mReceivers.removeActivity(a, "receiver"); 9737 if (DEBUG_REMOVE && chatty) { 9738 if (r == null) { 9739 r = new StringBuilder(256); 9740 } else { 9741 r.append(' '); 9742 } 9743 r.append(a.info.name); 9744 } 9745 } 9746 if (r != null) { 9747 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 9748 } 9749 9750 N = pkg.activities.size(); 9751 r = null; 9752 for (i=0; i<N; i++) { 9753 PackageParser.Activity a = pkg.activities.get(i); 9754 mActivities.removeActivity(a, "activity"); 9755 if (DEBUG_REMOVE && chatty) { 9756 if (r == null) { 9757 r = new StringBuilder(256); 9758 } else { 9759 r.append(' '); 9760 } 9761 r.append(a.info.name); 9762 } 9763 } 9764 if (r != null) { 9765 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 9766 } 9767 9768 N = pkg.permissions.size(); 9769 r = null; 9770 for (i=0; i<N; i++) { 9771 PackageParser.Permission p = pkg.permissions.get(i); 9772 BasePermission bp = mSettings.mPermissions.get(p.info.name); 9773 if (bp == null) { 9774 bp = mSettings.mPermissionTrees.get(p.info.name); 9775 } 9776 if (bp != null && bp.perm == p) { 9777 bp.perm = null; 9778 if (DEBUG_REMOVE && chatty) { 9779 if (r == null) { 9780 r = new StringBuilder(256); 9781 } else { 9782 r.append(' '); 9783 } 9784 r.append(p.info.name); 9785 } 9786 } 9787 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9788 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 9789 if (appOpPkgs != null) { 9790 appOpPkgs.remove(pkg.packageName); 9791 } 9792 } 9793 } 9794 if (r != null) { 9795 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9796 } 9797 9798 N = pkg.requestedPermissions.size(); 9799 r = null; 9800 for (i=0; i<N; i++) { 9801 String perm = pkg.requestedPermissions.get(i); 9802 BasePermission bp = mSettings.mPermissions.get(perm); 9803 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9804 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 9805 if (appOpPkgs != null) { 9806 appOpPkgs.remove(pkg.packageName); 9807 if (appOpPkgs.isEmpty()) { 9808 mAppOpPermissionPackages.remove(perm); 9809 } 9810 } 9811 } 9812 } 9813 if (r != null) { 9814 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9815 } 9816 9817 N = pkg.instrumentation.size(); 9818 r = null; 9819 for (i=0; i<N; i++) { 9820 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9821 mInstrumentation.remove(a.getComponentName()); 9822 if (DEBUG_REMOVE && chatty) { 9823 if (r == null) { 9824 r = new StringBuilder(256); 9825 } else { 9826 r.append(' '); 9827 } 9828 r.append(a.info.name); 9829 } 9830 } 9831 if (r != null) { 9832 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9833 } 9834 9835 r = null; 9836 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9837 // Only system apps can hold shared libraries. 9838 if (pkg.libraryNames != null) { 9839 for (i=0; i<pkg.libraryNames.size(); i++) { 9840 String name = pkg.libraryNames.get(i); 9841 SharedLibraryEntry cur = mSharedLibraries.get(name); 9842 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9843 mSharedLibraries.remove(name); 9844 if (DEBUG_REMOVE && chatty) { 9845 if (r == null) { 9846 r = new StringBuilder(256); 9847 } else { 9848 r.append(' '); 9849 } 9850 r.append(name); 9851 } 9852 } 9853 } 9854 } 9855 } 9856 if (r != null) { 9857 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9858 } 9859 } 9860 9861 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9862 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9863 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9864 return true; 9865 } 9866 } 9867 return false; 9868 } 9869 9870 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9871 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9872 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9873 9874 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9875 // Update the parent permissions 9876 updatePermissionsLPw(pkg.packageName, pkg, flags); 9877 // Update the child permissions 9878 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9879 for (int i = 0; i < childCount; i++) { 9880 PackageParser.Package childPkg = pkg.childPackages.get(i); 9881 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9882 } 9883 } 9884 9885 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9886 int flags) { 9887 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9888 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9889 } 9890 9891 private void updatePermissionsLPw(String changingPkg, 9892 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9893 // Make sure there are no dangling permission trees. 9894 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9895 while (it.hasNext()) { 9896 final BasePermission bp = it.next(); 9897 if (bp.packageSetting == null) { 9898 // We may not yet have parsed the package, so just see if 9899 // we still know about its settings. 9900 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9901 } 9902 if (bp.packageSetting == null) { 9903 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9904 + " from package " + bp.sourcePackage); 9905 it.remove(); 9906 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9907 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9908 Slog.i(TAG, "Removing old permission tree: " + bp.name 9909 + " from package " + bp.sourcePackage); 9910 flags |= UPDATE_PERMISSIONS_ALL; 9911 it.remove(); 9912 } 9913 } 9914 } 9915 9916 // Make sure all dynamic permissions have been assigned to a package, 9917 // and make sure there are no dangling permissions. 9918 it = mSettings.mPermissions.values().iterator(); 9919 while (it.hasNext()) { 9920 final BasePermission bp = it.next(); 9921 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9922 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9923 + bp.name + " pkg=" + bp.sourcePackage 9924 + " info=" + bp.pendingInfo); 9925 if (bp.packageSetting == null && bp.pendingInfo != null) { 9926 final BasePermission tree = findPermissionTreeLP(bp.name); 9927 if (tree != null && tree.perm != null) { 9928 bp.packageSetting = tree.packageSetting; 9929 bp.perm = new PackageParser.Permission(tree.perm.owner, 9930 new PermissionInfo(bp.pendingInfo)); 9931 bp.perm.info.packageName = tree.perm.info.packageName; 9932 bp.perm.info.name = bp.name; 9933 bp.uid = tree.uid; 9934 } 9935 } 9936 } 9937 if (bp.packageSetting == null) { 9938 // We may not yet have parsed the package, so just see if 9939 // we still know about its settings. 9940 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9941 } 9942 if (bp.packageSetting == null) { 9943 Slog.w(TAG, "Removing dangling permission: " + bp.name 9944 + " from package " + bp.sourcePackage); 9945 it.remove(); 9946 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9947 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9948 Slog.i(TAG, "Removing old permission: " + bp.name 9949 + " from package " + bp.sourcePackage); 9950 flags |= UPDATE_PERMISSIONS_ALL; 9951 it.remove(); 9952 } 9953 } 9954 } 9955 9956 // Now update the permissions for all packages, in particular 9957 // replace the granted permissions of the system packages. 9958 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9959 for (PackageParser.Package pkg : mPackages.values()) { 9960 if (pkg != pkgInfo) { 9961 // Only replace for packages on requested volume 9962 final String volumeUuid = getVolumeUuidForPackage(pkg); 9963 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9964 && Objects.equals(replaceVolumeUuid, volumeUuid); 9965 grantPermissionsLPw(pkg, replace, changingPkg); 9966 } 9967 } 9968 } 9969 9970 if (pkgInfo != null) { 9971 // Only replace for packages on requested volume 9972 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9973 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9974 && Objects.equals(replaceVolumeUuid, volumeUuid); 9975 grantPermissionsLPw(pkgInfo, replace, changingPkg); 9976 } 9977 } 9978 9979 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 9980 String packageOfInterest) { 9981 // IMPORTANT: There are two types of permissions: install and runtime. 9982 // Install time permissions are granted when the app is installed to 9983 // all device users and users added in the future. Runtime permissions 9984 // are granted at runtime explicitly to specific users. Normal and signature 9985 // protected permissions are install time permissions. Dangerous permissions 9986 // are install permissions if the app's target SDK is Lollipop MR1 or older, 9987 // otherwise they are runtime permissions. This function does not manage 9988 // runtime permissions except for the case an app targeting Lollipop MR1 9989 // being upgraded to target a newer SDK, in which case dangerous permissions 9990 // are transformed from install time to runtime ones. 9991 9992 final PackageSetting ps = (PackageSetting) pkg.mExtras; 9993 if (ps == null) { 9994 return; 9995 } 9996 9997 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 9998 9999 PermissionsState permissionsState = ps.getPermissionsState(); 10000 PermissionsState origPermissions = permissionsState; 10001 10002 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 10003 10004 boolean runtimePermissionsRevoked = false; 10005 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 10006 10007 boolean changedInstallPermission = false; 10008 10009 if (replace) { 10010 ps.installPermissionsFixed = false; 10011 if (!ps.isSharedUser()) { 10012 origPermissions = new PermissionsState(permissionsState); 10013 permissionsState.reset(); 10014 } else { 10015 // We need to know only about runtime permission changes since the 10016 // calling code always writes the install permissions state but 10017 // the runtime ones are written only if changed. The only cases of 10018 // changed runtime permissions here are promotion of an install to 10019 // runtime and revocation of a runtime from a shared user. 10020 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 10021 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 10022 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 10023 runtimePermissionsRevoked = true; 10024 } 10025 } 10026 } 10027 10028 permissionsState.setGlobalGids(mGlobalGids); 10029 10030 final int N = pkg.requestedPermissions.size(); 10031 for (int i=0; i<N; i++) { 10032 final String name = pkg.requestedPermissions.get(i); 10033 final BasePermission bp = mSettings.mPermissions.get(name); 10034 10035 if (DEBUG_INSTALL) { 10036 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 10037 } 10038 10039 if (bp == null || bp.packageSetting == null) { 10040 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 10041 Slog.w(TAG, "Unknown permission " + name 10042 + " in package " + pkg.packageName); 10043 } 10044 continue; 10045 } 10046 10047 final String perm = bp.name; 10048 boolean allowedSig = false; 10049 int grant = GRANT_DENIED; 10050 10051 // Keep track of app op permissions. 10052 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 10053 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 10054 if (pkgs == null) { 10055 pkgs = new ArraySet<>(); 10056 mAppOpPermissionPackages.put(bp.name, pkgs); 10057 } 10058 pkgs.add(pkg.packageName); 10059 } 10060 10061 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 10062 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 10063 >= Build.VERSION_CODES.M; 10064 switch (level) { 10065 case PermissionInfo.PROTECTION_NORMAL: { 10066 // For all apps normal permissions are install time ones. 10067 grant = GRANT_INSTALL; 10068 } break; 10069 10070 case PermissionInfo.PROTECTION_DANGEROUS: { 10071 // If a permission review is required for legacy apps we represent 10072 // their permissions as always granted runtime ones since we need 10073 // to keep the review required permission flag per user while an 10074 // install permission's state is shared across all users. 10075 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 10076 // For legacy apps dangerous permissions are install time ones. 10077 grant = GRANT_INSTALL; 10078 } else if (origPermissions.hasInstallPermission(bp.name)) { 10079 // For legacy apps that became modern, install becomes runtime. 10080 grant = GRANT_UPGRADE; 10081 } else if (mPromoteSystemApps 10082 && isSystemApp(ps) 10083 && mExistingSystemPackages.contains(ps.name)) { 10084 // For legacy system apps, install becomes runtime. 10085 // We cannot check hasInstallPermission() for system apps since those 10086 // permissions were granted implicitly and not persisted pre-M. 10087 grant = GRANT_UPGRADE; 10088 } else { 10089 // For modern apps keep runtime permissions unchanged. 10090 grant = GRANT_RUNTIME; 10091 } 10092 } break; 10093 10094 case PermissionInfo.PROTECTION_SIGNATURE: { 10095 // For all apps signature permissions are install time ones. 10096 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 10097 if (allowedSig) { 10098 grant = GRANT_INSTALL; 10099 } 10100 } break; 10101 } 10102 10103 if (DEBUG_INSTALL) { 10104 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 10105 } 10106 10107 if (grant != GRANT_DENIED) { 10108 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 10109 // If this is an existing, non-system package, then 10110 // we can't add any new permissions to it. 10111 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 10112 // Except... if this is a permission that was added 10113 // to the platform (note: need to only do this when 10114 // updating the platform). 10115 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 10116 grant = GRANT_DENIED; 10117 } 10118 } 10119 } 10120 10121 switch (grant) { 10122 case GRANT_INSTALL: { 10123 // Revoke this as runtime permission to handle the case of 10124 // a runtime permission being downgraded to an install one. 10125 // Also in permission review mode we keep dangerous permissions 10126 // for legacy apps 10127 for (int userId : UserManagerService.getInstance().getUserIds()) { 10128 if (origPermissions.getRuntimePermissionState( 10129 bp.name, userId) != null) { 10130 // Revoke the runtime permission and clear the flags. 10131 origPermissions.revokeRuntimePermission(bp, userId); 10132 origPermissions.updatePermissionFlags(bp, userId, 10133 PackageManager.MASK_PERMISSION_FLAGS, 0); 10134 // If we revoked a permission permission, we have to write. 10135 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10136 changedRuntimePermissionUserIds, userId); 10137 } 10138 } 10139 // Grant an install permission. 10140 if (permissionsState.grantInstallPermission(bp) != 10141 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10142 changedInstallPermission = true; 10143 } 10144 } break; 10145 10146 case GRANT_RUNTIME: { 10147 // Grant previously granted runtime permissions. 10148 for (int userId : UserManagerService.getInstance().getUserIds()) { 10149 PermissionState permissionState = origPermissions 10150 .getRuntimePermissionState(bp.name, userId); 10151 int flags = permissionState != null 10152 ? permissionState.getFlags() : 0; 10153 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 10154 if (permissionsState.grantRuntimePermission(bp, userId) == 10155 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10156 // If we cannot put the permission as it was, we have to write. 10157 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10158 changedRuntimePermissionUserIds, userId); 10159 } 10160 // If the app supports runtime permissions no need for a review. 10161 if (Build.PERMISSIONS_REVIEW_REQUIRED 10162 && appSupportsRuntimePermissions 10163 && (flags & PackageManager 10164 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 10165 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 10166 // Since we changed the flags, we have to write. 10167 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10168 changedRuntimePermissionUserIds, userId); 10169 } 10170 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 10171 && !appSupportsRuntimePermissions) { 10172 // For legacy apps that need a permission review, every new 10173 // runtime permission is granted but it is pending a review. 10174 // We also need to review only platform defined runtime 10175 // permissions as these are the only ones the platform knows 10176 // how to disable the API to simulate revocation as legacy 10177 // apps don't expect to run with revoked permissions. 10178 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 10179 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 10180 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 10181 // We changed the flags, hence have to write. 10182 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10183 changedRuntimePermissionUserIds, userId); 10184 } 10185 } 10186 if (permissionsState.grantRuntimePermission(bp, userId) 10187 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10188 // We changed the permission, hence have to write. 10189 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10190 changedRuntimePermissionUserIds, userId); 10191 } 10192 } 10193 // Propagate the permission flags. 10194 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 10195 } 10196 } break; 10197 10198 case GRANT_UPGRADE: { 10199 // Grant runtime permissions for a previously held install permission. 10200 PermissionState permissionState = origPermissions 10201 .getInstallPermissionState(bp.name); 10202 final int flags = permissionState != null ? permissionState.getFlags() : 0; 10203 10204 if (origPermissions.revokeInstallPermission(bp) 10205 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10206 // We will be transferring the permission flags, so clear them. 10207 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 10208 PackageManager.MASK_PERMISSION_FLAGS, 0); 10209 changedInstallPermission = true; 10210 } 10211 10212 // If the permission is not to be promoted to runtime we ignore it and 10213 // also its other flags as they are not applicable to install permissions. 10214 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 10215 for (int userId : currentUserIds) { 10216 if (permissionsState.grantRuntimePermission(bp, userId) != 10217 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10218 // Transfer the permission flags. 10219 permissionsState.updatePermissionFlags(bp, userId, 10220 flags, flags); 10221 // If we granted the permission, we have to write. 10222 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10223 changedRuntimePermissionUserIds, userId); 10224 } 10225 } 10226 } 10227 } break; 10228 10229 default: { 10230 if (packageOfInterest == null 10231 || packageOfInterest.equals(pkg.packageName)) { 10232 Slog.w(TAG, "Not granting permission " + perm 10233 + " to package " + pkg.packageName 10234 + " because it was previously installed without"); 10235 } 10236 } break; 10237 } 10238 } else { 10239 if (permissionsState.revokeInstallPermission(bp) != 10240 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10241 // Also drop the permission flags. 10242 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 10243 PackageManager.MASK_PERMISSION_FLAGS, 0); 10244 changedInstallPermission = true; 10245 Slog.i(TAG, "Un-granting permission " + perm 10246 + " from package " + pkg.packageName 10247 + " (protectionLevel=" + bp.protectionLevel 10248 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10249 + ")"); 10250 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 10251 // Don't print warning for app op permissions, since it is fine for them 10252 // not to be granted, there is a UI for the user to decide. 10253 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 10254 Slog.w(TAG, "Not granting permission " + perm 10255 + " to package " + pkg.packageName 10256 + " (protectionLevel=" + bp.protectionLevel 10257 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10258 + ")"); 10259 } 10260 } 10261 } 10262 } 10263 10264 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 10265 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 10266 // This is the first that we have heard about this package, so the 10267 // permissions we have now selected are fixed until explicitly 10268 // changed. 10269 ps.installPermissionsFixed = true; 10270 } 10271 10272 // Persist the runtime permissions state for users with changes. If permissions 10273 // were revoked because no app in the shared user declares them we have to 10274 // write synchronously to avoid losing runtime permissions state. 10275 for (int userId : changedRuntimePermissionUserIds) { 10276 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 10277 } 10278 10279 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10280 } 10281 10282 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 10283 boolean allowed = false; 10284 final int NP = PackageParser.NEW_PERMISSIONS.length; 10285 for (int ip=0; ip<NP; ip++) { 10286 final PackageParser.NewPermissionInfo npi 10287 = PackageParser.NEW_PERMISSIONS[ip]; 10288 if (npi.name.equals(perm) 10289 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 10290 allowed = true; 10291 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 10292 + pkg.packageName); 10293 break; 10294 } 10295 } 10296 return allowed; 10297 } 10298 10299 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 10300 BasePermission bp, PermissionsState origPermissions) { 10301 boolean allowed; 10302 allowed = (compareSignatures( 10303 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 10304 == PackageManager.SIGNATURE_MATCH) 10305 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 10306 == PackageManager.SIGNATURE_MATCH); 10307 if (!allowed && (bp.protectionLevel 10308 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 10309 if (isSystemApp(pkg)) { 10310 // For updated system applications, a system permission 10311 // is granted only if it had been defined by the original application. 10312 if (pkg.isUpdatedSystemApp()) { 10313 final PackageSetting sysPs = mSettings 10314 .getDisabledSystemPkgLPr(pkg.packageName); 10315 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 10316 // If the original was granted this permission, we take 10317 // that grant decision as read and propagate it to the 10318 // update. 10319 if (sysPs.isPrivileged()) { 10320 allowed = true; 10321 } 10322 } else { 10323 // The system apk may have been updated with an older 10324 // version of the one on the data partition, but which 10325 // granted a new system permission that it didn't have 10326 // before. In this case we do want to allow the app to 10327 // now get the new permission if the ancestral apk is 10328 // privileged to get it. 10329 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 10330 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 10331 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 10332 allowed = true; 10333 break; 10334 } 10335 } 10336 } 10337 // Also if a privileged parent package on the system image or any of 10338 // its children requested a privileged permission, the updated child 10339 // packages can also get the permission. 10340 if (pkg.parentPackage != null) { 10341 final PackageSetting disabledSysParentPs = mSettings 10342 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 10343 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 10344 && disabledSysParentPs.isPrivileged()) { 10345 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 10346 allowed = true; 10347 } else if (disabledSysParentPs.pkg.childPackages != null) { 10348 final int count = disabledSysParentPs.pkg.childPackages.size(); 10349 for (int i = 0; i < count; i++) { 10350 PackageParser.Package disabledSysChildPkg = 10351 disabledSysParentPs.pkg.childPackages.get(i); 10352 if (isPackageRequestingPermission(disabledSysChildPkg, 10353 perm)) { 10354 allowed = true; 10355 break; 10356 } 10357 } 10358 } 10359 } 10360 } 10361 } 10362 } else { 10363 allowed = isPrivilegedApp(pkg); 10364 } 10365 } 10366 } 10367 if (!allowed) { 10368 if (!allowed && (bp.protectionLevel 10369 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 10370 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 10371 // If this was a previously normal/dangerous permission that got moved 10372 // to a system permission as part of the runtime permission redesign, then 10373 // we still want to blindly grant it to old apps. 10374 allowed = true; 10375 } 10376 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 10377 && pkg.packageName.equals(mRequiredInstallerPackage)) { 10378 // If this permission is to be granted to the system installer and 10379 // this app is an installer, then it gets the permission. 10380 allowed = true; 10381 } 10382 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 10383 && pkg.packageName.equals(mRequiredVerifierPackage)) { 10384 // If this permission is to be granted to the system verifier and 10385 // this app is a verifier, then it gets the permission. 10386 allowed = true; 10387 } 10388 if (!allowed && (bp.protectionLevel 10389 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 10390 && isSystemApp(pkg)) { 10391 // Any pre-installed system app is allowed to get this permission. 10392 allowed = true; 10393 } 10394 if (!allowed && (bp.protectionLevel 10395 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 10396 // For development permissions, a development permission 10397 // is granted only if it was already granted. 10398 allowed = origPermissions.hasInstallPermission(perm); 10399 } 10400 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 10401 && pkg.packageName.equals(mSetupWizardPackage)) { 10402 // If this permission is to be granted to the system setup wizard and 10403 // this app is a setup wizard, then it gets the permission. 10404 allowed = true; 10405 } 10406 } 10407 return allowed; 10408 } 10409 10410 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 10411 final int permCount = pkg.requestedPermissions.size(); 10412 for (int j = 0; j < permCount; j++) { 10413 String requestedPermission = pkg.requestedPermissions.get(j); 10414 if (permission.equals(requestedPermission)) { 10415 return true; 10416 } 10417 } 10418 return false; 10419 } 10420 10421 final class ActivityIntentResolver 10422 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 10423 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10424 boolean defaultOnly, int userId) { 10425 if (!sUserManager.exists(userId)) return null; 10426 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10427 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10428 } 10429 10430 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10431 int userId) { 10432 if (!sUserManager.exists(userId)) return null; 10433 mFlags = flags; 10434 return super.queryIntent(intent, resolvedType, 10435 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10436 } 10437 10438 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10439 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 10440 if (!sUserManager.exists(userId)) return null; 10441 if (packageActivities == null) { 10442 return null; 10443 } 10444 mFlags = flags; 10445 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10446 final int N = packageActivities.size(); 10447 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 10448 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 10449 10450 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 10451 for (int i = 0; i < N; ++i) { 10452 intentFilters = packageActivities.get(i).intents; 10453 if (intentFilters != null && intentFilters.size() > 0) { 10454 PackageParser.ActivityIntentInfo[] array = 10455 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 10456 intentFilters.toArray(array); 10457 listCut.add(array); 10458 } 10459 } 10460 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10461 } 10462 10463 /** 10464 * Finds a privileged activity that matches the specified activity names. 10465 */ 10466 private PackageParser.Activity findMatchingActivity( 10467 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 10468 for (PackageParser.Activity sysActivity : activityList) { 10469 if (sysActivity.info.name.equals(activityInfo.name)) { 10470 return sysActivity; 10471 } 10472 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 10473 return sysActivity; 10474 } 10475 if (sysActivity.info.targetActivity != null) { 10476 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 10477 return sysActivity; 10478 } 10479 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 10480 return sysActivity; 10481 } 10482 } 10483 } 10484 return null; 10485 } 10486 10487 public class IterGenerator<E> { 10488 public Iterator<E> generate(ActivityIntentInfo info) { 10489 return null; 10490 } 10491 } 10492 10493 public class ActionIterGenerator extends IterGenerator<String> { 10494 @Override 10495 public Iterator<String> generate(ActivityIntentInfo info) { 10496 return info.actionsIterator(); 10497 } 10498 } 10499 10500 public class CategoriesIterGenerator extends IterGenerator<String> { 10501 @Override 10502 public Iterator<String> generate(ActivityIntentInfo info) { 10503 return info.categoriesIterator(); 10504 } 10505 } 10506 10507 public class SchemesIterGenerator extends IterGenerator<String> { 10508 @Override 10509 public Iterator<String> generate(ActivityIntentInfo info) { 10510 return info.schemesIterator(); 10511 } 10512 } 10513 10514 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 10515 @Override 10516 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 10517 return info.authoritiesIterator(); 10518 } 10519 } 10520 10521 /** 10522 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 10523 * MODIFIED. Do not pass in a list that should not be changed. 10524 */ 10525 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 10526 IterGenerator<T> generator, Iterator<T> searchIterator) { 10527 // loop through the set of actions; every one must be found in the intent filter 10528 while (searchIterator.hasNext()) { 10529 // we must have at least one filter in the list to consider a match 10530 if (intentList.size() == 0) { 10531 break; 10532 } 10533 10534 final T searchAction = searchIterator.next(); 10535 10536 // loop through the set of intent filters 10537 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 10538 while (intentIter.hasNext()) { 10539 final ActivityIntentInfo intentInfo = intentIter.next(); 10540 boolean selectionFound = false; 10541 10542 // loop through the intent filter's selection criteria; at least one 10543 // of them must match the searched criteria 10544 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 10545 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 10546 final T intentSelection = intentSelectionIter.next(); 10547 if (intentSelection != null && intentSelection.equals(searchAction)) { 10548 selectionFound = true; 10549 break; 10550 } 10551 } 10552 10553 // the selection criteria wasn't found in this filter's set; this filter 10554 // is not a potential match 10555 if (!selectionFound) { 10556 intentIter.remove(); 10557 } 10558 } 10559 } 10560 } 10561 10562 private boolean isProtectedAction(ActivityIntentInfo filter) { 10563 final Iterator<String> actionsIter = filter.actionsIterator(); 10564 while (actionsIter != null && actionsIter.hasNext()) { 10565 final String filterAction = actionsIter.next(); 10566 if (PROTECTED_ACTIONS.contains(filterAction)) { 10567 return true; 10568 } 10569 } 10570 return false; 10571 } 10572 10573 /** 10574 * Adjusts the priority of the given intent filter according to policy. 10575 * <p> 10576 * <ul> 10577 * <li>The priority for non privileged applications is capped to '0'</li> 10578 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 10579 * <li>The priority for unbundled updates to privileged applications is capped to the 10580 * priority defined on the system partition</li> 10581 * </ul> 10582 * <p> 10583 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 10584 * allowed to obtain any priority on any action. 10585 */ 10586 private void adjustPriority( 10587 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 10588 // nothing to do; priority is fine as-is 10589 if (intent.getPriority() <= 0) { 10590 return; 10591 } 10592 10593 final ActivityInfo activityInfo = intent.activity.info; 10594 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 10595 10596 final boolean privilegedApp = 10597 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 10598 if (!privilegedApp) { 10599 // non-privileged applications can never define a priority >0 10600 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 10601 + " package: " + applicationInfo.packageName 10602 + " activity: " + intent.activity.className 10603 + " origPrio: " + intent.getPriority()); 10604 intent.setPriority(0); 10605 return; 10606 } 10607 10608 if (systemActivities == null) { 10609 // the system package is not disabled; we're parsing the system partition 10610 if (isProtectedAction(intent)) { 10611 if (mDeferProtectedFilters) { 10612 // We can't deal with these just yet. No component should ever obtain a 10613 // >0 priority for a protected actions, with ONE exception -- the setup 10614 // wizard. The setup wizard, however, cannot be known until we're able to 10615 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 10616 // until all intent filters have been processed. Chicken, meet egg. 10617 // Let the filter temporarily have a high priority and rectify the 10618 // priorities after all system packages have been scanned. 10619 mProtectedFilters.add(intent); 10620 if (DEBUG_FILTERS) { 10621 Slog.i(TAG, "Protected action; save for later;" 10622 + " package: " + applicationInfo.packageName 10623 + " activity: " + intent.activity.className 10624 + " origPrio: " + intent.getPriority()); 10625 } 10626 return; 10627 } else { 10628 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 10629 Slog.i(TAG, "No setup wizard;" 10630 + " All protected intents capped to priority 0"); 10631 } 10632 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 10633 if (DEBUG_FILTERS) { 10634 Slog.i(TAG, "Found setup wizard;" 10635 + " allow priority " + intent.getPriority() + ";" 10636 + " package: " + intent.activity.info.packageName 10637 + " activity: " + intent.activity.className 10638 + " priority: " + intent.getPriority()); 10639 } 10640 // setup wizard gets whatever it wants 10641 return; 10642 } 10643 Slog.w(TAG, "Protected action; cap priority to 0;" 10644 + " package: " + intent.activity.info.packageName 10645 + " activity: " + intent.activity.className 10646 + " origPrio: " + intent.getPriority()); 10647 intent.setPriority(0); 10648 return; 10649 } 10650 } 10651 // privileged apps on the system image get whatever priority they request 10652 return; 10653 } 10654 10655 // privileged app unbundled update ... try to find the same activity 10656 final PackageParser.Activity foundActivity = 10657 findMatchingActivity(systemActivities, activityInfo); 10658 if (foundActivity == null) { 10659 // this is a new activity; it cannot obtain >0 priority 10660 if (DEBUG_FILTERS) { 10661 Slog.i(TAG, "New activity; cap priority to 0;" 10662 + " package: " + applicationInfo.packageName 10663 + " activity: " + intent.activity.className 10664 + " origPrio: " + intent.getPriority()); 10665 } 10666 intent.setPriority(0); 10667 return; 10668 } 10669 10670 // found activity, now check for filter equivalence 10671 10672 // a shallow copy is enough; we modify the list, not its contents 10673 final List<ActivityIntentInfo> intentListCopy = 10674 new ArrayList<>(foundActivity.intents); 10675 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 10676 10677 // find matching action subsets 10678 final Iterator<String> actionsIterator = intent.actionsIterator(); 10679 if (actionsIterator != null) { 10680 getIntentListSubset( 10681 intentListCopy, new ActionIterGenerator(), actionsIterator); 10682 if (intentListCopy.size() == 0) { 10683 // no more intents to match; we're not equivalent 10684 if (DEBUG_FILTERS) { 10685 Slog.i(TAG, "Mismatched action; cap priority to 0;" 10686 + " package: " + applicationInfo.packageName 10687 + " activity: " + intent.activity.className 10688 + " origPrio: " + intent.getPriority()); 10689 } 10690 intent.setPriority(0); 10691 return; 10692 } 10693 } 10694 10695 // find matching category subsets 10696 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 10697 if (categoriesIterator != null) { 10698 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 10699 categoriesIterator); 10700 if (intentListCopy.size() == 0) { 10701 // no more intents to match; we're not equivalent 10702 if (DEBUG_FILTERS) { 10703 Slog.i(TAG, "Mismatched category; cap priority to 0;" 10704 + " package: " + applicationInfo.packageName 10705 + " activity: " + intent.activity.className 10706 + " origPrio: " + intent.getPriority()); 10707 } 10708 intent.setPriority(0); 10709 return; 10710 } 10711 } 10712 10713 // find matching schemes subsets 10714 final Iterator<String> schemesIterator = intent.schemesIterator(); 10715 if (schemesIterator != null) { 10716 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 10717 schemesIterator); 10718 if (intentListCopy.size() == 0) { 10719 // no more intents to match; we're not equivalent 10720 if (DEBUG_FILTERS) { 10721 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 10722 + " package: " + applicationInfo.packageName 10723 + " activity: " + intent.activity.className 10724 + " origPrio: " + intent.getPriority()); 10725 } 10726 intent.setPriority(0); 10727 return; 10728 } 10729 } 10730 10731 // find matching authorities subsets 10732 final Iterator<IntentFilter.AuthorityEntry> 10733 authoritiesIterator = intent.authoritiesIterator(); 10734 if (authoritiesIterator != null) { 10735 getIntentListSubset(intentListCopy, 10736 new AuthoritiesIterGenerator(), 10737 authoritiesIterator); 10738 if (intentListCopy.size() == 0) { 10739 // no more intents to match; we're not equivalent 10740 if (DEBUG_FILTERS) { 10741 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 10742 + " package: " + applicationInfo.packageName 10743 + " activity: " + intent.activity.className 10744 + " origPrio: " + intent.getPriority()); 10745 } 10746 intent.setPriority(0); 10747 return; 10748 } 10749 } 10750 10751 // we found matching filter(s); app gets the max priority of all intents 10752 int cappedPriority = 0; 10753 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 10754 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 10755 } 10756 if (intent.getPriority() > cappedPriority) { 10757 if (DEBUG_FILTERS) { 10758 Slog.i(TAG, "Found matching filter(s);" 10759 + " cap priority to " + cappedPriority + ";" 10760 + " package: " + applicationInfo.packageName 10761 + " activity: " + intent.activity.className 10762 + " origPrio: " + intent.getPriority()); 10763 } 10764 intent.setPriority(cappedPriority); 10765 return; 10766 } 10767 // all this for nothing; the requested priority was <= what was on the system 10768 } 10769 10770 public final void addActivity(PackageParser.Activity a, String type) { 10771 mActivities.put(a.getComponentName(), a); 10772 if (DEBUG_SHOW_INFO) 10773 Log.v( 10774 TAG, " " + type + " " + 10775 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 10776 if (DEBUG_SHOW_INFO) 10777 Log.v(TAG, " Class=" + a.info.name); 10778 final int NI = a.intents.size(); 10779 for (int j=0; j<NI; j++) { 10780 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10781 if ("activity".equals(type)) { 10782 final PackageSetting ps = 10783 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 10784 final List<PackageParser.Activity> systemActivities = 10785 ps != null && ps.pkg != null ? ps.pkg.activities : null; 10786 adjustPriority(systemActivities, intent); 10787 } 10788 if (DEBUG_SHOW_INFO) { 10789 Log.v(TAG, " IntentFilter:"); 10790 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10791 } 10792 if (!intent.debugCheck()) { 10793 Log.w(TAG, "==> For Activity " + a.info.name); 10794 } 10795 addFilter(intent); 10796 } 10797 } 10798 10799 public final void removeActivity(PackageParser.Activity a, String type) { 10800 mActivities.remove(a.getComponentName()); 10801 if (DEBUG_SHOW_INFO) { 10802 Log.v(TAG, " " + type + " " 10803 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 10804 : a.info.name) + ":"); 10805 Log.v(TAG, " Class=" + a.info.name); 10806 } 10807 final int NI = a.intents.size(); 10808 for (int j=0; j<NI; j++) { 10809 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10810 if (DEBUG_SHOW_INFO) { 10811 Log.v(TAG, " IntentFilter:"); 10812 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10813 } 10814 removeFilter(intent); 10815 } 10816 } 10817 10818 @Override 10819 protected boolean allowFilterResult( 10820 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 10821 ActivityInfo filterAi = filter.activity.info; 10822 for (int i=dest.size()-1; i>=0; i--) { 10823 ActivityInfo destAi = dest.get(i).activityInfo; 10824 if (destAi.name == filterAi.name 10825 && destAi.packageName == filterAi.packageName) { 10826 return false; 10827 } 10828 } 10829 return true; 10830 } 10831 10832 @Override 10833 protected ActivityIntentInfo[] newArray(int size) { 10834 return new ActivityIntentInfo[size]; 10835 } 10836 10837 @Override 10838 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 10839 if (!sUserManager.exists(userId)) return true; 10840 PackageParser.Package p = filter.activity.owner; 10841 if (p != null) { 10842 PackageSetting ps = (PackageSetting)p.mExtras; 10843 if (ps != null) { 10844 // System apps are never considered stopped for purposes of 10845 // filtering, because there may be no way for the user to 10846 // actually re-launch them. 10847 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 10848 && ps.getStopped(userId); 10849 } 10850 } 10851 return false; 10852 } 10853 10854 @Override 10855 protected boolean isPackageForFilter(String packageName, 10856 PackageParser.ActivityIntentInfo info) { 10857 return packageName.equals(info.activity.owner.packageName); 10858 } 10859 10860 @Override 10861 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 10862 int match, int userId) { 10863 if (!sUserManager.exists(userId)) return null; 10864 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 10865 return null; 10866 } 10867 final PackageParser.Activity activity = info.activity; 10868 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 10869 if (ps == null) { 10870 return null; 10871 } 10872 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 10873 ps.readUserState(userId), userId); 10874 if (ai == null) { 10875 return null; 10876 } 10877 final ResolveInfo res = new ResolveInfo(); 10878 res.activityInfo = ai; 10879 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10880 res.filter = info; 10881 } 10882 if (info != null) { 10883 res.handleAllWebDataURI = info.handleAllWebDataURI(); 10884 } 10885 res.priority = info.getPriority(); 10886 res.preferredOrder = activity.owner.mPreferredOrder; 10887 //System.out.println("Result: " + res.activityInfo.className + 10888 // " = " + res.priority); 10889 res.match = match; 10890 res.isDefault = info.hasDefault; 10891 res.labelRes = info.labelRes; 10892 res.nonLocalizedLabel = info.nonLocalizedLabel; 10893 if (userNeedsBadging(userId)) { 10894 res.noResourceId = true; 10895 } else { 10896 res.icon = info.icon; 10897 } 10898 res.iconResourceId = info.icon; 10899 res.system = res.activityInfo.applicationInfo.isSystemApp(); 10900 return res; 10901 } 10902 10903 @Override 10904 protected void sortResults(List<ResolveInfo> results) { 10905 Collections.sort(results, mResolvePrioritySorter); 10906 } 10907 10908 @Override 10909 protected void dumpFilter(PrintWriter out, String prefix, 10910 PackageParser.ActivityIntentInfo filter) { 10911 out.print(prefix); out.print( 10912 Integer.toHexString(System.identityHashCode(filter.activity))); 10913 out.print(' '); 10914 filter.activity.printComponentShortName(out); 10915 out.print(" filter "); 10916 out.println(Integer.toHexString(System.identityHashCode(filter))); 10917 } 10918 10919 @Override 10920 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 10921 return filter.activity; 10922 } 10923 10924 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10925 PackageParser.Activity activity = (PackageParser.Activity)label; 10926 out.print(prefix); out.print( 10927 Integer.toHexString(System.identityHashCode(activity))); 10928 out.print(' '); 10929 activity.printComponentShortName(out); 10930 if (count > 1) { 10931 out.print(" ("); out.print(count); out.print(" filters)"); 10932 } 10933 out.println(); 10934 } 10935 10936 // Keys are String (activity class name), values are Activity. 10937 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 10938 = new ArrayMap<ComponentName, PackageParser.Activity>(); 10939 private int mFlags; 10940 } 10941 10942 private final class ServiceIntentResolver 10943 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 10944 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10945 boolean defaultOnly, int userId) { 10946 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10947 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10948 } 10949 10950 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10951 int userId) { 10952 if (!sUserManager.exists(userId)) return null; 10953 mFlags = flags; 10954 return super.queryIntent(intent, resolvedType, 10955 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10956 } 10957 10958 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10959 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 10960 if (!sUserManager.exists(userId)) return null; 10961 if (packageServices == null) { 10962 return null; 10963 } 10964 mFlags = flags; 10965 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10966 final int N = packageServices.size(); 10967 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 10968 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 10969 10970 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 10971 for (int i = 0; i < N; ++i) { 10972 intentFilters = packageServices.get(i).intents; 10973 if (intentFilters != null && intentFilters.size() > 0) { 10974 PackageParser.ServiceIntentInfo[] array = 10975 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 10976 intentFilters.toArray(array); 10977 listCut.add(array); 10978 } 10979 } 10980 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10981 } 10982 10983 public final void addService(PackageParser.Service s) { 10984 mServices.put(s.getComponentName(), s); 10985 if (DEBUG_SHOW_INFO) { 10986 Log.v(TAG, " " 10987 + (s.info.nonLocalizedLabel != null 10988 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10989 Log.v(TAG, " Class=" + s.info.name); 10990 } 10991 final int NI = s.intents.size(); 10992 int j; 10993 for (j=0; j<NI; j++) { 10994 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10995 if (DEBUG_SHOW_INFO) { 10996 Log.v(TAG, " IntentFilter:"); 10997 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10998 } 10999 if (!intent.debugCheck()) { 11000 Log.w(TAG, "==> For Service " + s.info.name); 11001 } 11002 addFilter(intent); 11003 } 11004 } 11005 11006 public final void removeService(PackageParser.Service s) { 11007 mServices.remove(s.getComponentName()); 11008 if (DEBUG_SHOW_INFO) { 11009 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 11010 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 11011 Log.v(TAG, " Class=" + s.info.name); 11012 } 11013 final int NI = s.intents.size(); 11014 int j; 11015 for (j=0; j<NI; j++) { 11016 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 11017 if (DEBUG_SHOW_INFO) { 11018 Log.v(TAG, " IntentFilter:"); 11019 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11020 } 11021 removeFilter(intent); 11022 } 11023 } 11024 11025 @Override 11026 protected boolean allowFilterResult( 11027 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 11028 ServiceInfo filterSi = filter.service.info; 11029 for (int i=dest.size()-1; i>=0; i--) { 11030 ServiceInfo destAi = dest.get(i).serviceInfo; 11031 if (destAi.name == filterSi.name 11032 && destAi.packageName == filterSi.packageName) { 11033 return false; 11034 } 11035 } 11036 return true; 11037 } 11038 11039 @Override 11040 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 11041 return new PackageParser.ServiceIntentInfo[size]; 11042 } 11043 11044 @Override 11045 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 11046 if (!sUserManager.exists(userId)) return true; 11047 PackageParser.Package p = filter.service.owner; 11048 if (p != null) { 11049 PackageSetting ps = (PackageSetting)p.mExtras; 11050 if (ps != null) { 11051 // System apps are never considered stopped for purposes of 11052 // filtering, because there may be no way for the user to 11053 // actually re-launch them. 11054 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 11055 && ps.getStopped(userId); 11056 } 11057 } 11058 return false; 11059 } 11060 11061 @Override 11062 protected boolean isPackageForFilter(String packageName, 11063 PackageParser.ServiceIntentInfo info) { 11064 return packageName.equals(info.service.owner.packageName); 11065 } 11066 11067 @Override 11068 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 11069 int match, int userId) { 11070 if (!sUserManager.exists(userId)) return null; 11071 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 11072 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 11073 return null; 11074 } 11075 final PackageParser.Service service = info.service; 11076 PackageSetting ps = (PackageSetting) service.owner.mExtras; 11077 if (ps == null) { 11078 return null; 11079 } 11080 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 11081 ps.readUserState(userId), userId); 11082 if (si == null) { 11083 return null; 11084 } 11085 final ResolveInfo res = new ResolveInfo(); 11086 res.serviceInfo = si; 11087 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 11088 res.filter = filter; 11089 } 11090 res.priority = info.getPriority(); 11091 res.preferredOrder = service.owner.mPreferredOrder; 11092 res.match = match; 11093 res.isDefault = info.hasDefault; 11094 res.labelRes = info.labelRes; 11095 res.nonLocalizedLabel = info.nonLocalizedLabel; 11096 res.icon = info.icon; 11097 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 11098 return res; 11099 } 11100 11101 @Override 11102 protected void sortResults(List<ResolveInfo> results) { 11103 Collections.sort(results, mResolvePrioritySorter); 11104 } 11105 11106 @Override 11107 protected void dumpFilter(PrintWriter out, String prefix, 11108 PackageParser.ServiceIntentInfo filter) { 11109 out.print(prefix); out.print( 11110 Integer.toHexString(System.identityHashCode(filter.service))); 11111 out.print(' '); 11112 filter.service.printComponentShortName(out); 11113 out.print(" filter "); 11114 out.println(Integer.toHexString(System.identityHashCode(filter))); 11115 } 11116 11117 @Override 11118 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 11119 return filter.service; 11120 } 11121 11122 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11123 PackageParser.Service service = (PackageParser.Service)label; 11124 out.print(prefix); out.print( 11125 Integer.toHexString(System.identityHashCode(service))); 11126 out.print(' '); 11127 service.printComponentShortName(out); 11128 if (count > 1) { 11129 out.print(" ("); out.print(count); out.print(" filters)"); 11130 } 11131 out.println(); 11132 } 11133 11134// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 11135// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 11136// final List<ResolveInfo> retList = Lists.newArrayList(); 11137// while (i.hasNext()) { 11138// final ResolveInfo resolveInfo = (ResolveInfo) i; 11139// if (isEnabledLP(resolveInfo.serviceInfo)) { 11140// retList.add(resolveInfo); 11141// } 11142// } 11143// return retList; 11144// } 11145 11146 // Keys are String (activity class name), values are Activity. 11147 private final ArrayMap<ComponentName, PackageParser.Service> mServices 11148 = new ArrayMap<ComponentName, PackageParser.Service>(); 11149 private int mFlags; 11150 }; 11151 11152 private final class ProviderIntentResolver 11153 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 11154 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 11155 boolean defaultOnly, int userId) { 11156 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 11157 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 11158 } 11159 11160 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 11161 int userId) { 11162 if (!sUserManager.exists(userId)) 11163 return null; 11164 mFlags = flags; 11165 return super.queryIntent(intent, resolvedType, 11166 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 11167 } 11168 11169 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 11170 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 11171 if (!sUserManager.exists(userId)) 11172 return null; 11173 if (packageProviders == null) { 11174 return null; 11175 } 11176 mFlags = flags; 11177 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 11178 final int N = packageProviders.size(); 11179 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 11180 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 11181 11182 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 11183 for (int i = 0; i < N; ++i) { 11184 intentFilters = packageProviders.get(i).intents; 11185 if (intentFilters != null && intentFilters.size() > 0) { 11186 PackageParser.ProviderIntentInfo[] array = 11187 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 11188 intentFilters.toArray(array); 11189 listCut.add(array); 11190 } 11191 } 11192 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 11193 } 11194 11195 public final void addProvider(PackageParser.Provider p) { 11196 if (mProviders.containsKey(p.getComponentName())) { 11197 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 11198 return; 11199 } 11200 11201 mProviders.put(p.getComponentName(), p); 11202 if (DEBUG_SHOW_INFO) { 11203 Log.v(TAG, " " 11204 + (p.info.nonLocalizedLabel != null 11205 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11206 Log.v(TAG, " Class=" + p.info.name); 11207 } 11208 final int NI = p.intents.size(); 11209 int j; 11210 for (j = 0; j < NI; j++) { 11211 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11212 if (DEBUG_SHOW_INFO) { 11213 Log.v(TAG, " IntentFilter:"); 11214 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11215 } 11216 if (!intent.debugCheck()) { 11217 Log.w(TAG, "==> For Provider " + p.info.name); 11218 } 11219 addFilter(intent); 11220 } 11221 } 11222 11223 public final void removeProvider(PackageParser.Provider p) { 11224 mProviders.remove(p.getComponentName()); 11225 if (DEBUG_SHOW_INFO) { 11226 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 11227 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11228 Log.v(TAG, " Class=" + p.info.name); 11229 } 11230 final int NI = p.intents.size(); 11231 int j; 11232 for (j = 0; j < NI; j++) { 11233 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11234 if (DEBUG_SHOW_INFO) { 11235 Log.v(TAG, " IntentFilter:"); 11236 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11237 } 11238 removeFilter(intent); 11239 } 11240 } 11241 11242 @Override 11243 protected boolean allowFilterResult( 11244 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 11245 ProviderInfo filterPi = filter.provider.info; 11246 for (int i = dest.size() - 1; i >= 0; i--) { 11247 ProviderInfo destPi = dest.get(i).providerInfo; 11248 if (destPi.name == filterPi.name 11249 && destPi.packageName == filterPi.packageName) { 11250 return false; 11251 } 11252 } 11253 return true; 11254 } 11255 11256 @Override 11257 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 11258 return new PackageParser.ProviderIntentInfo[size]; 11259 } 11260 11261 @Override 11262 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 11263 if (!sUserManager.exists(userId)) 11264 return true; 11265 PackageParser.Package p = filter.provider.owner; 11266 if (p != null) { 11267 PackageSetting ps = (PackageSetting) p.mExtras; 11268 if (ps != null) { 11269 // System apps are never considered stopped for purposes of 11270 // filtering, because there may be no way for the user to 11271 // actually re-launch them. 11272 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 11273 && ps.getStopped(userId); 11274 } 11275 } 11276 return false; 11277 } 11278 11279 @Override 11280 protected boolean isPackageForFilter(String packageName, 11281 PackageParser.ProviderIntentInfo info) { 11282 return packageName.equals(info.provider.owner.packageName); 11283 } 11284 11285 @Override 11286 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 11287 int match, int userId) { 11288 if (!sUserManager.exists(userId)) 11289 return null; 11290 final PackageParser.ProviderIntentInfo info = filter; 11291 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 11292 return null; 11293 } 11294 final PackageParser.Provider provider = info.provider; 11295 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 11296 if (ps == null) { 11297 return null; 11298 } 11299 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 11300 ps.readUserState(userId), userId); 11301 if (pi == null) { 11302 return null; 11303 } 11304 final ResolveInfo res = new ResolveInfo(); 11305 res.providerInfo = pi; 11306 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 11307 res.filter = filter; 11308 } 11309 res.priority = info.getPriority(); 11310 res.preferredOrder = provider.owner.mPreferredOrder; 11311 res.match = match; 11312 res.isDefault = info.hasDefault; 11313 res.labelRes = info.labelRes; 11314 res.nonLocalizedLabel = info.nonLocalizedLabel; 11315 res.icon = info.icon; 11316 res.system = res.providerInfo.applicationInfo.isSystemApp(); 11317 return res; 11318 } 11319 11320 @Override 11321 protected void sortResults(List<ResolveInfo> results) { 11322 Collections.sort(results, mResolvePrioritySorter); 11323 } 11324 11325 @Override 11326 protected void dumpFilter(PrintWriter out, String prefix, 11327 PackageParser.ProviderIntentInfo filter) { 11328 out.print(prefix); 11329 out.print( 11330 Integer.toHexString(System.identityHashCode(filter.provider))); 11331 out.print(' '); 11332 filter.provider.printComponentShortName(out); 11333 out.print(" filter "); 11334 out.println(Integer.toHexString(System.identityHashCode(filter))); 11335 } 11336 11337 @Override 11338 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 11339 return filter.provider; 11340 } 11341 11342 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11343 PackageParser.Provider provider = (PackageParser.Provider)label; 11344 out.print(prefix); out.print( 11345 Integer.toHexString(System.identityHashCode(provider))); 11346 out.print(' '); 11347 provider.printComponentShortName(out); 11348 if (count > 1) { 11349 out.print(" ("); out.print(count); out.print(" filters)"); 11350 } 11351 out.println(); 11352 } 11353 11354 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 11355 = new ArrayMap<ComponentName, PackageParser.Provider>(); 11356 private int mFlags; 11357 } 11358 11359 private static final class EphemeralIntentResolver 11360 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 11361 @Override 11362 protected EphemeralResolveIntentInfo[] newArray(int size) { 11363 return new EphemeralResolveIntentInfo[size]; 11364 } 11365 11366 @Override 11367 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 11368 return true; 11369 } 11370 11371 @Override 11372 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 11373 int userId) { 11374 if (!sUserManager.exists(userId)) { 11375 return null; 11376 } 11377 return info.getEphemeralResolveInfo(); 11378 } 11379 } 11380 11381 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 11382 new Comparator<ResolveInfo>() { 11383 public int compare(ResolveInfo r1, ResolveInfo r2) { 11384 int v1 = r1.priority; 11385 int v2 = r2.priority; 11386 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 11387 if (v1 != v2) { 11388 return (v1 > v2) ? -1 : 1; 11389 } 11390 v1 = r1.preferredOrder; 11391 v2 = r2.preferredOrder; 11392 if (v1 != v2) { 11393 return (v1 > v2) ? -1 : 1; 11394 } 11395 if (r1.isDefault != r2.isDefault) { 11396 return r1.isDefault ? -1 : 1; 11397 } 11398 v1 = r1.match; 11399 v2 = r2.match; 11400 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 11401 if (v1 != v2) { 11402 return (v1 > v2) ? -1 : 1; 11403 } 11404 if (r1.system != r2.system) { 11405 return r1.system ? -1 : 1; 11406 } 11407 if (r1.activityInfo != null) { 11408 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 11409 } 11410 if (r1.serviceInfo != null) { 11411 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 11412 } 11413 if (r1.providerInfo != null) { 11414 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 11415 } 11416 return 0; 11417 } 11418 }; 11419 11420 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 11421 new Comparator<ProviderInfo>() { 11422 public int compare(ProviderInfo p1, ProviderInfo p2) { 11423 final int v1 = p1.initOrder; 11424 final int v2 = p2.initOrder; 11425 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 11426 } 11427 }; 11428 11429 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 11430 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 11431 final int[] userIds) { 11432 mHandler.post(new Runnable() { 11433 @Override 11434 public void run() { 11435 try { 11436 final IActivityManager am = ActivityManagerNative.getDefault(); 11437 if (am == null) return; 11438 final int[] resolvedUserIds; 11439 if (userIds == null) { 11440 resolvedUserIds = am.getRunningUserIds(); 11441 } else { 11442 resolvedUserIds = userIds; 11443 } 11444 for (int id : resolvedUserIds) { 11445 final Intent intent = new Intent(action, 11446 pkg != null ? Uri.fromParts("package", pkg, null) : null); 11447 if (extras != null) { 11448 intent.putExtras(extras); 11449 } 11450 if (targetPkg != null) { 11451 intent.setPackage(targetPkg); 11452 } 11453 // Modify the UID when posting to other users 11454 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 11455 if (uid > 0 && UserHandle.getUserId(uid) != id) { 11456 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 11457 intent.putExtra(Intent.EXTRA_UID, uid); 11458 } 11459 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 11460 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 11461 if (DEBUG_BROADCASTS) { 11462 RuntimeException here = new RuntimeException("here"); 11463 here.fillInStackTrace(); 11464 Slog.d(TAG, "Sending to user " + id + ": " 11465 + intent.toShortString(false, true, false, false) 11466 + " " + intent.getExtras(), here); 11467 } 11468 am.broadcastIntent(null, intent, null, finishedReceiver, 11469 0, null, null, null, android.app.AppOpsManager.OP_NONE, 11470 null, finishedReceiver != null, false, id); 11471 } 11472 } catch (RemoteException ex) { 11473 } 11474 } 11475 }); 11476 } 11477 11478 /** 11479 * Check if the external storage media is available. This is true if there 11480 * is a mounted external storage medium or if the external storage is 11481 * emulated. 11482 */ 11483 private boolean isExternalMediaAvailable() { 11484 return mMediaMounted || Environment.isExternalStorageEmulated(); 11485 } 11486 11487 @Override 11488 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 11489 // writer 11490 synchronized (mPackages) { 11491 if (!isExternalMediaAvailable()) { 11492 // If the external storage is no longer mounted at this point, 11493 // the caller may not have been able to delete all of this 11494 // packages files and can not delete any more. Bail. 11495 return null; 11496 } 11497 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 11498 if (lastPackage != null) { 11499 pkgs.remove(lastPackage); 11500 } 11501 if (pkgs.size() > 0) { 11502 return pkgs.get(0); 11503 } 11504 } 11505 return null; 11506 } 11507 11508 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 11509 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 11510 userId, andCode ? 1 : 0, packageName); 11511 if (mSystemReady) { 11512 msg.sendToTarget(); 11513 } else { 11514 if (mPostSystemReadyMessages == null) { 11515 mPostSystemReadyMessages = new ArrayList<>(); 11516 } 11517 mPostSystemReadyMessages.add(msg); 11518 } 11519 } 11520 11521 void startCleaningPackages() { 11522 // reader 11523 if (!isExternalMediaAvailable()) { 11524 return; 11525 } 11526 synchronized (mPackages) { 11527 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 11528 return; 11529 } 11530 } 11531 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 11532 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 11533 IActivityManager am = ActivityManagerNative.getDefault(); 11534 if (am != null) { 11535 try { 11536 am.startService(null, intent, null, mContext.getOpPackageName(), 11537 UserHandle.USER_SYSTEM); 11538 } catch (RemoteException e) { 11539 } 11540 } 11541 } 11542 11543 @Override 11544 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 11545 int installFlags, String installerPackageName, int userId) { 11546 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 11547 11548 final int callingUid = Binder.getCallingUid(); 11549 enforceCrossUserPermission(callingUid, userId, 11550 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 11551 11552 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11553 try { 11554 if (observer != null) { 11555 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 11556 } 11557 } catch (RemoteException re) { 11558 } 11559 return; 11560 } 11561 11562 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 11563 installFlags |= PackageManager.INSTALL_FROM_ADB; 11564 11565 } else { 11566 // Caller holds INSTALL_PACKAGES permission, so we're less strict 11567 // about installerPackageName. 11568 11569 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 11570 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 11571 } 11572 11573 UserHandle user; 11574 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 11575 user = UserHandle.ALL; 11576 } else { 11577 user = new UserHandle(userId); 11578 } 11579 11580 // Only system components can circumvent runtime permissions when installing. 11581 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 11582 && mContext.checkCallingOrSelfPermission(Manifest.permission 11583 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 11584 throw new SecurityException("You need the " 11585 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 11586 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 11587 } 11588 11589 final File originFile = new File(originPath); 11590 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 11591 11592 final Message msg = mHandler.obtainMessage(INIT_COPY); 11593 final VerificationInfo verificationInfo = new VerificationInfo( 11594 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 11595 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 11596 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 11597 null /*packageAbiOverride*/, null /*grantedPermissions*/, 11598 null /*certificates*/); 11599 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 11600 msg.obj = params; 11601 11602 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 11603 System.identityHashCode(msg.obj)); 11604 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11605 System.identityHashCode(msg.obj)); 11606 11607 mHandler.sendMessage(msg); 11608 } 11609 11610 void installStage(String packageName, File stagedDir, String stagedCid, 11611 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 11612 String installerPackageName, int installerUid, UserHandle user, 11613 Certificate[][] certificates) { 11614 if (DEBUG_EPHEMERAL) { 11615 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11616 Slog.d(TAG, "Ephemeral install of " + packageName); 11617 } 11618 } 11619 final VerificationInfo verificationInfo = new VerificationInfo( 11620 sessionParams.originatingUri, sessionParams.referrerUri, 11621 sessionParams.originatingUid, installerUid); 11622 11623 final OriginInfo origin; 11624 if (stagedDir != null) { 11625 origin = OriginInfo.fromStagedFile(stagedDir); 11626 } else { 11627 origin = OriginInfo.fromStagedContainer(stagedCid); 11628 } 11629 11630 final Message msg = mHandler.obtainMessage(INIT_COPY); 11631 final InstallParams params = new InstallParams(origin, null, observer, 11632 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 11633 verificationInfo, user, sessionParams.abiOverride, 11634 sessionParams.grantedRuntimePermissions, certificates); 11635 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 11636 msg.obj = params; 11637 11638 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 11639 System.identityHashCode(msg.obj)); 11640 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11641 System.identityHashCode(msg.obj)); 11642 11643 mHandler.sendMessage(msg); 11644 } 11645 11646 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 11647 int userId) { 11648 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 11649 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId); 11650 } 11651 11652 private void sendPackageAddedForUser(String packageName, boolean isSystem, 11653 int appId, int userId) { 11654 Bundle extras = new Bundle(1); 11655 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId)); 11656 11657 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 11658 packageName, extras, 0, null, null, new int[] {userId}); 11659 try { 11660 IActivityManager am = ActivityManagerNative.getDefault(); 11661 if (isSystem && am.isUserRunning(userId, 0)) { 11662 // The just-installed/enabled app is bundled on the system, so presumed 11663 // to be able to run automatically without needing an explicit launch. 11664 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 11665 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 11666 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 11667 .setPackage(packageName); 11668 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 11669 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 11670 } 11671 } catch (RemoteException e) { 11672 // shouldn't happen 11673 Slog.w(TAG, "Unable to bootstrap installed package", e); 11674 } 11675 } 11676 11677 @Override 11678 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 11679 int userId) { 11680 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11681 PackageSetting pkgSetting; 11682 final int uid = Binder.getCallingUid(); 11683 enforceCrossUserPermission(uid, userId, 11684 true /* requireFullPermission */, true /* checkShell */, 11685 "setApplicationHiddenSetting for user " + userId); 11686 11687 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 11688 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 11689 return false; 11690 } 11691 11692 long callingId = Binder.clearCallingIdentity(); 11693 try { 11694 boolean sendAdded = false; 11695 boolean sendRemoved = false; 11696 // writer 11697 synchronized (mPackages) { 11698 pkgSetting = mSettings.mPackages.get(packageName); 11699 if (pkgSetting == null) { 11700 return false; 11701 } 11702 // Only allow protected packages to hide themselves. 11703 if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId) 11704 && mProtectedPackages.isPackageStateProtected(userId, packageName)) { 11705 Slog.w(TAG, "Not hiding protected package: " + packageName); 11706 return false; 11707 } 11708 if (pkgSetting.getHidden(userId) != hidden) { 11709 pkgSetting.setHidden(hidden, userId); 11710 mSettings.writePackageRestrictionsLPr(userId); 11711 if (hidden) { 11712 sendRemoved = true; 11713 } else { 11714 sendAdded = true; 11715 } 11716 } 11717 } 11718 if (sendAdded) { 11719 sendPackageAddedForUser(packageName, pkgSetting, userId); 11720 return true; 11721 } 11722 if (sendRemoved) { 11723 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 11724 "hiding pkg"); 11725 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 11726 return true; 11727 } 11728 } finally { 11729 Binder.restoreCallingIdentity(callingId); 11730 } 11731 return false; 11732 } 11733 11734 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 11735 int userId) { 11736 final PackageRemovedInfo info = new PackageRemovedInfo(); 11737 info.removedPackage = packageName; 11738 info.removedUsers = new int[] {userId}; 11739 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 11740 info.sendPackageRemovedBroadcasts(true /*killApp*/); 11741 } 11742 11743 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 11744 if (pkgList.length > 0) { 11745 Bundle extras = new Bundle(1); 11746 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 11747 11748 sendPackageBroadcast( 11749 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 11750 : Intent.ACTION_PACKAGES_UNSUSPENDED, 11751 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 11752 new int[] {userId}); 11753 } 11754 } 11755 11756 /** 11757 * Returns true if application is not found or there was an error. Otherwise it returns 11758 * the hidden state of the package for the given user. 11759 */ 11760 @Override 11761 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 11762 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11763 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11764 true /* requireFullPermission */, false /* checkShell */, 11765 "getApplicationHidden for user " + userId); 11766 PackageSetting pkgSetting; 11767 long callingId = Binder.clearCallingIdentity(); 11768 try { 11769 // writer 11770 synchronized (mPackages) { 11771 pkgSetting = mSettings.mPackages.get(packageName); 11772 if (pkgSetting == null) { 11773 return true; 11774 } 11775 return pkgSetting.getHidden(userId); 11776 } 11777 } finally { 11778 Binder.restoreCallingIdentity(callingId); 11779 } 11780 } 11781 11782 /** 11783 * @hide 11784 */ 11785 @Override 11786 public int installExistingPackageAsUser(String packageName, int userId) { 11787 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 11788 null); 11789 PackageSetting pkgSetting; 11790 final int uid = Binder.getCallingUid(); 11791 enforceCrossUserPermission(uid, userId, 11792 true /* requireFullPermission */, true /* checkShell */, 11793 "installExistingPackage for user " + userId); 11794 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11795 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 11796 } 11797 11798 long callingId = Binder.clearCallingIdentity(); 11799 try { 11800 boolean installed = false; 11801 11802 // writer 11803 synchronized (mPackages) { 11804 pkgSetting = mSettings.mPackages.get(packageName); 11805 if (pkgSetting == null) { 11806 return PackageManager.INSTALL_FAILED_INVALID_URI; 11807 } 11808 if (!pkgSetting.getInstalled(userId)) { 11809 pkgSetting.setInstalled(true, userId); 11810 pkgSetting.setHidden(false, userId); 11811 mSettings.writePackageRestrictionsLPr(userId); 11812 installed = true; 11813 } 11814 } 11815 11816 if (installed) { 11817 if (pkgSetting.pkg != null) { 11818 synchronized (mInstallLock) { 11819 // We don't need to freeze for a brand new install 11820 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 11821 } 11822 } 11823 sendPackageAddedForUser(packageName, pkgSetting, userId); 11824 } 11825 } finally { 11826 Binder.restoreCallingIdentity(callingId); 11827 } 11828 11829 return PackageManager.INSTALL_SUCCEEDED; 11830 } 11831 11832 boolean isUserRestricted(int userId, String restrictionKey) { 11833 Bundle restrictions = sUserManager.getUserRestrictions(userId); 11834 if (restrictions.getBoolean(restrictionKey, false)) { 11835 Log.w(TAG, "User is restricted: " + restrictionKey); 11836 return true; 11837 } 11838 return false; 11839 } 11840 11841 @Override 11842 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 11843 int userId) { 11844 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11845 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11846 true /* requireFullPermission */, true /* checkShell */, 11847 "setPackagesSuspended for user " + userId); 11848 11849 if (ArrayUtils.isEmpty(packageNames)) { 11850 return packageNames; 11851 } 11852 11853 // List of package names for whom the suspended state has changed. 11854 List<String> changedPackages = new ArrayList<>(packageNames.length); 11855 // List of package names for whom the suspended state is not set as requested in this 11856 // method. 11857 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 11858 long callingId = Binder.clearCallingIdentity(); 11859 try { 11860 for (int i = 0; i < packageNames.length; i++) { 11861 String packageName = packageNames[i]; 11862 boolean changed = false; 11863 final int appId; 11864 synchronized (mPackages) { 11865 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11866 if (pkgSetting == null) { 11867 Slog.w(TAG, "Could not find package setting for package \"" + packageName 11868 + "\". Skipping suspending/un-suspending."); 11869 unactionedPackages.add(packageName); 11870 continue; 11871 } 11872 appId = pkgSetting.appId; 11873 if (pkgSetting.getSuspended(userId) != suspended) { 11874 if (!canSuspendPackageForUserLocked(packageName, userId)) { 11875 unactionedPackages.add(packageName); 11876 continue; 11877 } 11878 pkgSetting.setSuspended(suspended, userId); 11879 mSettings.writePackageRestrictionsLPr(userId); 11880 changed = true; 11881 changedPackages.add(packageName); 11882 } 11883 } 11884 11885 if (changed && suspended) { 11886 killApplication(packageName, UserHandle.getUid(userId, appId), 11887 "suspending package"); 11888 } 11889 } 11890 } finally { 11891 Binder.restoreCallingIdentity(callingId); 11892 } 11893 11894 if (!changedPackages.isEmpty()) { 11895 sendPackagesSuspendedForUser(changedPackages.toArray( 11896 new String[changedPackages.size()]), userId, suspended); 11897 } 11898 11899 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 11900 } 11901 11902 @Override 11903 public boolean isPackageSuspendedForUser(String packageName, int userId) { 11904 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11905 true /* requireFullPermission */, false /* checkShell */, 11906 "isPackageSuspendedForUser for user " + userId); 11907 synchronized (mPackages) { 11908 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11909 if (pkgSetting == null) { 11910 throw new IllegalArgumentException("Unknown target package: " + packageName); 11911 } 11912 return pkgSetting.getSuspended(userId); 11913 } 11914 } 11915 11916 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 11917 if (isPackageDeviceAdmin(packageName, userId)) { 11918 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11919 + "\": has an active device admin"); 11920 return false; 11921 } 11922 11923 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 11924 if (packageName.equals(activeLauncherPackageName)) { 11925 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11926 + "\": contains the active launcher"); 11927 return false; 11928 } 11929 11930 if (packageName.equals(mRequiredInstallerPackage)) { 11931 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11932 + "\": required for package installation"); 11933 return false; 11934 } 11935 11936 if (packageName.equals(mRequiredVerifierPackage)) { 11937 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11938 + "\": required for package verification"); 11939 return false; 11940 } 11941 11942 if (packageName.equals(getDefaultDialerPackageName(userId))) { 11943 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11944 + "\": is the default dialer"); 11945 return false; 11946 } 11947 11948 return true; 11949 } 11950 11951 private String getActiveLauncherPackageName(int userId) { 11952 Intent intent = new Intent(Intent.ACTION_MAIN); 11953 intent.addCategory(Intent.CATEGORY_HOME); 11954 ResolveInfo resolveInfo = resolveIntent( 11955 intent, 11956 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 11957 PackageManager.MATCH_DEFAULT_ONLY, 11958 userId); 11959 11960 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 11961 } 11962 11963 private String getDefaultDialerPackageName(int userId) { 11964 synchronized (mPackages) { 11965 return mSettings.getDefaultDialerPackageNameLPw(userId); 11966 } 11967 } 11968 11969 @Override 11970 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 11971 mContext.enforceCallingOrSelfPermission( 11972 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11973 "Only package verification agents can verify applications"); 11974 11975 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11976 final PackageVerificationResponse response = new PackageVerificationResponse( 11977 verificationCode, Binder.getCallingUid()); 11978 msg.arg1 = id; 11979 msg.obj = response; 11980 mHandler.sendMessage(msg); 11981 } 11982 11983 @Override 11984 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 11985 long millisecondsToDelay) { 11986 mContext.enforceCallingOrSelfPermission( 11987 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11988 "Only package verification agents can extend verification timeouts"); 11989 11990 final PackageVerificationState state = mPendingVerification.get(id); 11991 final PackageVerificationResponse response = new PackageVerificationResponse( 11992 verificationCodeAtTimeout, Binder.getCallingUid()); 11993 11994 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 11995 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 11996 } 11997 if (millisecondsToDelay < 0) { 11998 millisecondsToDelay = 0; 11999 } 12000 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 12001 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 12002 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 12003 } 12004 12005 if ((state != null) && !state.timeoutExtended()) { 12006 state.extendTimeout(); 12007 12008 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 12009 msg.arg1 = id; 12010 msg.obj = response; 12011 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 12012 } 12013 } 12014 12015 private void broadcastPackageVerified(int verificationId, Uri packageUri, 12016 int verificationCode, UserHandle user) { 12017 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 12018 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 12019 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 12020 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 12021 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 12022 12023 mContext.sendBroadcastAsUser(intent, user, 12024 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 12025 } 12026 12027 private ComponentName matchComponentForVerifier(String packageName, 12028 List<ResolveInfo> receivers) { 12029 ActivityInfo targetReceiver = null; 12030 12031 final int NR = receivers.size(); 12032 for (int i = 0; i < NR; i++) { 12033 final ResolveInfo info = receivers.get(i); 12034 if (info.activityInfo == null) { 12035 continue; 12036 } 12037 12038 if (packageName.equals(info.activityInfo.packageName)) { 12039 targetReceiver = info.activityInfo; 12040 break; 12041 } 12042 } 12043 12044 if (targetReceiver == null) { 12045 return null; 12046 } 12047 12048 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 12049 } 12050 12051 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 12052 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 12053 if (pkgInfo.verifiers.length == 0) { 12054 return null; 12055 } 12056 12057 final int N = pkgInfo.verifiers.length; 12058 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 12059 for (int i = 0; i < N; i++) { 12060 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 12061 12062 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 12063 receivers); 12064 if (comp == null) { 12065 continue; 12066 } 12067 12068 final int verifierUid = getUidForVerifier(verifierInfo); 12069 if (verifierUid == -1) { 12070 continue; 12071 } 12072 12073 if (DEBUG_VERIFY) { 12074 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 12075 + " with the correct signature"); 12076 } 12077 sufficientVerifiers.add(comp); 12078 verificationState.addSufficientVerifier(verifierUid); 12079 } 12080 12081 return sufficientVerifiers; 12082 } 12083 12084 private int getUidForVerifier(VerifierInfo verifierInfo) { 12085 synchronized (mPackages) { 12086 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 12087 if (pkg == null) { 12088 return -1; 12089 } else if (pkg.mSignatures.length != 1) { 12090 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 12091 + " has more than one signature; ignoring"); 12092 return -1; 12093 } 12094 12095 /* 12096 * If the public key of the package's signature does not match 12097 * our expected public key, then this is a different package and 12098 * we should skip. 12099 */ 12100 12101 final byte[] expectedPublicKey; 12102 try { 12103 final Signature verifierSig = pkg.mSignatures[0]; 12104 final PublicKey publicKey = verifierSig.getPublicKey(); 12105 expectedPublicKey = publicKey.getEncoded(); 12106 } catch (CertificateException e) { 12107 return -1; 12108 } 12109 12110 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 12111 12112 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 12113 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 12114 + " does not have the expected public key; ignoring"); 12115 return -1; 12116 } 12117 12118 return pkg.applicationInfo.uid; 12119 } 12120 } 12121 12122 @Override 12123 public void finishPackageInstall(int token, boolean didLaunch) { 12124 enforceSystemOrRoot("Only the system is allowed to finish installs"); 12125 12126 if (DEBUG_INSTALL) { 12127 Slog.v(TAG, "BM finishing package install for " + token); 12128 } 12129 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12130 12131 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 12132 mHandler.sendMessage(msg); 12133 } 12134 12135 /** 12136 * Get the verification agent timeout. 12137 * 12138 * @return verification timeout in milliseconds 12139 */ 12140 private long getVerificationTimeout() { 12141 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 12142 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 12143 DEFAULT_VERIFICATION_TIMEOUT); 12144 } 12145 12146 /** 12147 * Get the default verification agent response code. 12148 * 12149 * @return default verification response code 12150 */ 12151 private int getDefaultVerificationResponse() { 12152 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12153 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 12154 DEFAULT_VERIFICATION_RESPONSE); 12155 } 12156 12157 /** 12158 * Check whether or not package verification has been enabled. 12159 * 12160 * @return true if verification should be performed 12161 */ 12162 private boolean isVerificationEnabled(int userId, int installFlags) { 12163 if (!DEFAULT_VERIFY_ENABLE) { 12164 return false; 12165 } 12166 // Ephemeral apps don't get the full verification treatment 12167 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 12168 if (DEBUG_EPHEMERAL) { 12169 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 12170 } 12171 return false; 12172 } 12173 12174 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 12175 12176 // Check if installing from ADB 12177 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 12178 // Do not run verification in a test harness environment 12179 if (ActivityManager.isRunningInTestHarness()) { 12180 return false; 12181 } 12182 if (ensureVerifyAppsEnabled) { 12183 return true; 12184 } 12185 // Check if the developer does not want package verification for ADB installs 12186 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12187 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 12188 return false; 12189 } 12190 } 12191 12192 if (ensureVerifyAppsEnabled) { 12193 return true; 12194 } 12195 12196 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12197 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 12198 } 12199 12200 @Override 12201 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 12202 throws RemoteException { 12203 mContext.enforceCallingOrSelfPermission( 12204 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 12205 "Only intentfilter verification agents can verify applications"); 12206 12207 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 12208 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 12209 Binder.getCallingUid(), verificationCode, failedDomains); 12210 msg.arg1 = id; 12211 msg.obj = response; 12212 mHandler.sendMessage(msg); 12213 } 12214 12215 @Override 12216 public int getIntentVerificationStatus(String packageName, int userId) { 12217 synchronized (mPackages) { 12218 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 12219 } 12220 } 12221 12222 @Override 12223 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 12224 mContext.enforceCallingOrSelfPermission( 12225 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12226 12227 boolean result = false; 12228 synchronized (mPackages) { 12229 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 12230 } 12231 if (result) { 12232 scheduleWritePackageRestrictionsLocked(userId); 12233 } 12234 return result; 12235 } 12236 12237 @Override 12238 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 12239 String packageName) { 12240 synchronized (mPackages) { 12241 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 12242 } 12243 } 12244 12245 @Override 12246 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 12247 if (TextUtils.isEmpty(packageName)) { 12248 return ParceledListSlice.emptyList(); 12249 } 12250 synchronized (mPackages) { 12251 PackageParser.Package pkg = mPackages.get(packageName); 12252 if (pkg == null || pkg.activities == null) { 12253 return ParceledListSlice.emptyList(); 12254 } 12255 final int count = pkg.activities.size(); 12256 ArrayList<IntentFilter> result = new ArrayList<>(); 12257 for (int n=0; n<count; n++) { 12258 PackageParser.Activity activity = pkg.activities.get(n); 12259 if (activity.intents != null && activity.intents.size() > 0) { 12260 result.addAll(activity.intents); 12261 } 12262 } 12263 return new ParceledListSlice<>(result); 12264 } 12265 } 12266 12267 @Override 12268 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 12269 mContext.enforceCallingOrSelfPermission( 12270 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12271 12272 synchronized (mPackages) { 12273 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 12274 if (packageName != null) { 12275 result |= updateIntentVerificationStatus(packageName, 12276 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 12277 userId); 12278 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 12279 packageName, userId); 12280 } 12281 return result; 12282 } 12283 } 12284 12285 @Override 12286 public String getDefaultBrowserPackageName(int userId) { 12287 synchronized (mPackages) { 12288 return mSettings.getDefaultBrowserPackageNameLPw(userId); 12289 } 12290 } 12291 12292 /** 12293 * Get the "allow unknown sources" setting. 12294 * 12295 * @return the current "allow unknown sources" setting 12296 */ 12297 private int getUnknownSourcesSettings() { 12298 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 12299 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 12300 -1); 12301 } 12302 12303 @Override 12304 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 12305 final int uid = Binder.getCallingUid(); 12306 // writer 12307 synchronized (mPackages) { 12308 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 12309 if (targetPackageSetting == null) { 12310 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 12311 } 12312 12313 PackageSetting installerPackageSetting; 12314 if (installerPackageName != null) { 12315 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 12316 if (installerPackageSetting == null) { 12317 throw new IllegalArgumentException("Unknown installer package: " 12318 + installerPackageName); 12319 } 12320 } else { 12321 installerPackageSetting = null; 12322 } 12323 12324 Signature[] callerSignature; 12325 Object obj = mSettings.getUserIdLPr(uid); 12326 if (obj != null) { 12327 if (obj instanceof SharedUserSetting) { 12328 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 12329 } else if (obj instanceof PackageSetting) { 12330 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 12331 } else { 12332 throw new SecurityException("Bad object " + obj + " for uid " + uid); 12333 } 12334 } else { 12335 throw new SecurityException("Unknown calling UID: " + uid); 12336 } 12337 12338 // Verify: can't set installerPackageName to a package that is 12339 // not signed with the same cert as the caller. 12340 if (installerPackageSetting != null) { 12341 if (compareSignatures(callerSignature, 12342 installerPackageSetting.signatures.mSignatures) 12343 != PackageManager.SIGNATURE_MATCH) { 12344 throw new SecurityException( 12345 "Caller does not have same cert as new installer package " 12346 + installerPackageName); 12347 } 12348 } 12349 12350 // Verify: if target already has an installer package, it must 12351 // be signed with the same cert as the caller. 12352 if (targetPackageSetting.installerPackageName != null) { 12353 PackageSetting setting = mSettings.mPackages.get( 12354 targetPackageSetting.installerPackageName); 12355 // If the currently set package isn't valid, then it's always 12356 // okay to change it. 12357 if (setting != null) { 12358 if (compareSignatures(callerSignature, 12359 setting.signatures.mSignatures) 12360 != PackageManager.SIGNATURE_MATCH) { 12361 throw new SecurityException( 12362 "Caller does not have same cert as old installer package " 12363 + targetPackageSetting.installerPackageName); 12364 } 12365 } 12366 } 12367 12368 // Okay! 12369 targetPackageSetting.installerPackageName = installerPackageName; 12370 if (installerPackageName != null) { 12371 mSettings.mInstallerPackages.add(installerPackageName); 12372 } 12373 scheduleWriteSettingsLocked(); 12374 } 12375 } 12376 12377 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 12378 // Queue up an async operation since the package installation may take a little while. 12379 mHandler.post(new Runnable() { 12380 public void run() { 12381 mHandler.removeCallbacks(this); 12382 // Result object to be returned 12383 PackageInstalledInfo res = new PackageInstalledInfo(); 12384 res.setReturnCode(currentStatus); 12385 res.uid = -1; 12386 res.pkg = null; 12387 res.removedInfo = null; 12388 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12389 args.doPreInstall(res.returnCode); 12390 synchronized (mInstallLock) { 12391 installPackageTracedLI(args, res); 12392 } 12393 args.doPostInstall(res.returnCode, res.uid); 12394 } 12395 12396 // A restore should be performed at this point if (a) the install 12397 // succeeded, (b) the operation is not an update, and (c) the new 12398 // package has not opted out of backup participation. 12399 final boolean update = res.removedInfo != null 12400 && res.removedInfo.removedPackage != null; 12401 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 12402 boolean doRestore = !update 12403 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 12404 12405 // Set up the post-install work request bookkeeping. This will be used 12406 // and cleaned up by the post-install event handling regardless of whether 12407 // there's a restore pass performed. Token values are >= 1. 12408 int token; 12409 if (mNextInstallToken < 0) mNextInstallToken = 1; 12410 token = mNextInstallToken++; 12411 12412 PostInstallData data = new PostInstallData(args, res); 12413 mRunningInstalls.put(token, data); 12414 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 12415 12416 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 12417 // Pass responsibility to the Backup Manager. It will perform a 12418 // restore if appropriate, then pass responsibility back to the 12419 // Package Manager to run the post-install observer callbacks 12420 // and broadcasts. 12421 IBackupManager bm = IBackupManager.Stub.asInterface( 12422 ServiceManager.getService(Context.BACKUP_SERVICE)); 12423 if (bm != null) { 12424 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 12425 + " to BM for possible restore"); 12426 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12427 try { 12428 // TODO: http://b/22388012 12429 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 12430 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 12431 } else { 12432 doRestore = false; 12433 } 12434 } catch (RemoteException e) { 12435 // can't happen; the backup manager is local 12436 } catch (Exception e) { 12437 Slog.e(TAG, "Exception trying to enqueue restore", e); 12438 doRestore = false; 12439 } 12440 } else { 12441 Slog.e(TAG, "Backup Manager not found!"); 12442 doRestore = false; 12443 } 12444 } 12445 12446 if (!doRestore) { 12447 // No restore possible, or the Backup Manager was mysteriously not 12448 // available -- just fire the post-install work request directly. 12449 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 12450 12451 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 12452 12453 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 12454 mHandler.sendMessage(msg); 12455 } 12456 } 12457 }); 12458 } 12459 12460 /** 12461 * Callback from PackageSettings whenever an app is first transitioned out of the 12462 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 12463 * the app was "launched" for a restoreAtInstall operation. Therefore we check 12464 * here whether the app is the target of an ongoing install, and only send the 12465 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 12466 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 12467 * handling. 12468 */ 12469 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 12470 // Serialize this with the rest of the install-process message chain. In the 12471 // restore-at-install case, this Runnable will necessarily run before the 12472 // POST_INSTALL message is processed, so the contents of mRunningInstalls 12473 // are coherent. In the non-restore case, the app has already completed install 12474 // and been launched through some other means, so it is not in a problematic 12475 // state for observers to see the FIRST_LAUNCH signal. 12476 mHandler.post(new Runnable() { 12477 @Override 12478 public void run() { 12479 for (int i = 0; i < mRunningInstalls.size(); i++) { 12480 final PostInstallData data = mRunningInstalls.valueAt(i); 12481 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 12482 // right package; but is it for the right user? 12483 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 12484 if (userId == data.res.newUsers[uIndex]) { 12485 if (DEBUG_BACKUP) { 12486 Slog.i(TAG, "Package " + pkgName 12487 + " being restored so deferring FIRST_LAUNCH"); 12488 } 12489 return; 12490 } 12491 } 12492 } 12493 } 12494 // didn't find it, so not being restored 12495 if (DEBUG_BACKUP) { 12496 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 12497 } 12498 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 12499 } 12500 }); 12501 } 12502 12503 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 12504 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 12505 installerPkg, null, userIds); 12506 } 12507 12508 private abstract class HandlerParams { 12509 private static final int MAX_RETRIES = 4; 12510 12511 /** 12512 * Number of times startCopy() has been attempted and had a non-fatal 12513 * error. 12514 */ 12515 private int mRetries = 0; 12516 12517 /** User handle for the user requesting the information or installation. */ 12518 private final UserHandle mUser; 12519 String traceMethod; 12520 int traceCookie; 12521 12522 HandlerParams(UserHandle user) { 12523 mUser = user; 12524 } 12525 12526 UserHandle getUser() { 12527 return mUser; 12528 } 12529 12530 HandlerParams setTraceMethod(String traceMethod) { 12531 this.traceMethod = traceMethod; 12532 return this; 12533 } 12534 12535 HandlerParams setTraceCookie(int traceCookie) { 12536 this.traceCookie = traceCookie; 12537 return this; 12538 } 12539 12540 final boolean startCopy() { 12541 boolean res; 12542 try { 12543 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 12544 12545 if (++mRetries > MAX_RETRIES) { 12546 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 12547 mHandler.sendEmptyMessage(MCS_GIVE_UP); 12548 handleServiceError(); 12549 return false; 12550 } else { 12551 handleStartCopy(); 12552 res = true; 12553 } 12554 } catch (RemoteException e) { 12555 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 12556 mHandler.sendEmptyMessage(MCS_RECONNECT); 12557 res = false; 12558 } 12559 handleReturnCode(); 12560 return res; 12561 } 12562 12563 final void serviceError() { 12564 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 12565 handleServiceError(); 12566 handleReturnCode(); 12567 } 12568 12569 abstract void handleStartCopy() throws RemoteException; 12570 abstract void handleServiceError(); 12571 abstract void handleReturnCode(); 12572 } 12573 12574 class MeasureParams extends HandlerParams { 12575 private final PackageStats mStats; 12576 private boolean mSuccess; 12577 12578 private final IPackageStatsObserver mObserver; 12579 12580 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 12581 super(new UserHandle(stats.userHandle)); 12582 mObserver = observer; 12583 mStats = stats; 12584 } 12585 12586 @Override 12587 public String toString() { 12588 return "MeasureParams{" 12589 + Integer.toHexString(System.identityHashCode(this)) 12590 + " " + mStats.packageName + "}"; 12591 } 12592 12593 @Override 12594 void handleStartCopy() throws RemoteException { 12595 synchronized (mInstallLock) { 12596 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 12597 } 12598 12599 if (mSuccess) { 12600 boolean mounted = false; 12601 try { 12602 final String status = Environment.getExternalStorageState(); 12603 mounted = (Environment.MEDIA_MOUNTED.equals(status) 12604 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 12605 } catch (Exception e) { 12606 } 12607 12608 if (mounted) { 12609 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 12610 12611 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 12612 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 12613 12614 mStats.externalDataSize = calculateDirectorySize(mContainerService, 12615 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 12616 12617 // Always subtract cache size, since it's a subdirectory 12618 mStats.externalDataSize -= mStats.externalCacheSize; 12619 12620 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 12621 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 12622 12623 mStats.externalObbSize = calculateDirectorySize(mContainerService, 12624 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 12625 } 12626 } 12627 } 12628 12629 @Override 12630 void handleReturnCode() { 12631 if (mObserver != null) { 12632 try { 12633 mObserver.onGetStatsCompleted(mStats, mSuccess); 12634 } catch (RemoteException e) { 12635 Slog.i(TAG, "Observer no longer exists."); 12636 } 12637 } 12638 } 12639 12640 @Override 12641 void handleServiceError() { 12642 Slog.e(TAG, "Could not measure application " + mStats.packageName 12643 + " external storage"); 12644 } 12645 } 12646 12647 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 12648 throws RemoteException { 12649 long result = 0; 12650 for (File path : paths) { 12651 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 12652 } 12653 return result; 12654 } 12655 12656 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 12657 for (File path : paths) { 12658 try { 12659 mcs.clearDirectory(path.getAbsolutePath()); 12660 } catch (RemoteException e) { 12661 } 12662 } 12663 } 12664 12665 static class OriginInfo { 12666 /** 12667 * Location where install is coming from, before it has been 12668 * copied/renamed into place. This could be a single monolithic APK 12669 * file, or a cluster directory. This location may be untrusted. 12670 */ 12671 final File file; 12672 final String cid; 12673 12674 /** 12675 * Flag indicating that {@link #file} or {@link #cid} has already been 12676 * staged, meaning downstream users don't need to defensively copy the 12677 * contents. 12678 */ 12679 final boolean staged; 12680 12681 /** 12682 * Flag indicating that {@link #file} or {@link #cid} is an already 12683 * installed app that is being moved. 12684 */ 12685 final boolean existing; 12686 12687 final String resolvedPath; 12688 final File resolvedFile; 12689 12690 static OriginInfo fromNothing() { 12691 return new OriginInfo(null, null, false, false); 12692 } 12693 12694 static OriginInfo fromUntrustedFile(File file) { 12695 return new OriginInfo(file, null, false, false); 12696 } 12697 12698 static OriginInfo fromExistingFile(File file) { 12699 return new OriginInfo(file, null, false, true); 12700 } 12701 12702 static OriginInfo fromStagedFile(File file) { 12703 return new OriginInfo(file, null, true, false); 12704 } 12705 12706 static OriginInfo fromStagedContainer(String cid) { 12707 return new OriginInfo(null, cid, true, false); 12708 } 12709 12710 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 12711 this.file = file; 12712 this.cid = cid; 12713 this.staged = staged; 12714 this.existing = existing; 12715 12716 if (cid != null) { 12717 resolvedPath = PackageHelper.getSdDir(cid); 12718 resolvedFile = new File(resolvedPath); 12719 } else if (file != null) { 12720 resolvedPath = file.getAbsolutePath(); 12721 resolvedFile = file; 12722 } else { 12723 resolvedPath = null; 12724 resolvedFile = null; 12725 } 12726 } 12727 } 12728 12729 static class MoveInfo { 12730 final int moveId; 12731 final String fromUuid; 12732 final String toUuid; 12733 final String packageName; 12734 final String dataAppName; 12735 final int appId; 12736 final String seinfo; 12737 final int targetSdkVersion; 12738 12739 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 12740 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 12741 this.moveId = moveId; 12742 this.fromUuid = fromUuid; 12743 this.toUuid = toUuid; 12744 this.packageName = packageName; 12745 this.dataAppName = dataAppName; 12746 this.appId = appId; 12747 this.seinfo = seinfo; 12748 this.targetSdkVersion = targetSdkVersion; 12749 } 12750 } 12751 12752 static class VerificationInfo { 12753 /** A constant used to indicate that a uid value is not present. */ 12754 public static final int NO_UID = -1; 12755 12756 /** URI referencing where the package was downloaded from. */ 12757 final Uri originatingUri; 12758 12759 /** HTTP referrer URI associated with the originatingURI. */ 12760 final Uri referrer; 12761 12762 /** UID of the application that the install request originated from. */ 12763 final int originatingUid; 12764 12765 /** UID of application requesting the install */ 12766 final int installerUid; 12767 12768 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 12769 this.originatingUri = originatingUri; 12770 this.referrer = referrer; 12771 this.originatingUid = originatingUid; 12772 this.installerUid = installerUid; 12773 } 12774 } 12775 12776 class InstallParams extends HandlerParams { 12777 final OriginInfo origin; 12778 final MoveInfo move; 12779 final IPackageInstallObserver2 observer; 12780 int installFlags; 12781 final String installerPackageName; 12782 final String volumeUuid; 12783 private InstallArgs mArgs; 12784 private int mRet; 12785 final String packageAbiOverride; 12786 final String[] grantedRuntimePermissions; 12787 final VerificationInfo verificationInfo; 12788 final Certificate[][] certificates; 12789 12790 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12791 int installFlags, String installerPackageName, String volumeUuid, 12792 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 12793 String[] grantedPermissions, Certificate[][] certificates) { 12794 super(user); 12795 this.origin = origin; 12796 this.move = move; 12797 this.observer = observer; 12798 this.installFlags = installFlags; 12799 this.installerPackageName = installerPackageName; 12800 this.volumeUuid = volumeUuid; 12801 this.verificationInfo = verificationInfo; 12802 this.packageAbiOverride = packageAbiOverride; 12803 this.grantedRuntimePermissions = grantedPermissions; 12804 this.certificates = certificates; 12805 } 12806 12807 @Override 12808 public String toString() { 12809 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 12810 + " file=" + origin.file + " cid=" + origin.cid + "}"; 12811 } 12812 12813 private int installLocationPolicy(PackageInfoLite pkgLite) { 12814 String packageName = pkgLite.packageName; 12815 int installLocation = pkgLite.installLocation; 12816 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12817 // reader 12818 synchronized (mPackages) { 12819 // Currently installed package which the new package is attempting to replace or 12820 // null if no such package is installed. 12821 PackageParser.Package installedPkg = mPackages.get(packageName); 12822 // Package which currently owns the data which the new package will own if installed. 12823 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 12824 // will be null whereas dataOwnerPkg will contain information about the package 12825 // which was uninstalled while keeping its data. 12826 PackageParser.Package dataOwnerPkg = installedPkg; 12827 if (dataOwnerPkg == null) { 12828 PackageSetting ps = mSettings.mPackages.get(packageName); 12829 if (ps != null) { 12830 dataOwnerPkg = ps.pkg; 12831 } 12832 } 12833 12834 if (dataOwnerPkg != null) { 12835 // If installed, the package will get access to data left on the device by its 12836 // predecessor. As a security measure, this is permited only if this is not a 12837 // version downgrade or if the predecessor package is marked as debuggable and 12838 // a downgrade is explicitly requested. 12839 // 12840 // On debuggable platform builds, downgrades are permitted even for 12841 // non-debuggable packages to make testing easier. Debuggable platform builds do 12842 // not offer security guarantees and thus it's OK to disable some security 12843 // mechanisms to make debugging/testing easier on those builds. However, even on 12844 // debuggable builds downgrades of packages are permitted only if requested via 12845 // installFlags. This is because we aim to keep the behavior of debuggable 12846 // platform builds as close as possible to the behavior of non-debuggable 12847 // platform builds. 12848 final boolean downgradeRequested = 12849 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 12850 final boolean packageDebuggable = 12851 (dataOwnerPkg.applicationInfo.flags 12852 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 12853 final boolean downgradePermitted = 12854 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 12855 if (!downgradePermitted) { 12856 try { 12857 checkDowngrade(dataOwnerPkg, pkgLite); 12858 } catch (PackageManagerException e) { 12859 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 12860 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 12861 } 12862 } 12863 } 12864 12865 if (installedPkg != null) { 12866 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12867 // Check for updated system application. 12868 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 12869 if (onSd) { 12870 Slog.w(TAG, "Cannot install update to system app on sdcard"); 12871 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 12872 } 12873 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12874 } else { 12875 if (onSd) { 12876 // Install flag overrides everything. 12877 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12878 } 12879 // If current upgrade specifies particular preference 12880 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 12881 // Application explicitly specified internal. 12882 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12883 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 12884 // App explictly prefers external. Let policy decide 12885 } else { 12886 // Prefer previous location 12887 if (isExternal(installedPkg)) { 12888 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12889 } 12890 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12891 } 12892 } 12893 } else { 12894 // Invalid install. Return error code 12895 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 12896 } 12897 } 12898 } 12899 // All the special cases have been taken care of. 12900 // Return result based on recommended install location. 12901 if (onSd) { 12902 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12903 } 12904 return pkgLite.recommendedInstallLocation; 12905 } 12906 12907 /* 12908 * Invoke remote method to get package information and install 12909 * location values. Override install location based on default 12910 * policy if needed and then create install arguments based 12911 * on the install location. 12912 */ 12913 public void handleStartCopy() throws RemoteException { 12914 int ret = PackageManager.INSTALL_SUCCEEDED; 12915 12916 // If we're already staged, we've firmly committed to an install location 12917 if (origin.staged) { 12918 if (origin.file != null) { 12919 installFlags |= PackageManager.INSTALL_INTERNAL; 12920 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12921 } else if (origin.cid != null) { 12922 installFlags |= PackageManager.INSTALL_EXTERNAL; 12923 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12924 } else { 12925 throw new IllegalStateException("Invalid stage location"); 12926 } 12927 } 12928 12929 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12930 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 12931 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12932 PackageInfoLite pkgLite = null; 12933 12934 if (onInt && onSd) { 12935 // Check if both bits are set. 12936 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 12937 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12938 } else if (onSd && ephemeral) { 12939 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 12940 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12941 } else { 12942 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 12943 packageAbiOverride); 12944 12945 if (DEBUG_EPHEMERAL && ephemeral) { 12946 Slog.v(TAG, "pkgLite for install: " + pkgLite); 12947 } 12948 12949 /* 12950 * If we have too little free space, try to free cache 12951 * before giving up. 12952 */ 12953 if (!origin.staged && pkgLite.recommendedInstallLocation 12954 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12955 // TODO: focus freeing disk space on the target device 12956 final StorageManager storage = StorageManager.from(mContext); 12957 final long lowThreshold = storage.getStorageLowBytes( 12958 Environment.getDataDirectory()); 12959 12960 final long sizeBytes = mContainerService.calculateInstalledSize( 12961 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 12962 12963 try { 12964 mInstaller.freeCache(null, sizeBytes + lowThreshold); 12965 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 12966 installFlags, packageAbiOverride); 12967 } catch (InstallerException e) { 12968 Slog.w(TAG, "Failed to free cache", e); 12969 } 12970 12971 /* 12972 * The cache free must have deleted the file we 12973 * downloaded to install. 12974 * 12975 * TODO: fix the "freeCache" call to not delete 12976 * the file we care about. 12977 */ 12978 if (pkgLite.recommendedInstallLocation 12979 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12980 pkgLite.recommendedInstallLocation 12981 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 12982 } 12983 } 12984 } 12985 12986 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12987 int loc = pkgLite.recommendedInstallLocation; 12988 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 12989 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12990 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 12991 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 12992 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12993 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12994 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 12995 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 12996 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12997 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 12998 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 12999 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 13000 } else { 13001 // Override with defaults if needed. 13002 loc = installLocationPolicy(pkgLite); 13003 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 13004 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 13005 } else if (!onSd && !onInt) { 13006 // Override install location with flags 13007 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 13008 // Set the flag to install on external media. 13009 installFlags |= PackageManager.INSTALL_EXTERNAL; 13010 installFlags &= ~PackageManager.INSTALL_INTERNAL; 13011 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 13012 if (DEBUG_EPHEMERAL) { 13013 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 13014 } 13015 installFlags |= PackageManager.INSTALL_EPHEMERAL; 13016 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 13017 |PackageManager.INSTALL_INTERNAL); 13018 } else { 13019 // Make sure the flag for installing on external 13020 // media is unset 13021 installFlags |= PackageManager.INSTALL_INTERNAL; 13022 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 13023 } 13024 } 13025 } 13026 } 13027 13028 final InstallArgs args = createInstallArgs(this); 13029 mArgs = args; 13030 13031 if (ret == PackageManager.INSTALL_SUCCEEDED) { 13032 // TODO: http://b/22976637 13033 // Apps installed for "all" users use the device owner to verify the app 13034 UserHandle verifierUser = getUser(); 13035 if (verifierUser == UserHandle.ALL) { 13036 verifierUser = UserHandle.SYSTEM; 13037 } 13038 13039 /* 13040 * Determine if we have any installed package verifiers. If we 13041 * do, then we'll defer to them to verify the packages. 13042 */ 13043 final int requiredUid = mRequiredVerifierPackage == null ? -1 13044 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 13045 verifierUser.getIdentifier()); 13046 if (!origin.existing && requiredUid != -1 13047 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 13048 final Intent verification = new Intent( 13049 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 13050 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 13051 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 13052 PACKAGE_MIME_TYPE); 13053 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 13054 13055 // Query all live verifiers based on current user state 13056 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 13057 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 13058 13059 if (DEBUG_VERIFY) { 13060 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 13061 + verification.toString() + " with " + pkgLite.verifiers.length 13062 + " optional verifiers"); 13063 } 13064 13065 final int verificationId = mPendingVerificationToken++; 13066 13067 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 13068 13069 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 13070 installerPackageName); 13071 13072 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 13073 installFlags); 13074 13075 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 13076 pkgLite.packageName); 13077 13078 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 13079 pkgLite.versionCode); 13080 13081 if (verificationInfo != null) { 13082 if (verificationInfo.originatingUri != null) { 13083 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 13084 verificationInfo.originatingUri); 13085 } 13086 if (verificationInfo.referrer != null) { 13087 verification.putExtra(Intent.EXTRA_REFERRER, 13088 verificationInfo.referrer); 13089 } 13090 if (verificationInfo.originatingUid >= 0) { 13091 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 13092 verificationInfo.originatingUid); 13093 } 13094 if (verificationInfo.installerUid >= 0) { 13095 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 13096 verificationInfo.installerUid); 13097 } 13098 } 13099 13100 final PackageVerificationState verificationState = new PackageVerificationState( 13101 requiredUid, args); 13102 13103 mPendingVerification.append(verificationId, verificationState); 13104 13105 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 13106 receivers, verificationState); 13107 13108 /* 13109 * If any sufficient verifiers were listed in the package 13110 * manifest, attempt to ask them. 13111 */ 13112 if (sufficientVerifiers != null) { 13113 final int N = sufficientVerifiers.size(); 13114 if (N == 0) { 13115 Slog.i(TAG, "Additional verifiers required, but none installed."); 13116 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 13117 } else { 13118 for (int i = 0; i < N; i++) { 13119 final ComponentName verifierComponent = sufficientVerifiers.get(i); 13120 13121 final Intent sufficientIntent = new Intent(verification); 13122 sufficientIntent.setComponent(verifierComponent); 13123 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 13124 } 13125 } 13126 } 13127 13128 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 13129 mRequiredVerifierPackage, receivers); 13130 if (ret == PackageManager.INSTALL_SUCCEEDED 13131 && mRequiredVerifierPackage != null) { 13132 Trace.asyncTraceBegin( 13133 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 13134 /* 13135 * Send the intent to the required verification agent, 13136 * but only start the verification timeout after the 13137 * target BroadcastReceivers have run. 13138 */ 13139 verification.setComponent(requiredVerifierComponent); 13140 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 13141 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13142 new BroadcastReceiver() { 13143 @Override 13144 public void onReceive(Context context, Intent intent) { 13145 final Message msg = mHandler 13146 .obtainMessage(CHECK_PENDING_VERIFICATION); 13147 msg.arg1 = verificationId; 13148 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 13149 } 13150 }, null, 0, null, null); 13151 13152 /* 13153 * We don't want the copy to proceed until verification 13154 * succeeds, so null out this field. 13155 */ 13156 mArgs = null; 13157 } 13158 } else { 13159 /* 13160 * No package verification is enabled, so immediately start 13161 * the remote call to initiate copy using temporary file. 13162 */ 13163 ret = args.copyApk(mContainerService, true); 13164 } 13165 } 13166 13167 mRet = ret; 13168 } 13169 13170 @Override 13171 void handleReturnCode() { 13172 // If mArgs is null, then MCS couldn't be reached. When it 13173 // reconnects, it will try again to install. At that point, this 13174 // will succeed. 13175 if (mArgs != null) { 13176 processPendingInstall(mArgs, mRet); 13177 } 13178 } 13179 13180 @Override 13181 void handleServiceError() { 13182 mArgs = createInstallArgs(this); 13183 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13184 } 13185 13186 public boolean isForwardLocked() { 13187 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13188 } 13189 } 13190 13191 /** 13192 * Used during creation of InstallArgs 13193 * 13194 * @param installFlags package installation flags 13195 * @return true if should be installed on external storage 13196 */ 13197 private static boolean installOnExternalAsec(int installFlags) { 13198 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 13199 return false; 13200 } 13201 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 13202 return true; 13203 } 13204 return false; 13205 } 13206 13207 /** 13208 * Used during creation of InstallArgs 13209 * 13210 * @param installFlags package installation flags 13211 * @return true if should be installed as forward locked 13212 */ 13213 private static boolean installForwardLocked(int installFlags) { 13214 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13215 } 13216 13217 private InstallArgs createInstallArgs(InstallParams params) { 13218 if (params.move != null) { 13219 return new MoveInstallArgs(params); 13220 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 13221 return new AsecInstallArgs(params); 13222 } else { 13223 return new FileInstallArgs(params); 13224 } 13225 } 13226 13227 /** 13228 * Create args that describe an existing installed package. Typically used 13229 * when cleaning up old installs, or used as a move source. 13230 */ 13231 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 13232 String resourcePath, String[] instructionSets) { 13233 final boolean isInAsec; 13234 if (installOnExternalAsec(installFlags)) { 13235 /* Apps on SD card are always in ASEC containers. */ 13236 isInAsec = true; 13237 } else if (installForwardLocked(installFlags) 13238 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 13239 /* 13240 * Forward-locked apps are only in ASEC containers if they're the 13241 * new style 13242 */ 13243 isInAsec = true; 13244 } else { 13245 isInAsec = false; 13246 } 13247 13248 if (isInAsec) { 13249 return new AsecInstallArgs(codePath, instructionSets, 13250 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 13251 } else { 13252 return new FileInstallArgs(codePath, resourcePath, instructionSets); 13253 } 13254 } 13255 13256 static abstract class InstallArgs { 13257 /** @see InstallParams#origin */ 13258 final OriginInfo origin; 13259 /** @see InstallParams#move */ 13260 final MoveInfo move; 13261 13262 final IPackageInstallObserver2 observer; 13263 // Always refers to PackageManager flags only 13264 final int installFlags; 13265 final String installerPackageName; 13266 final String volumeUuid; 13267 final UserHandle user; 13268 final String abiOverride; 13269 final String[] installGrantPermissions; 13270 /** If non-null, drop an async trace when the install completes */ 13271 final String traceMethod; 13272 final int traceCookie; 13273 final Certificate[][] certificates; 13274 13275 // The list of instruction sets supported by this app. This is currently 13276 // only used during the rmdex() phase to clean up resources. We can get rid of this 13277 // if we move dex files under the common app path. 13278 /* nullable */ String[] instructionSets; 13279 13280 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 13281 int installFlags, String installerPackageName, String volumeUuid, 13282 UserHandle user, String[] instructionSets, 13283 String abiOverride, String[] installGrantPermissions, 13284 String traceMethod, int traceCookie, Certificate[][] certificates) { 13285 this.origin = origin; 13286 this.move = move; 13287 this.installFlags = installFlags; 13288 this.observer = observer; 13289 this.installerPackageName = installerPackageName; 13290 this.volumeUuid = volumeUuid; 13291 this.user = user; 13292 this.instructionSets = instructionSets; 13293 this.abiOverride = abiOverride; 13294 this.installGrantPermissions = installGrantPermissions; 13295 this.traceMethod = traceMethod; 13296 this.traceCookie = traceCookie; 13297 this.certificates = certificates; 13298 } 13299 13300 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 13301 abstract int doPreInstall(int status); 13302 13303 /** 13304 * Rename package into final resting place. All paths on the given 13305 * scanned package should be updated to reflect the rename. 13306 */ 13307 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 13308 abstract int doPostInstall(int status, int uid); 13309 13310 /** @see PackageSettingBase#codePathString */ 13311 abstract String getCodePath(); 13312 /** @see PackageSettingBase#resourcePathString */ 13313 abstract String getResourcePath(); 13314 13315 // Need installer lock especially for dex file removal. 13316 abstract void cleanUpResourcesLI(); 13317 abstract boolean doPostDeleteLI(boolean delete); 13318 13319 /** 13320 * Called before the source arguments are copied. This is used mostly 13321 * for MoveParams when it needs to read the source file to put it in the 13322 * destination. 13323 */ 13324 int doPreCopy() { 13325 return PackageManager.INSTALL_SUCCEEDED; 13326 } 13327 13328 /** 13329 * Called after the source arguments are copied. This is used mostly for 13330 * MoveParams when it needs to read the source file to put it in the 13331 * destination. 13332 */ 13333 int doPostCopy(int uid) { 13334 return PackageManager.INSTALL_SUCCEEDED; 13335 } 13336 13337 protected boolean isFwdLocked() { 13338 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13339 } 13340 13341 protected boolean isExternalAsec() { 13342 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 13343 } 13344 13345 protected boolean isEphemeral() { 13346 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13347 } 13348 13349 UserHandle getUser() { 13350 return user; 13351 } 13352 } 13353 13354 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 13355 if (!allCodePaths.isEmpty()) { 13356 if (instructionSets == null) { 13357 throw new IllegalStateException("instructionSet == null"); 13358 } 13359 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 13360 for (String codePath : allCodePaths) { 13361 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 13362 try { 13363 mInstaller.rmdex(codePath, dexCodeInstructionSet); 13364 } catch (InstallerException ignored) { 13365 } 13366 } 13367 } 13368 } 13369 } 13370 13371 /** 13372 * Logic to handle installation of non-ASEC applications, including copying 13373 * and renaming logic. 13374 */ 13375 class FileInstallArgs extends InstallArgs { 13376 private File codeFile; 13377 private File resourceFile; 13378 13379 // Example topology: 13380 // /data/app/com.example/base.apk 13381 // /data/app/com.example/split_foo.apk 13382 // /data/app/com.example/lib/arm/libfoo.so 13383 // /data/app/com.example/lib/arm64/libfoo.so 13384 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 13385 13386 /** New install */ 13387 FileInstallArgs(InstallParams params) { 13388 super(params.origin, params.move, params.observer, params.installFlags, 13389 params.installerPackageName, params.volumeUuid, 13390 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 13391 params.grantedRuntimePermissions, 13392 params.traceMethod, params.traceCookie, params.certificates); 13393 if (isFwdLocked()) { 13394 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 13395 } 13396 } 13397 13398 /** Existing install */ 13399 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 13400 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 13401 null, null, null, 0, null /*certificates*/); 13402 this.codeFile = (codePath != null) ? new File(codePath) : null; 13403 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 13404 } 13405 13406 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13407 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 13408 try { 13409 return doCopyApk(imcs, temp); 13410 } finally { 13411 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13412 } 13413 } 13414 13415 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13416 if (origin.staged) { 13417 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 13418 codeFile = origin.file; 13419 resourceFile = origin.file; 13420 return PackageManager.INSTALL_SUCCEEDED; 13421 } 13422 13423 try { 13424 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13425 final File tempDir = 13426 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 13427 codeFile = tempDir; 13428 resourceFile = tempDir; 13429 } catch (IOException e) { 13430 Slog.w(TAG, "Failed to create copy file: " + e); 13431 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 13432 } 13433 13434 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 13435 @Override 13436 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 13437 if (!FileUtils.isValidExtFilename(name)) { 13438 throw new IllegalArgumentException("Invalid filename: " + name); 13439 } 13440 try { 13441 final File file = new File(codeFile, name); 13442 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 13443 O_RDWR | O_CREAT, 0644); 13444 Os.chmod(file.getAbsolutePath(), 0644); 13445 return new ParcelFileDescriptor(fd); 13446 } catch (ErrnoException e) { 13447 throw new RemoteException("Failed to open: " + e.getMessage()); 13448 } 13449 } 13450 }; 13451 13452 int ret = PackageManager.INSTALL_SUCCEEDED; 13453 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 13454 if (ret != PackageManager.INSTALL_SUCCEEDED) { 13455 Slog.e(TAG, "Failed to copy package"); 13456 return ret; 13457 } 13458 13459 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 13460 NativeLibraryHelper.Handle handle = null; 13461 try { 13462 handle = NativeLibraryHelper.Handle.create(codeFile); 13463 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 13464 abiOverride); 13465 } catch (IOException e) { 13466 Slog.e(TAG, "Copying native libraries failed", e); 13467 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13468 } finally { 13469 IoUtils.closeQuietly(handle); 13470 } 13471 13472 return ret; 13473 } 13474 13475 int doPreInstall(int status) { 13476 if (status != PackageManager.INSTALL_SUCCEEDED) { 13477 cleanUp(); 13478 } 13479 return status; 13480 } 13481 13482 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13483 if (status != PackageManager.INSTALL_SUCCEEDED) { 13484 cleanUp(); 13485 return false; 13486 } 13487 13488 final File targetDir = codeFile.getParentFile(); 13489 final File beforeCodeFile = codeFile; 13490 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 13491 13492 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 13493 try { 13494 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 13495 } catch (ErrnoException e) { 13496 Slog.w(TAG, "Failed to rename", e); 13497 return false; 13498 } 13499 13500 if (!SELinux.restoreconRecursive(afterCodeFile)) { 13501 Slog.w(TAG, "Failed to restorecon"); 13502 return false; 13503 } 13504 13505 // Reflect the rename internally 13506 codeFile = afterCodeFile; 13507 resourceFile = afterCodeFile; 13508 13509 // Reflect the rename in scanned details 13510 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13511 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13512 afterCodeFile, pkg.baseCodePath)); 13513 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13514 afterCodeFile, pkg.splitCodePaths)); 13515 13516 // Reflect the rename in app info 13517 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13518 pkg.setApplicationInfoCodePath(pkg.codePath); 13519 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13520 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13521 pkg.setApplicationInfoResourcePath(pkg.codePath); 13522 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13523 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13524 13525 return true; 13526 } 13527 13528 int doPostInstall(int status, int uid) { 13529 if (status != PackageManager.INSTALL_SUCCEEDED) { 13530 cleanUp(); 13531 } 13532 return status; 13533 } 13534 13535 @Override 13536 String getCodePath() { 13537 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13538 } 13539 13540 @Override 13541 String getResourcePath() { 13542 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13543 } 13544 13545 private boolean cleanUp() { 13546 if (codeFile == null || !codeFile.exists()) { 13547 return false; 13548 } 13549 13550 removeCodePathLI(codeFile); 13551 13552 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 13553 resourceFile.delete(); 13554 } 13555 13556 return true; 13557 } 13558 13559 void cleanUpResourcesLI() { 13560 // Try enumerating all code paths before deleting 13561 List<String> allCodePaths = Collections.EMPTY_LIST; 13562 if (codeFile != null && codeFile.exists()) { 13563 try { 13564 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13565 allCodePaths = pkg.getAllCodePaths(); 13566 } catch (PackageParserException e) { 13567 // Ignored; we tried our best 13568 } 13569 } 13570 13571 cleanUp(); 13572 removeDexFiles(allCodePaths, instructionSets); 13573 } 13574 13575 boolean doPostDeleteLI(boolean delete) { 13576 // XXX err, shouldn't we respect the delete flag? 13577 cleanUpResourcesLI(); 13578 return true; 13579 } 13580 } 13581 13582 private boolean isAsecExternal(String cid) { 13583 final String asecPath = PackageHelper.getSdFilesystem(cid); 13584 return !asecPath.startsWith(mAsecInternalPath); 13585 } 13586 13587 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 13588 PackageManagerException { 13589 if (copyRet < 0) { 13590 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 13591 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 13592 throw new PackageManagerException(copyRet, message); 13593 } 13594 } 13595 } 13596 13597 /** 13598 * Extract the MountService "container ID" from the full code path of an 13599 * .apk. 13600 */ 13601 static String cidFromCodePath(String fullCodePath) { 13602 int eidx = fullCodePath.lastIndexOf("/"); 13603 String subStr1 = fullCodePath.substring(0, eidx); 13604 int sidx = subStr1.lastIndexOf("/"); 13605 return subStr1.substring(sidx+1, eidx); 13606 } 13607 13608 /** 13609 * Logic to handle installation of ASEC applications, including copying and 13610 * renaming logic. 13611 */ 13612 class AsecInstallArgs extends InstallArgs { 13613 static final String RES_FILE_NAME = "pkg.apk"; 13614 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 13615 13616 String cid; 13617 String packagePath; 13618 String resourcePath; 13619 13620 /** New install */ 13621 AsecInstallArgs(InstallParams params) { 13622 super(params.origin, params.move, params.observer, params.installFlags, 13623 params.installerPackageName, params.volumeUuid, 13624 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13625 params.grantedRuntimePermissions, 13626 params.traceMethod, params.traceCookie, params.certificates); 13627 } 13628 13629 /** Existing install */ 13630 AsecInstallArgs(String fullCodePath, String[] instructionSets, 13631 boolean isExternal, boolean isForwardLocked) { 13632 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 13633 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13634 instructionSets, null, null, null, 0, null /*certificates*/); 13635 // Hackily pretend we're still looking at a full code path 13636 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 13637 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 13638 } 13639 13640 // Extract cid from fullCodePath 13641 int eidx = fullCodePath.lastIndexOf("/"); 13642 String subStr1 = fullCodePath.substring(0, eidx); 13643 int sidx = subStr1.lastIndexOf("/"); 13644 cid = subStr1.substring(sidx+1, eidx); 13645 setMountPath(subStr1); 13646 } 13647 13648 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 13649 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 13650 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13651 instructionSets, null, null, null, 0, null /*certificates*/); 13652 this.cid = cid; 13653 setMountPath(PackageHelper.getSdDir(cid)); 13654 } 13655 13656 void createCopyFile() { 13657 cid = mInstallerService.allocateExternalStageCidLegacy(); 13658 } 13659 13660 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13661 if (origin.staged && origin.cid != null) { 13662 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 13663 cid = origin.cid; 13664 setMountPath(PackageHelper.getSdDir(cid)); 13665 return PackageManager.INSTALL_SUCCEEDED; 13666 } 13667 13668 if (temp) { 13669 createCopyFile(); 13670 } else { 13671 /* 13672 * Pre-emptively destroy the container since it's destroyed if 13673 * copying fails due to it existing anyway. 13674 */ 13675 PackageHelper.destroySdDir(cid); 13676 } 13677 13678 final String newMountPath = imcs.copyPackageToContainer( 13679 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 13680 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 13681 13682 if (newMountPath != null) { 13683 setMountPath(newMountPath); 13684 return PackageManager.INSTALL_SUCCEEDED; 13685 } else { 13686 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13687 } 13688 } 13689 13690 @Override 13691 String getCodePath() { 13692 return packagePath; 13693 } 13694 13695 @Override 13696 String getResourcePath() { 13697 return resourcePath; 13698 } 13699 13700 int doPreInstall(int status) { 13701 if (status != PackageManager.INSTALL_SUCCEEDED) { 13702 // Destroy container 13703 PackageHelper.destroySdDir(cid); 13704 } else { 13705 boolean mounted = PackageHelper.isContainerMounted(cid); 13706 if (!mounted) { 13707 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 13708 Process.SYSTEM_UID); 13709 if (newMountPath != null) { 13710 setMountPath(newMountPath); 13711 } else { 13712 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13713 } 13714 } 13715 } 13716 return status; 13717 } 13718 13719 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13720 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 13721 String newMountPath = null; 13722 if (PackageHelper.isContainerMounted(cid)) { 13723 // Unmount the container 13724 if (!PackageHelper.unMountSdDir(cid)) { 13725 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 13726 return false; 13727 } 13728 } 13729 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13730 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 13731 " which might be stale. Will try to clean up."); 13732 // Clean up the stale container and proceed to recreate. 13733 if (!PackageHelper.destroySdDir(newCacheId)) { 13734 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 13735 return false; 13736 } 13737 // Successfully cleaned up stale container. Try to rename again. 13738 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13739 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 13740 + " inspite of cleaning it up."); 13741 return false; 13742 } 13743 } 13744 if (!PackageHelper.isContainerMounted(newCacheId)) { 13745 Slog.w(TAG, "Mounting container " + newCacheId); 13746 newMountPath = PackageHelper.mountSdDir(newCacheId, 13747 getEncryptKey(), Process.SYSTEM_UID); 13748 } else { 13749 newMountPath = PackageHelper.getSdDir(newCacheId); 13750 } 13751 if (newMountPath == null) { 13752 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 13753 return false; 13754 } 13755 Log.i(TAG, "Succesfully renamed " + cid + 13756 " to " + newCacheId + 13757 " at new path: " + newMountPath); 13758 cid = newCacheId; 13759 13760 final File beforeCodeFile = new File(packagePath); 13761 setMountPath(newMountPath); 13762 final File afterCodeFile = new File(packagePath); 13763 13764 // Reflect the rename in scanned details 13765 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13766 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13767 afterCodeFile, pkg.baseCodePath)); 13768 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13769 afterCodeFile, pkg.splitCodePaths)); 13770 13771 // Reflect the rename in app info 13772 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13773 pkg.setApplicationInfoCodePath(pkg.codePath); 13774 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13775 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13776 pkg.setApplicationInfoResourcePath(pkg.codePath); 13777 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13778 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13779 13780 return true; 13781 } 13782 13783 private void setMountPath(String mountPath) { 13784 final File mountFile = new File(mountPath); 13785 13786 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 13787 if (monolithicFile.exists()) { 13788 packagePath = monolithicFile.getAbsolutePath(); 13789 if (isFwdLocked()) { 13790 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 13791 } else { 13792 resourcePath = packagePath; 13793 } 13794 } else { 13795 packagePath = mountFile.getAbsolutePath(); 13796 resourcePath = packagePath; 13797 } 13798 } 13799 13800 int doPostInstall(int status, int uid) { 13801 if (status != PackageManager.INSTALL_SUCCEEDED) { 13802 cleanUp(); 13803 } else { 13804 final int groupOwner; 13805 final String protectedFile; 13806 if (isFwdLocked()) { 13807 groupOwner = UserHandle.getSharedAppGid(uid); 13808 protectedFile = RES_FILE_NAME; 13809 } else { 13810 groupOwner = -1; 13811 protectedFile = null; 13812 } 13813 13814 if (uid < Process.FIRST_APPLICATION_UID 13815 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 13816 Slog.e(TAG, "Failed to finalize " + cid); 13817 PackageHelper.destroySdDir(cid); 13818 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13819 } 13820 13821 boolean mounted = PackageHelper.isContainerMounted(cid); 13822 if (!mounted) { 13823 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 13824 } 13825 } 13826 return status; 13827 } 13828 13829 private void cleanUp() { 13830 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 13831 13832 // Destroy secure container 13833 PackageHelper.destroySdDir(cid); 13834 } 13835 13836 private List<String> getAllCodePaths() { 13837 final File codeFile = new File(getCodePath()); 13838 if (codeFile != null && codeFile.exists()) { 13839 try { 13840 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13841 return pkg.getAllCodePaths(); 13842 } catch (PackageParserException e) { 13843 // Ignored; we tried our best 13844 } 13845 } 13846 return Collections.EMPTY_LIST; 13847 } 13848 13849 void cleanUpResourcesLI() { 13850 // Enumerate all code paths before deleting 13851 cleanUpResourcesLI(getAllCodePaths()); 13852 } 13853 13854 private void cleanUpResourcesLI(List<String> allCodePaths) { 13855 cleanUp(); 13856 removeDexFiles(allCodePaths, instructionSets); 13857 } 13858 13859 String getPackageName() { 13860 return getAsecPackageName(cid); 13861 } 13862 13863 boolean doPostDeleteLI(boolean delete) { 13864 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 13865 final List<String> allCodePaths = getAllCodePaths(); 13866 boolean mounted = PackageHelper.isContainerMounted(cid); 13867 if (mounted) { 13868 // Unmount first 13869 if (PackageHelper.unMountSdDir(cid)) { 13870 mounted = false; 13871 } 13872 } 13873 if (!mounted && delete) { 13874 cleanUpResourcesLI(allCodePaths); 13875 } 13876 return !mounted; 13877 } 13878 13879 @Override 13880 int doPreCopy() { 13881 if (isFwdLocked()) { 13882 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 13883 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 13884 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13885 } 13886 } 13887 13888 return PackageManager.INSTALL_SUCCEEDED; 13889 } 13890 13891 @Override 13892 int doPostCopy(int uid) { 13893 if (isFwdLocked()) { 13894 if (uid < Process.FIRST_APPLICATION_UID 13895 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 13896 RES_FILE_NAME)) { 13897 Slog.e(TAG, "Failed to finalize " + cid); 13898 PackageHelper.destroySdDir(cid); 13899 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13900 } 13901 } 13902 13903 return PackageManager.INSTALL_SUCCEEDED; 13904 } 13905 } 13906 13907 /** 13908 * Logic to handle movement of existing installed applications. 13909 */ 13910 class MoveInstallArgs extends InstallArgs { 13911 private File codeFile; 13912 private File resourceFile; 13913 13914 /** New install */ 13915 MoveInstallArgs(InstallParams params) { 13916 super(params.origin, params.move, params.observer, params.installFlags, 13917 params.installerPackageName, params.volumeUuid, 13918 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13919 params.grantedRuntimePermissions, 13920 params.traceMethod, params.traceCookie, params.certificates); 13921 } 13922 13923 int copyApk(IMediaContainerService imcs, boolean temp) { 13924 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 13925 + move.fromUuid + " to " + move.toUuid); 13926 synchronized (mInstaller) { 13927 try { 13928 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 13929 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 13930 } catch (InstallerException e) { 13931 Slog.w(TAG, "Failed to move app", e); 13932 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13933 } 13934 } 13935 13936 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 13937 resourceFile = codeFile; 13938 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 13939 13940 return PackageManager.INSTALL_SUCCEEDED; 13941 } 13942 13943 int doPreInstall(int status) { 13944 if (status != PackageManager.INSTALL_SUCCEEDED) { 13945 cleanUp(move.toUuid); 13946 } 13947 return status; 13948 } 13949 13950 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13951 if (status != PackageManager.INSTALL_SUCCEEDED) { 13952 cleanUp(move.toUuid); 13953 return false; 13954 } 13955 13956 // Reflect the move in app info 13957 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13958 pkg.setApplicationInfoCodePath(pkg.codePath); 13959 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13960 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13961 pkg.setApplicationInfoResourcePath(pkg.codePath); 13962 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13963 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13964 13965 return true; 13966 } 13967 13968 int doPostInstall(int status, int uid) { 13969 if (status == PackageManager.INSTALL_SUCCEEDED) { 13970 cleanUp(move.fromUuid); 13971 } else { 13972 cleanUp(move.toUuid); 13973 } 13974 return status; 13975 } 13976 13977 @Override 13978 String getCodePath() { 13979 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13980 } 13981 13982 @Override 13983 String getResourcePath() { 13984 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13985 } 13986 13987 private boolean cleanUp(String volumeUuid) { 13988 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 13989 move.dataAppName); 13990 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 13991 final int[] userIds = sUserManager.getUserIds(); 13992 synchronized (mInstallLock) { 13993 // Clean up both app data and code 13994 // All package moves are frozen until finished 13995 for (int userId : userIds) { 13996 try { 13997 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 13998 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 13999 } catch (InstallerException e) { 14000 Slog.w(TAG, String.valueOf(e)); 14001 } 14002 } 14003 removeCodePathLI(codeFile); 14004 } 14005 return true; 14006 } 14007 14008 void cleanUpResourcesLI() { 14009 throw new UnsupportedOperationException(); 14010 } 14011 14012 boolean doPostDeleteLI(boolean delete) { 14013 throw new UnsupportedOperationException(); 14014 } 14015 } 14016 14017 static String getAsecPackageName(String packageCid) { 14018 int idx = packageCid.lastIndexOf("-"); 14019 if (idx == -1) { 14020 return packageCid; 14021 } 14022 return packageCid.substring(0, idx); 14023 } 14024 14025 // Utility method used to create code paths based on package name and available index. 14026 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 14027 String idxStr = ""; 14028 int idx = 1; 14029 // Fall back to default value of idx=1 if prefix is not 14030 // part of oldCodePath 14031 if (oldCodePath != null) { 14032 String subStr = oldCodePath; 14033 // Drop the suffix right away 14034 if (suffix != null && subStr.endsWith(suffix)) { 14035 subStr = subStr.substring(0, subStr.length() - suffix.length()); 14036 } 14037 // If oldCodePath already contains prefix find out the 14038 // ending index to either increment or decrement. 14039 int sidx = subStr.lastIndexOf(prefix); 14040 if (sidx != -1) { 14041 subStr = subStr.substring(sidx + prefix.length()); 14042 if (subStr != null) { 14043 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 14044 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 14045 } 14046 try { 14047 idx = Integer.parseInt(subStr); 14048 if (idx <= 1) { 14049 idx++; 14050 } else { 14051 idx--; 14052 } 14053 } catch(NumberFormatException e) { 14054 } 14055 } 14056 } 14057 } 14058 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 14059 return prefix + idxStr; 14060 } 14061 14062 private File getNextCodePath(File targetDir, String packageName) { 14063 int suffix = 1; 14064 File result; 14065 do { 14066 result = new File(targetDir, packageName + "-" + suffix); 14067 suffix++; 14068 } while (result.exists()); 14069 return result; 14070 } 14071 14072 // Utility method that returns the relative package path with respect 14073 // to the installation directory. Like say for /data/data/com.test-1.apk 14074 // string com.test-1 is returned. 14075 static String deriveCodePathName(String codePath) { 14076 if (codePath == null) { 14077 return null; 14078 } 14079 final File codeFile = new File(codePath); 14080 final String name = codeFile.getName(); 14081 if (codeFile.isDirectory()) { 14082 return name; 14083 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 14084 final int lastDot = name.lastIndexOf('.'); 14085 return name.substring(0, lastDot); 14086 } else { 14087 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 14088 return null; 14089 } 14090 } 14091 14092 static class PackageInstalledInfo { 14093 String name; 14094 int uid; 14095 // The set of users that originally had this package installed. 14096 int[] origUsers; 14097 // The set of users that now have this package installed. 14098 int[] newUsers; 14099 PackageParser.Package pkg; 14100 int returnCode; 14101 String returnMsg; 14102 PackageRemovedInfo removedInfo; 14103 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 14104 14105 public void setError(int code, String msg) { 14106 setReturnCode(code); 14107 setReturnMessage(msg); 14108 Slog.w(TAG, msg); 14109 } 14110 14111 public void setError(String msg, PackageParserException e) { 14112 setReturnCode(e.error); 14113 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 14114 Slog.w(TAG, msg, e); 14115 } 14116 14117 public void setError(String msg, PackageManagerException e) { 14118 returnCode = e.error; 14119 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 14120 Slog.w(TAG, msg, e); 14121 } 14122 14123 public void setReturnCode(int returnCode) { 14124 this.returnCode = returnCode; 14125 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 14126 for (int i = 0; i < childCount; i++) { 14127 addedChildPackages.valueAt(i).returnCode = returnCode; 14128 } 14129 } 14130 14131 private void setReturnMessage(String returnMsg) { 14132 this.returnMsg = returnMsg; 14133 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 14134 for (int i = 0; i < childCount; i++) { 14135 addedChildPackages.valueAt(i).returnMsg = returnMsg; 14136 } 14137 } 14138 14139 // In some error cases we want to convey more info back to the observer 14140 String origPackage; 14141 String origPermission; 14142 } 14143 14144 /* 14145 * Install a non-existing package. 14146 */ 14147 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 14148 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 14149 PackageInstalledInfo res) { 14150 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 14151 14152 // Remember this for later, in case we need to rollback this install 14153 String pkgName = pkg.packageName; 14154 14155 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 14156 14157 synchronized(mPackages) { 14158 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 14159 // A package with the same name is already installed, though 14160 // it has been renamed to an older name. The package we 14161 // are trying to install should be installed as an update to 14162 // the existing one, but that has not been requested, so bail. 14163 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 14164 + " without first uninstalling package running as " 14165 + mSettings.mRenamedPackages.get(pkgName)); 14166 return; 14167 } 14168 if (mPackages.containsKey(pkgName)) { 14169 // Don't allow installation over an existing package with the same name. 14170 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 14171 + " without first uninstalling."); 14172 return; 14173 } 14174 } 14175 14176 try { 14177 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 14178 System.currentTimeMillis(), user); 14179 14180 updateSettingsLI(newPackage, installerPackageName, null, res, user); 14181 14182 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14183 prepareAppDataAfterInstallLIF(newPackage); 14184 14185 } else { 14186 // Remove package from internal structures, but keep around any 14187 // data that might have already existed 14188 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 14189 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 14190 } 14191 } catch (PackageManagerException e) { 14192 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14193 } 14194 14195 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14196 } 14197 14198 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 14199 // Can't rotate keys during boot or if sharedUser. 14200 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 14201 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 14202 return false; 14203 } 14204 // app is using upgradeKeySets; make sure all are valid 14205 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14206 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 14207 for (int i = 0; i < upgradeKeySets.length; i++) { 14208 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 14209 Slog.wtf(TAG, "Package " 14210 + (oldPs.name != null ? oldPs.name : "<null>") 14211 + " contains upgrade-key-set reference to unknown key-set: " 14212 + upgradeKeySets[i] 14213 + " reverting to signatures check."); 14214 return false; 14215 } 14216 } 14217 return true; 14218 } 14219 14220 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 14221 // Upgrade keysets are being used. Determine if new package has a superset of the 14222 // required keys. 14223 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 14224 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14225 for (int i = 0; i < upgradeKeySets.length; i++) { 14226 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 14227 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 14228 return true; 14229 } 14230 } 14231 return false; 14232 } 14233 14234 private static void updateDigest(MessageDigest digest, File file) throws IOException { 14235 try (DigestInputStream digestStream = 14236 new DigestInputStream(new FileInputStream(file), digest)) { 14237 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 14238 } 14239 } 14240 14241 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 14242 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 14243 final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 14244 14245 final PackageParser.Package oldPackage; 14246 final String pkgName = pkg.packageName; 14247 final int[] allUsers; 14248 final int[] installedUsers; 14249 14250 synchronized(mPackages) { 14251 oldPackage = mPackages.get(pkgName); 14252 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 14253 14254 // don't allow upgrade to target a release SDK from a pre-release SDK 14255 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 14256 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14257 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 14258 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14259 if (oldTargetsPreRelease 14260 && !newTargetsPreRelease 14261 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 14262 Slog.w(TAG, "Can't install package targeting released sdk"); 14263 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 14264 return; 14265 } 14266 14267 // don't allow an upgrade from full to ephemeral 14268 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 14269 if (isEphemeral && !oldIsEphemeral) { 14270 // can't downgrade from full to ephemeral 14271 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 14272 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14273 return; 14274 } 14275 14276 // verify signatures are valid 14277 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14278 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14279 if (!checkUpgradeKeySetLP(ps, pkg)) { 14280 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14281 "New package not signed by keys specified by upgrade-keysets: " 14282 + pkgName); 14283 return; 14284 } 14285 } else { 14286 // default to original signature matching 14287 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 14288 != PackageManager.SIGNATURE_MATCH) { 14289 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14290 "New package has a different signature: " + pkgName); 14291 return; 14292 } 14293 } 14294 14295 // don't allow a system upgrade unless the upgrade hash matches 14296 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 14297 byte[] digestBytes = null; 14298 try { 14299 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 14300 updateDigest(digest, new File(pkg.baseCodePath)); 14301 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 14302 for (String path : pkg.splitCodePaths) { 14303 updateDigest(digest, new File(path)); 14304 } 14305 } 14306 digestBytes = digest.digest(); 14307 } catch (NoSuchAlgorithmException | IOException e) { 14308 res.setError(INSTALL_FAILED_INVALID_APK, 14309 "Could not compute hash: " + pkgName); 14310 return; 14311 } 14312 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 14313 res.setError(INSTALL_FAILED_INVALID_APK, 14314 "New package fails restrict-update check: " + pkgName); 14315 return; 14316 } 14317 // retain upgrade restriction 14318 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 14319 } 14320 14321 // Check for shared user id changes 14322 String invalidPackageName = 14323 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 14324 if (invalidPackageName != null) { 14325 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 14326 "Package " + invalidPackageName + " tried to change user " 14327 + oldPackage.mSharedUserId); 14328 return; 14329 } 14330 14331 // In case of rollback, remember per-user/profile install state 14332 allUsers = sUserManager.getUserIds(); 14333 installedUsers = ps.queryInstalledUsers(allUsers, true); 14334 } 14335 14336 // Update what is removed 14337 res.removedInfo = new PackageRemovedInfo(); 14338 res.removedInfo.uid = oldPackage.applicationInfo.uid; 14339 res.removedInfo.removedPackage = oldPackage.packageName; 14340 res.removedInfo.isUpdate = true; 14341 res.removedInfo.origUsers = installedUsers; 14342 final int childCount = (oldPackage.childPackages != null) 14343 ? oldPackage.childPackages.size() : 0; 14344 for (int i = 0; i < childCount; i++) { 14345 boolean childPackageUpdated = false; 14346 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 14347 if (res.addedChildPackages != null) { 14348 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14349 if (childRes != null) { 14350 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 14351 childRes.removedInfo.removedPackage = childPkg.packageName; 14352 childRes.removedInfo.isUpdate = true; 14353 childPackageUpdated = true; 14354 } 14355 } 14356 if (!childPackageUpdated) { 14357 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 14358 childRemovedRes.removedPackage = childPkg.packageName; 14359 childRemovedRes.isUpdate = false; 14360 childRemovedRes.dataRemoved = true; 14361 synchronized (mPackages) { 14362 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14363 if (childPs != null) { 14364 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 14365 } 14366 } 14367 if (res.removedInfo.removedChildPackages == null) { 14368 res.removedInfo.removedChildPackages = new ArrayMap<>(); 14369 } 14370 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 14371 } 14372 } 14373 14374 boolean sysPkg = (isSystemApp(oldPackage)); 14375 if (sysPkg) { 14376 // Set the system/privileged flags as needed 14377 final boolean privileged = 14378 (oldPackage.applicationInfo.privateFlags 14379 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14380 final int systemPolicyFlags = policyFlags 14381 | PackageParser.PARSE_IS_SYSTEM 14382 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 14383 14384 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 14385 user, allUsers, installerPackageName, res); 14386 } else { 14387 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 14388 user, allUsers, installerPackageName, res); 14389 } 14390 } 14391 14392 public List<String> getPreviousCodePaths(String packageName) { 14393 final PackageSetting ps = mSettings.mPackages.get(packageName); 14394 final List<String> result = new ArrayList<String>(); 14395 if (ps != null && ps.oldCodePaths != null) { 14396 result.addAll(ps.oldCodePaths); 14397 } 14398 return result; 14399 } 14400 14401 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 14402 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14403 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14404 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 14405 + deletedPackage); 14406 14407 String pkgName = deletedPackage.packageName; 14408 boolean deletedPkg = true; 14409 boolean addedPkg = false; 14410 boolean updatedSettings = false; 14411 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 14412 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 14413 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 14414 14415 final long origUpdateTime = (pkg.mExtras != null) 14416 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 14417 14418 // First delete the existing package while retaining the data directory 14419 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14420 res.removedInfo, true, pkg)) { 14421 // If the existing package wasn't successfully deleted 14422 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 14423 deletedPkg = false; 14424 } else { 14425 // Successfully deleted the old package; proceed with replace. 14426 14427 // If deleted package lived in a container, give users a chance to 14428 // relinquish resources before killing. 14429 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 14430 if (DEBUG_INSTALL) { 14431 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 14432 } 14433 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 14434 final ArrayList<String> pkgList = new ArrayList<String>(1); 14435 pkgList.add(deletedPackage.applicationInfo.packageName); 14436 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 14437 } 14438 14439 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14440 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14441 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14442 14443 try { 14444 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 14445 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 14446 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14447 14448 // Update the in-memory copy of the previous code paths. 14449 PackageSetting ps = mSettings.mPackages.get(pkgName); 14450 if (!killApp) { 14451 if (ps.oldCodePaths == null) { 14452 ps.oldCodePaths = new ArraySet<>(); 14453 } 14454 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 14455 if (deletedPackage.splitCodePaths != null) { 14456 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 14457 } 14458 } else { 14459 ps.oldCodePaths = null; 14460 } 14461 if (ps.childPackageNames != null) { 14462 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 14463 final String childPkgName = ps.childPackageNames.get(i); 14464 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 14465 childPs.oldCodePaths = ps.oldCodePaths; 14466 } 14467 } 14468 prepareAppDataAfterInstallLIF(newPackage); 14469 addedPkg = true; 14470 } catch (PackageManagerException e) { 14471 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14472 } 14473 } 14474 14475 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14476 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 14477 14478 // Revert all internal state mutations and added folders for the failed install 14479 if (addedPkg) { 14480 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14481 res.removedInfo, true, null); 14482 } 14483 14484 // Restore the old package 14485 if (deletedPkg) { 14486 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 14487 File restoreFile = new File(deletedPackage.codePath); 14488 // Parse old package 14489 boolean oldExternal = isExternal(deletedPackage); 14490 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 14491 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 14492 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 14493 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 14494 try { 14495 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 14496 null); 14497 } catch (PackageManagerException e) { 14498 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 14499 + e.getMessage()); 14500 return; 14501 } 14502 14503 synchronized (mPackages) { 14504 // Ensure the installer package name up to date 14505 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14506 14507 // Update permissions for restored package 14508 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14509 14510 mSettings.writeLPr(); 14511 } 14512 14513 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 14514 } 14515 } else { 14516 synchronized (mPackages) { 14517 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 14518 if (ps != null) { 14519 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 14520 if (res.removedInfo.removedChildPackages != null) { 14521 final int childCount = res.removedInfo.removedChildPackages.size(); 14522 // Iterate in reverse as we may modify the collection 14523 for (int i = childCount - 1; i >= 0; i--) { 14524 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 14525 if (res.addedChildPackages.containsKey(childPackageName)) { 14526 res.removedInfo.removedChildPackages.removeAt(i); 14527 } else { 14528 PackageRemovedInfo childInfo = res.removedInfo 14529 .removedChildPackages.valueAt(i); 14530 childInfo.removedForAllUsers = mPackages.get( 14531 childInfo.removedPackage) == null; 14532 } 14533 } 14534 } 14535 } 14536 } 14537 } 14538 } 14539 14540 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 14541 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14542 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14543 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 14544 + ", old=" + deletedPackage); 14545 14546 final boolean disabledSystem; 14547 14548 // Remove existing system package 14549 removePackageLI(deletedPackage, true); 14550 14551 synchronized (mPackages) { 14552 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 14553 } 14554 if (!disabledSystem) { 14555 // We didn't need to disable the .apk as a current system package, 14556 // which means we are replacing another update that is already 14557 // installed. We need to make sure to delete the older one's .apk. 14558 res.removedInfo.args = createInstallArgsForExisting(0, 14559 deletedPackage.applicationInfo.getCodePath(), 14560 deletedPackage.applicationInfo.getResourcePath(), 14561 getAppDexInstructionSets(deletedPackage.applicationInfo)); 14562 } else { 14563 res.removedInfo.args = null; 14564 } 14565 14566 // Successfully disabled the old package. Now proceed with re-installation 14567 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14568 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14569 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14570 14571 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14572 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 14573 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 14574 14575 PackageParser.Package newPackage = null; 14576 try { 14577 // Add the package to the internal data structures 14578 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 14579 14580 // Set the update and install times 14581 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 14582 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 14583 System.currentTimeMillis()); 14584 14585 // Update the package dynamic state if succeeded 14586 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14587 // Now that the install succeeded make sure we remove data 14588 // directories for any child package the update removed. 14589 final int deletedChildCount = (deletedPackage.childPackages != null) 14590 ? deletedPackage.childPackages.size() : 0; 14591 final int newChildCount = (newPackage.childPackages != null) 14592 ? newPackage.childPackages.size() : 0; 14593 for (int i = 0; i < deletedChildCount; i++) { 14594 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 14595 boolean childPackageDeleted = true; 14596 for (int j = 0; j < newChildCount; j++) { 14597 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 14598 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 14599 childPackageDeleted = false; 14600 break; 14601 } 14602 } 14603 if (childPackageDeleted) { 14604 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 14605 deletedChildPkg.packageName); 14606 if (ps != null && res.removedInfo.removedChildPackages != null) { 14607 PackageRemovedInfo removedChildRes = res.removedInfo 14608 .removedChildPackages.get(deletedChildPkg.packageName); 14609 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 14610 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 14611 } 14612 } 14613 } 14614 14615 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14616 prepareAppDataAfterInstallLIF(newPackage); 14617 } 14618 } catch (PackageManagerException e) { 14619 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 14620 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14621 } 14622 14623 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14624 // Re installation failed. Restore old information 14625 // Remove new pkg information 14626 if (newPackage != null) { 14627 removeInstalledPackageLI(newPackage, true); 14628 } 14629 // Add back the old system package 14630 try { 14631 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 14632 } catch (PackageManagerException e) { 14633 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 14634 } 14635 14636 synchronized (mPackages) { 14637 if (disabledSystem) { 14638 enableSystemPackageLPw(deletedPackage); 14639 } 14640 14641 // Ensure the installer package name up to date 14642 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14643 14644 // Update permissions for restored package 14645 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14646 14647 mSettings.writeLPr(); 14648 } 14649 14650 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 14651 + " after failed upgrade"); 14652 } 14653 } 14654 14655 /** 14656 * Checks whether the parent or any of the child packages have a change shared 14657 * user. For a package to be a valid update the shred users of the parent and 14658 * the children should match. We may later support changing child shared users. 14659 * @param oldPkg The updated package. 14660 * @param newPkg The update package. 14661 * @return The shared user that change between the versions. 14662 */ 14663 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 14664 PackageParser.Package newPkg) { 14665 // Check parent shared user 14666 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 14667 return newPkg.packageName; 14668 } 14669 // Check child shared users 14670 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14671 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 14672 for (int i = 0; i < newChildCount; i++) { 14673 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 14674 // If this child was present, did it have the same shared user? 14675 for (int j = 0; j < oldChildCount; j++) { 14676 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 14677 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 14678 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 14679 return newChildPkg.packageName; 14680 } 14681 } 14682 } 14683 return null; 14684 } 14685 14686 private void removeNativeBinariesLI(PackageSetting ps) { 14687 // Remove the lib path for the parent package 14688 if (ps != null) { 14689 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 14690 // Remove the lib path for the child packages 14691 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 14692 for (int i = 0; i < childCount; i++) { 14693 PackageSetting childPs = null; 14694 synchronized (mPackages) { 14695 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 14696 } 14697 if (childPs != null) { 14698 NativeLibraryHelper.removeNativeBinariesLI(childPs 14699 .legacyNativeLibraryPathString); 14700 } 14701 } 14702 } 14703 } 14704 14705 private void enableSystemPackageLPw(PackageParser.Package pkg) { 14706 // Enable the parent package 14707 mSettings.enableSystemPackageLPw(pkg.packageName); 14708 // Enable the child packages 14709 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14710 for (int i = 0; i < childCount; i++) { 14711 PackageParser.Package childPkg = pkg.childPackages.get(i); 14712 mSettings.enableSystemPackageLPw(childPkg.packageName); 14713 } 14714 } 14715 14716 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 14717 PackageParser.Package newPkg) { 14718 // Disable the parent package (parent always replaced) 14719 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 14720 // Disable the child packages 14721 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14722 for (int i = 0; i < childCount; i++) { 14723 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 14724 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 14725 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 14726 } 14727 return disabled; 14728 } 14729 14730 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 14731 String installerPackageName) { 14732 // Enable the parent package 14733 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 14734 // Enable the child packages 14735 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14736 for (int i = 0; i < childCount; i++) { 14737 PackageParser.Package childPkg = pkg.childPackages.get(i); 14738 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 14739 } 14740 } 14741 14742 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 14743 // Collect all used permissions in the UID 14744 ArraySet<String> usedPermissions = new ArraySet<>(); 14745 final int packageCount = su.packages.size(); 14746 for (int i = 0; i < packageCount; i++) { 14747 PackageSetting ps = su.packages.valueAt(i); 14748 if (ps.pkg == null) { 14749 continue; 14750 } 14751 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 14752 for (int j = 0; j < requestedPermCount; j++) { 14753 String permission = ps.pkg.requestedPermissions.get(j); 14754 BasePermission bp = mSettings.mPermissions.get(permission); 14755 if (bp != null) { 14756 usedPermissions.add(permission); 14757 } 14758 } 14759 } 14760 14761 PermissionsState permissionsState = su.getPermissionsState(); 14762 // Prune install permissions 14763 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 14764 final int installPermCount = installPermStates.size(); 14765 for (int i = installPermCount - 1; i >= 0; i--) { 14766 PermissionState permissionState = installPermStates.get(i); 14767 if (!usedPermissions.contains(permissionState.getName())) { 14768 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14769 if (bp != null) { 14770 permissionsState.revokeInstallPermission(bp); 14771 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 14772 PackageManager.MASK_PERMISSION_FLAGS, 0); 14773 } 14774 } 14775 } 14776 14777 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 14778 14779 // Prune runtime permissions 14780 for (int userId : allUserIds) { 14781 List<PermissionState> runtimePermStates = permissionsState 14782 .getRuntimePermissionStates(userId); 14783 final int runtimePermCount = runtimePermStates.size(); 14784 for (int i = runtimePermCount - 1; i >= 0; i--) { 14785 PermissionState permissionState = runtimePermStates.get(i); 14786 if (!usedPermissions.contains(permissionState.getName())) { 14787 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14788 if (bp != null) { 14789 permissionsState.revokeRuntimePermission(bp, userId); 14790 permissionsState.updatePermissionFlags(bp, userId, 14791 PackageManager.MASK_PERMISSION_FLAGS, 0); 14792 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 14793 runtimePermissionChangedUserIds, userId); 14794 } 14795 } 14796 } 14797 } 14798 14799 return runtimePermissionChangedUserIds; 14800 } 14801 14802 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 14803 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 14804 // Update the parent package setting 14805 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 14806 res, user); 14807 // Update the child packages setting 14808 final int childCount = (newPackage.childPackages != null) 14809 ? newPackage.childPackages.size() : 0; 14810 for (int i = 0; i < childCount; i++) { 14811 PackageParser.Package childPackage = newPackage.childPackages.get(i); 14812 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 14813 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 14814 childRes.origUsers, childRes, user); 14815 } 14816 } 14817 14818 private void updateSettingsInternalLI(PackageParser.Package newPackage, 14819 String installerPackageName, int[] allUsers, int[] installedForUsers, 14820 PackageInstalledInfo res, UserHandle user) { 14821 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 14822 14823 String pkgName = newPackage.packageName; 14824 synchronized (mPackages) { 14825 //write settings. the installStatus will be incomplete at this stage. 14826 //note that the new package setting would have already been 14827 //added to mPackages. It hasn't been persisted yet. 14828 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 14829 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14830 mSettings.writeLPr(); 14831 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14832 } 14833 14834 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 14835 synchronized (mPackages) { 14836 updatePermissionsLPw(newPackage.packageName, newPackage, 14837 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 14838 ? UPDATE_PERMISSIONS_ALL : 0)); 14839 // For system-bundled packages, we assume that installing an upgraded version 14840 // of the package implies that the user actually wants to run that new code, 14841 // so we enable the package. 14842 PackageSetting ps = mSettings.mPackages.get(pkgName); 14843 final int userId = user.getIdentifier(); 14844 if (ps != null) { 14845 if (isSystemApp(newPackage)) { 14846 if (DEBUG_INSTALL) { 14847 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 14848 } 14849 // Enable system package for requested users 14850 if (res.origUsers != null) { 14851 for (int origUserId : res.origUsers) { 14852 if (userId == UserHandle.USER_ALL || userId == origUserId) { 14853 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 14854 origUserId, installerPackageName); 14855 } 14856 } 14857 } 14858 // Also convey the prior install/uninstall state 14859 if (allUsers != null && installedForUsers != null) { 14860 for (int currentUserId : allUsers) { 14861 final boolean installed = ArrayUtils.contains( 14862 installedForUsers, currentUserId); 14863 if (DEBUG_INSTALL) { 14864 Slog.d(TAG, " user " + currentUserId + " => " + installed); 14865 } 14866 ps.setInstalled(installed, currentUserId); 14867 } 14868 // these install state changes will be persisted in the 14869 // upcoming call to mSettings.writeLPr(). 14870 } 14871 } 14872 // It's implied that when a user requests installation, they want the app to be 14873 // installed and enabled. 14874 if (userId != UserHandle.USER_ALL) { 14875 ps.setInstalled(true, userId); 14876 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 14877 } 14878 } 14879 res.name = pkgName; 14880 res.uid = newPackage.applicationInfo.uid; 14881 res.pkg = newPackage; 14882 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 14883 mSettings.setInstallerPackageName(pkgName, installerPackageName); 14884 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14885 //to update install status 14886 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14887 mSettings.writeLPr(); 14888 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14889 } 14890 14891 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14892 } 14893 14894 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 14895 try { 14896 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 14897 installPackageLI(args, res); 14898 } finally { 14899 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14900 } 14901 } 14902 14903 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 14904 final int installFlags = args.installFlags; 14905 final String installerPackageName = args.installerPackageName; 14906 final String volumeUuid = args.volumeUuid; 14907 final File tmpPackageFile = new File(args.getCodePath()); 14908 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 14909 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 14910 || (args.volumeUuid != null)); 14911 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 14912 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 14913 boolean replace = false; 14914 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 14915 if (args.move != null) { 14916 // moving a complete application; perform an initial scan on the new install location 14917 scanFlags |= SCAN_INITIAL; 14918 } 14919 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 14920 scanFlags |= SCAN_DONT_KILL_APP; 14921 } 14922 14923 // Result object to be returned 14924 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14925 14926 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 14927 14928 // Sanity check 14929 if (ephemeral && (forwardLocked || onExternal)) { 14930 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 14931 + " external=" + onExternal); 14932 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14933 return; 14934 } 14935 14936 // Retrieve PackageSettings and parse package 14937 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 14938 | PackageParser.PARSE_ENFORCE_CODE 14939 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 14940 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 14941 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0) 14942 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 14943 PackageParser pp = new PackageParser(); 14944 pp.setSeparateProcesses(mSeparateProcesses); 14945 pp.setDisplayMetrics(mMetrics); 14946 14947 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 14948 final PackageParser.Package pkg; 14949 try { 14950 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 14951 } catch (PackageParserException e) { 14952 res.setError("Failed parse during installPackageLI", e); 14953 return; 14954 } finally { 14955 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14956 } 14957 14958 // If we are installing a clustered package add results for the children 14959 if (pkg.childPackages != null) { 14960 synchronized (mPackages) { 14961 final int childCount = pkg.childPackages.size(); 14962 for (int i = 0; i < childCount; i++) { 14963 PackageParser.Package childPkg = pkg.childPackages.get(i); 14964 PackageInstalledInfo childRes = new PackageInstalledInfo(); 14965 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14966 childRes.pkg = childPkg; 14967 childRes.name = childPkg.packageName; 14968 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14969 if (childPs != null) { 14970 childRes.origUsers = childPs.queryInstalledUsers( 14971 sUserManager.getUserIds(), true); 14972 } 14973 if ((mPackages.containsKey(childPkg.packageName))) { 14974 childRes.removedInfo = new PackageRemovedInfo(); 14975 childRes.removedInfo.removedPackage = childPkg.packageName; 14976 } 14977 if (res.addedChildPackages == null) { 14978 res.addedChildPackages = new ArrayMap<>(); 14979 } 14980 res.addedChildPackages.put(childPkg.packageName, childRes); 14981 } 14982 } 14983 } 14984 14985 // If package doesn't declare API override, mark that we have an install 14986 // time CPU ABI override. 14987 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 14988 pkg.cpuAbiOverride = args.abiOverride; 14989 } 14990 14991 String pkgName = res.name = pkg.packageName; 14992 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 14993 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 14994 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 14995 return; 14996 } 14997 } 14998 14999 try { 15000 // either use what we've been given or parse directly from the APK 15001 if (args.certificates != null) { 15002 try { 15003 PackageParser.populateCertificates(pkg, args.certificates); 15004 } catch (PackageParserException e) { 15005 // there was something wrong with the certificates we were given; 15006 // try to pull them from the APK 15007 PackageParser.collectCertificates(pkg, parseFlags); 15008 } 15009 } else { 15010 PackageParser.collectCertificates(pkg, parseFlags); 15011 } 15012 } catch (PackageParserException e) { 15013 res.setError("Failed collect during installPackageLI", e); 15014 return; 15015 } 15016 15017 // Get rid of all references to package scan path via parser. 15018 pp = null; 15019 String oldCodePath = null; 15020 boolean systemApp = false; 15021 synchronized (mPackages) { 15022 // Check if installing already existing package 15023 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 15024 String oldName = mSettings.mRenamedPackages.get(pkgName); 15025 if (pkg.mOriginalPackages != null 15026 && pkg.mOriginalPackages.contains(oldName) 15027 && mPackages.containsKey(oldName)) { 15028 // This package is derived from an original package, 15029 // and this device has been updating from that original 15030 // name. We must continue using the original name, so 15031 // rename the new package here. 15032 pkg.setPackageName(oldName); 15033 pkgName = pkg.packageName; 15034 replace = true; 15035 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 15036 + oldName + " pkgName=" + pkgName); 15037 } else if (mPackages.containsKey(pkgName)) { 15038 // This package, under its official name, already exists 15039 // on the device; we should replace it. 15040 replace = true; 15041 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 15042 } 15043 15044 // Child packages are installed through the parent package 15045 if (pkg.parentPackage != null) { 15046 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 15047 "Package " + pkg.packageName + " is child of package " 15048 + pkg.parentPackage.parentPackage + ". Child packages " 15049 + "can be updated only through the parent package."); 15050 return; 15051 } 15052 15053 if (replace) { 15054 // Prevent apps opting out from runtime permissions 15055 PackageParser.Package oldPackage = mPackages.get(pkgName); 15056 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 15057 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 15058 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 15059 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 15060 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 15061 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 15062 + " doesn't support runtime permissions but the old" 15063 + " target SDK " + oldTargetSdk + " does."); 15064 return; 15065 } 15066 15067 // Prevent installing of child packages 15068 if (oldPackage.parentPackage != null) { 15069 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 15070 "Package " + pkg.packageName + " is child of package " 15071 + oldPackage.parentPackage + ". Child packages " 15072 + "can be updated only through the parent package."); 15073 return; 15074 } 15075 } 15076 } 15077 15078 PackageSetting ps = mSettings.mPackages.get(pkgName); 15079 if (ps != null) { 15080 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 15081 15082 // Quick sanity check that we're signed correctly if updating; 15083 // we'll check this again later when scanning, but we want to 15084 // bail early here before tripping over redefined permissions. 15085 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 15086 if (!checkUpgradeKeySetLP(ps, pkg)) { 15087 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 15088 + pkg.packageName + " upgrade keys do not match the " 15089 + "previously installed version"); 15090 return; 15091 } 15092 } else { 15093 try { 15094 verifySignaturesLP(ps, pkg); 15095 } catch (PackageManagerException e) { 15096 res.setError(e.error, e.getMessage()); 15097 return; 15098 } 15099 } 15100 15101 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 15102 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 15103 systemApp = (ps.pkg.applicationInfo.flags & 15104 ApplicationInfo.FLAG_SYSTEM) != 0; 15105 } 15106 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 15107 } 15108 15109 // Check whether the newly-scanned package wants to define an already-defined perm 15110 int N = pkg.permissions.size(); 15111 for (int i = N-1; i >= 0; i--) { 15112 PackageParser.Permission perm = pkg.permissions.get(i); 15113 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 15114 if (bp != null) { 15115 // If the defining package is signed with our cert, it's okay. This 15116 // also includes the "updating the same package" case, of course. 15117 // "updating same package" could also involve key-rotation. 15118 final boolean sigsOk; 15119 if (bp.sourcePackage.equals(pkg.packageName) 15120 && (bp.packageSetting instanceof PackageSetting) 15121 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 15122 scanFlags))) { 15123 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 15124 } else { 15125 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 15126 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 15127 } 15128 if (!sigsOk) { 15129 // If the owning package is the system itself, we log but allow 15130 // install to proceed; we fail the install on all other permission 15131 // redefinitions. 15132 if (!bp.sourcePackage.equals("android")) { 15133 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 15134 + pkg.packageName + " attempting to redeclare permission " 15135 + perm.info.name + " already owned by " + bp.sourcePackage); 15136 res.origPermission = perm.info.name; 15137 res.origPackage = bp.sourcePackage; 15138 return; 15139 } else { 15140 Slog.w(TAG, "Package " + pkg.packageName 15141 + " attempting to redeclare system permission " 15142 + perm.info.name + "; ignoring new declaration"); 15143 pkg.permissions.remove(i); 15144 } 15145 } 15146 } 15147 } 15148 } 15149 15150 if (systemApp) { 15151 if (onExternal) { 15152 // Abort update; system app can't be replaced with app on sdcard 15153 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 15154 "Cannot install updates to system apps on sdcard"); 15155 return; 15156 } else if (ephemeral) { 15157 // Abort update; system app can't be replaced with an ephemeral app 15158 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 15159 "Cannot update a system app with an ephemeral app"); 15160 return; 15161 } 15162 } 15163 15164 if (args.move != null) { 15165 // We did an in-place move, so dex is ready to roll 15166 scanFlags |= SCAN_NO_DEX; 15167 scanFlags |= SCAN_MOVE; 15168 15169 synchronized (mPackages) { 15170 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15171 if (ps == null) { 15172 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 15173 "Missing settings for moved package " + pkgName); 15174 } 15175 15176 // We moved the entire application as-is, so bring over the 15177 // previously derived ABI information. 15178 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 15179 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 15180 } 15181 15182 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 15183 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 15184 scanFlags |= SCAN_NO_DEX; 15185 15186 try { 15187 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 15188 args.abiOverride : pkg.cpuAbiOverride); 15189 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 15190 true /* extract libs */); 15191 } catch (PackageManagerException pme) { 15192 Slog.e(TAG, "Error deriving application ABI", pme); 15193 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 15194 return; 15195 } 15196 15197 // Shared libraries for the package need to be updated. 15198 synchronized (mPackages) { 15199 try { 15200 updateSharedLibrariesLPw(pkg, null); 15201 } catch (PackageManagerException e) { 15202 Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage()); 15203 } 15204 } 15205 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 15206 // Do not run PackageDexOptimizer through the local performDexOpt 15207 // method because `pkg` may not be in `mPackages` yet. 15208 // 15209 // Also, don't fail application installs if the dexopt step fails. 15210 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 15211 null /* instructionSets */, false /* checkProfiles */, 15212 getCompilerFilterForReason(REASON_INSTALL)); 15213 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15214 15215 // Notify BackgroundDexOptService that the package has been changed. 15216 // If this is an update of a package which used to fail to compile, 15217 // BDOS will remove it from its blacklist. 15218 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 15219 } 15220 15221 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 15222 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 15223 return; 15224 } 15225 15226 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 15227 15228 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 15229 "installPackageLI")) { 15230 if (replace) { 15231 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 15232 installerPackageName, res); 15233 } else { 15234 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 15235 args.user, installerPackageName, volumeUuid, res); 15236 } 15237 } 15238 synchronized (mPackages) { 15239 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15240 if (ps != null) { 15241 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 15242 } 15243 15244 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15245 for (int i = 0; i < childCount; i++) { 15246 PackageParser.Package childPkg = pkg.childPackages.get(i); 15247 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 15248 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 15249 if (childPs != null) { 15250 childRes.newUsers = childPs.queryInstalledUsers( 15251 sUserManager.getUserIds(), true); 15252 } 15253 } 15254 } 15255 } 15256 15257 private void startIntentFilterVerifications(int userId, boolean replacing, 15258 PackageParser.Package pkg) { 15259 if (mIntentFilterVerifierComponent == null) { 15260 Slog.w(TAG, "No IntentFilter verification will not be done as " 15261 + "there is no IntentFilterVerifier available!"); 15262 return; 15263 } 15264 15265 final int verifierUid = getPackageUid( 15266 mIntentFilterVerifierComponent.getPackageName(), 15267 MATCH_DEBUG_TRIAGED_MISSING, 15268 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 15269 15270 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15271 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 15272 mHandler.sendMessage(msg); 15273 15274 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15275 for (int i = 0; i < childCount; i++) { 15276 PackageParser.Package childPkg = pkg.childPackages.get(i); 15277 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15278 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 15279 mHandler.sendMessage(msg); 15280 } 15281 } 15282 15283 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 15284 PackageParser.Package pkg) { 15285 int size = pkg.activities.size(); 15286 if (size == 0) { 15287 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15288 "No activity, so no need to verify any IntentFilter!"); 15289 return; 15290 } 15291 15292 final boolean hasDomainURLs = hasDomainURLs(pkg); 15293 if (!hasDomainURLs) { 15294 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15295 "No domain URLs, so no need to verify any IntentFilter!"); 15296 return; 15297 } 15298 15299 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 15300 + " if any IntentFilter from the " + size 15301 + " Activities needs verification ..."); 15302 15303 int count = 0; 15304 final String packageName = pkg.packageName; 15305 15306 synchronized (mPackages) { 15307 // If this is a new install and we see that we've already run verification for this 15308 // package, we have nothing to do: it means the state was restored from backup. 15309 if (!replacing) { 15310 IntentFilterVerificationInfo ivi = 15311 mSettings.getIntentFilterVerificationLPr(packageName); 15312 if (ivi != null) { 15313 if (DEBUG_DOMAIN_VERIFICATION) { 15314 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 15315 + ivi.getStatusString()); 15316 } 15317 return; 15318 } 15319 } 15320 15321 // If any filters need to be verified, then all need to be. 15322 boolean needToVerify = false; 15323 for (PackageParser.Activity a : pkg.activities) { 15324 for (ActivityIntentInfo filter : a.intents) { 15325 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 15326 if (DEBUG_DOMAIN_VERIFICATION) { 15327 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 15328 } 15329 needToVerify = true; 15330 break; 15331 } 15332 } 15333 } 15334 15335 if (needToVerify) { 15336 final int verificationId = mIntentFilterVerificationToken++; 15337 for (PackageParser.Activity a : pkg.activities) { 15338 for (ActivityIntentInfo filter : a.intents) { 15339 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 15340 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15341 "Verification needed for IntentFilter:" + filter.toString()); 15342 mIntentFilterVerifier.addOneIntentFilterVerification( 15343 verifierUid, userId, verificationId, filter, packageName); 15344 count++; 15345 } 15346 } 15347 } 15348 } 15349 } 15350 15351 if (count > 0) { 15352 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 15353 + " IntentFilter verification" + (count > 1 ? "s" : "") 15354 + " for userId:" + userId); 15355 mIntentFilterVerifier.startVerifications(userId); 15356 } else { 15357 if (DEBUG_DOMAIN_VERIFICATION) { 15358 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 15359 } 15360 } 15361 } 15362 15363 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 15364 final ComponentName cn = filter.activity.getComponentName(); 15365 final String packageName = cn.getPackageName(); 15366 15367 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 15368 packageName); 15369 if (ivi == null) { 15370 return true; 15371 } 15372 int status = ivi.getStatus(); 15373 switch (status) { 15374 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 15375 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 15376 return true; 15377 15378 default: 15379 // Nothing to do 15380 return false; 15381 } 15382 } 15383 15384 private static boolean isMultiArch(ApplicationInfo info) { 15385 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 15386 } 15387 15388 private static boolean isExternal(PackageParser.Package pkg) { 15389 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15390 } 15391 15392 private static boolean isExternal(PackageSetting ps) { 15393 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15394 } 15395 15396 private static boolean isEphemeral(PackageParser.Package pkg) { 15397 return pkg.applicationInfo.isEphemeralApp(); 15398 } 15399 15400 private static boolean isEphemeral(PackageSetting ps) { 15401 return ps.pkg != null && isEphemeral(ps.pkg); 15402 } 15403 15404 private static boolean isSystemApp(PackageParser.Package pkg) { 15405 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 15406 } 15407 15408 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 15409 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 15410 } 15411 15412 private static boolean hasDomainURLs(PackageParser.Package pkg) { 15413 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 15414 } 15415 15416 private static boolean isSystemApp(PackageSetting ps) { 15417 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 15418 } 15419 15420 private static boolean isUpdatedSystemApp(PackageSetting ps) { 15421 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 15422 } 15423 15424 private int packageFlagsToInstallFlags(PackageSetting ps) { 15425 int installFlags = 0; 15426 if (isEphemeral(ps)) { 15427 installFlags |= PackageManager.INSTALL_EPHEMERAL; 15428 } 15429 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 15430 // This existing package was an external ASEC install when we have 15431 // the external flag without a UUID 15432 installFlags |= PackageManager.INSTALL_EXTERNAL; 15433 } 15434 if (ps.isForwardLocked()) { 15435 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 15436 } 15437 return installFlags; 15438 } 15439 15440 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 15441 if (isExternal(pkg)) { 15442 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15443 return StorageManager.UUID_PRIMARY_PHYSICAL; 15444 } else { 15445 return pkg.volumeUuid; 15446 } 15447 } else { 15448 return StorageManager.UUID_PRIVATE_INTERNAL; 15449 } 15450 } 15451 15452 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 15453 if (isExternal(pkg)) { 15454 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15455 return mSettings.getExternalVersion(); 15456 } else { 15457 return mSettings.findOrCreateVersion(pkg.volumeUuid); 15458 } 15459 } else { 15460 return mSettings.getInternalVersion(); 15461 } 15462 } 15463 15464 private void deleteTempPackageFiles() { 15465 final FilenameFilter filter = new FilenameFilter() { 15466 public boolean accept(File dir, String name) { 15467 return name.startsWith("vmdl") && name.endsWith(".tmp"); 15468 } 15469 }; 15470 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 15471 file.delete(); 15472 } 15473 } 15474 15475 @Override 15476 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 15477 int flags) { 15478 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 15479 flags); 15480 } 15481 15482 @Override 15483 public void deletePackage(final String packageName, 15484 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 15485 mContext.enforceCallingOrSelfPermission( 15486 android.Manifest.permission.DELETE_PACKAGES, null); 15487 Preconditions.checkNotNull(packageName); 15488 Preconditions.checkNotNull(observer); 15489 final int uid = Binder.getCallingUid(); 15490 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 15491 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 15492 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 15493 mContext.enforceCallingOrSelfPermission( 15494 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 15495 "deletePackage for user " + userId); 15496 } 15497 15498 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 15499 try { 15500 observer.onPackageDeleted(packageName, 15501 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 15502 } catch (RemoteException re) { 15503 } 15504 return; 15505 } 15506 15507 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 15508 try { 15509 observer.onPackageDeleted(packageName, 15510 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 15511 } catch (RemoteException re) { 15512 } 15513 return; 15514 } 15515 15516 if (DEBUG_REMOVE) { 15517 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 15518 + " deleteAllUsers: " + deleteAllUsers ); 15519 } 15520 // Queue up an async operation since the package deletion may take a little while. 15521 mHandler.post(new Runnable() { 15522 public void run() { 15523 mHandler.removeCallbacks(this); 15524 int returnCode; 15525 if (!deleteAllUsers) { 15526 returnCode = deletePackageX(packageName, userId, deleteFlags); 15527 } else { 15528 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 15529 // If nobody is blocking uninstall, proceed with delete for all users 15530 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 15531 returnCode = deletePackageX(packageName, userId, deleteFlags); 15532 } else { 15533 // Otherwise uninstall individually for users with blockUninstalls=false 15534 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 15535 for (int userId : users) { 15536 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 15537 returnCode = deletePackageX(packageName, userId, userFlags); 15538 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 15539 Slog.w(TAG, "Package delete failed for user " + userId 15540 + ", returnCode " + returnCode); 15541 } 15542 } 15543 } 15544 // The app has only been marked uninstalled for certain users. 15545 // We still need to report that delete was blocked 15546 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 15547 } 15548 } 15549 try { 15550 observer.onPackageDeleted(packageName, returnCode, null); 15551 } catch (RemoteException e) { 15552 Log.i(TAG, "Observer no longer exists."); 15553 } //end catch 15554 } //end run 15555 }); 15556 } 15557 15558 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 15559 int[] result = EMPTY_INT_ARRAY; 15560 for (int userId : userIds) { 15561 if (getBlockUninstallForUser(packageName, userId)) { 15562 result = ArrayUtils.appendInt(result, userId); 15563 } 15564 } 15565 return result; 15566 } 15567 15568 @Override 15569 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 15570 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 15571 } 15572 15573 private boolean isPackageDeviceAdmin(String packageName, int userId) { 15574 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 15575 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 15576 try { 15577 if (dpm != null) { 15578 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 15579 /* callingUserOnly =*/ false); 15580 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 15581 : deviceOwnerComponentName.getPackageName(); 15582 // Does the package contains the device owner? 15583 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 15584 // this check is probably not needed, since DO should be registered as a device 15585 // admin on some user too. (Original bug for this: b/17657954) 15586 if (packageName.equals(deviceOwnerPackageName)) { 15587 return true; 15588 } 15589 // Does it contain a device admin for any user? 15590 int[] users; 15591 if (userId == UserHandle.USER_ALL) { 15592 users = sUserManager.getUserIds(); 15593 } else { 15594 users = new int[]{userId}; 15595 } 15596 for (int i = 0; i < users.length; ++i) { 15597 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 15598 return true; 15599 } 15600 } 15601 } 15602 } catch (RemoteException e) { 15603 } 15604 return false; 15605 } 15606 15607 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 15608 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 15609 } 15610 15611 /** 15612 * This method is an internal method that could be get invoked either 15613 * to delete an installed package or to clean up a failed installation. 15614 * After deleting an installed package, a broadcast is sent to notify any 15615 * listeners that the package has been removed. For cleaning up a failed 15616 * installation, the broadcast is not necessary since the package's 15617 * installation wouldn't have sent the initial broadcast either 15618 * The key steps in deleting a package are 15619 * deleting the package information in internal structures like mPackages, 15620 * deleting the packages base directories through installd 15621 * updating mSettings to reflect current status 15622 * persisting settings for later use 15623 * sending a broadcast if necessary 15624 */ 15625 private int deletePackageX(String packageName, int userId, int deleteFlags) { 15626 final PackageRemovedInfo info = new PackageRemovedInfo(); 15627 final boolean res; 15628 15629 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 15630 ? UserHandle.USER_ALL : userId; 15631 15632 if (isPackageDeviceAdmin(packageName, removeUser)) { 15633 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 15634 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 15635 } 15636 15637 PackageSetting uninstalledPs = null; 15638 15639 // for the uninstall-updates case and restricted profiles, remember the per- 15640 // user handle installed state 15641 int[] allUsers; 15642 synchronized (mPackages) { 15643 uninstalledPs = mSettings.mPackages.get(packageName); 15644 if (uninstalledPs == null) { 15645 Slog.w(TAG, "Not removing non-existent package " + packageName); 15646 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15647 } 15648 allUsers = sUserManager.getUserIds(); 15649 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 15650 } 15651 15652 final int freezeUser; 15653 if (isUpdatedSystemApp(uninstalledPs) 15654 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) { 15655 // We're downgrading a system app, which will apply to all users, so 15656 // freeze them all during the downgrade 15657 freezeUser = UserHandle.USER_ALL; 15658 } else { 15659 freezeUser = removeUser; 15660 } 15661 15662 synchronized (mInstallLock) { 15663 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 15664 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser, 15665 deleteFlags, "deletePackageX")) { 15666 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers, 15667 deleteFlags | REMOVE_CHATTY, info, true, null); 15668 } 15669 synchronized (mPackages) { 15670 if (res) { 15671 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 15672 } 15673 } 15674 } 15675 15676 if (res) { 15677 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 15678 info.sendPackageRemovedBroadcasts(killApp); 15679 info.sendSystemPackageUpdatedBroadcasts(); 15680 info.sendSystemPackageAppearedBroadcasts(); 15681 } 15682 // Force a gc here. 15683 Runtime.getRuntime().gc(); 15684 // Delete the resources here after sending the broadcast to let 15685 // other processes clean up before deleting resources. 15686 if (info.args != null) { 15687 synchronized (mInstallLock) { 15688 info.args.doPostDeleteLI(true); 15689 } 15690 } 15691 15692 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15693 } 15694 15695 class PackageRemovedInfo { 15696 String removedPackage; 15697 int uid = -1; 15698 int removedAppId = -1; 15699 int[] origUsers; 15700 int[] removedUsers = null; 15701 boolean isRemovedPackageSystemUpdate = false; 15702 boolean isUpdate; 15703 boolean dataRemoved; 15704 boolean removedForAllUsers; 15705 // Clean up resources deleted packages. 15706 InstallArgs args = null; 15707 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 15708 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 15709 15710 void sendPackageRemovedBroadcasts(boolean killApp) { 15711 sendPackageRemovedBroadcastInternal(killApp); 15712 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 15713 for (int i = 0; i < childCount; i++) { 15714 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15715 childInfo.sendPackageRemovedBroadcastInternal(killApp); 15716 } 15717 } 15718 15719 void sendSystemPackageUpdatedBroadcasts() { 15720 if (isRemovedPackageSystemUpdate) { 15721 sendSystemPackageUpdatedBroadcastsInternal(); 15722 final int childCount = (removedChildPackages != null) 15723 ? removedChildPackages.size() : 0; 15724 for (int i = 0; i < childCount; i++) { 15725 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15726 if (childInfo.isRemovedPackageSystemUpdate) { 15727 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 15728 } 15729 } 15730 } 15731 } 15732 15733 void sendSystemPackageAppearedBroadcasts() { 15734 final int packageCount = (appearedChildPackages != null) 15735 ? appearedChildPackages.size() : 0; 15736 for (int i = 0; i < packageCount; i++) { 15737 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 15738 for (int userId : installedInfo.newUsers) { 15739 sendPackageAddedForUser(installedInfo.name, true, 15740 UserHandle.getAppId(installedInfo.uid), userId); 15741 } 15742 } 15743 } 15744 15745 private void sendSystemPackageUpdatedBroadcastsInternal() { 15746 Bundle extras = new Bundle(2); 15747 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15748 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15749 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 15750 extras, 0, null, null, null); 15751 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 15752 extras, 0, null, null, null); 15753 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 15754 null, 0, removedPackage, null, null); 15755 } 15756 15757 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 15758 Bundle extras = new Bundle(2); 15759 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15760 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 15761 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 15762 if (isUpdate || isRemovedPackageSystemUpdate) { 15763 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15764 } 15765 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 15766 if (removedPackage != null) { 15767 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 15768 extras, 0, null, null, removedUsers); 15769 if (dataRemoved && !isRemovedPackageSystemUpdate) { 15770 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 15771 removedPackage, extras, 0, null, null, removedUsers); 15772 } 15773 } 15774 if (removedAppId >= 0) { 15775 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 15776 removedUsers); 15777 } 15778 } 15779 } 15780 15781 /* 15782 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 15783 * flag is not set, the data directory is removed as well. 15784 * make sure this flag is set for partially installed apps. If not its meaningless to 15785 * delete a partially installed application. 15786 */ 15787 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 15788 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 15789 String packageName = ps.name; 15790 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 15791 // Retrieve object to delete permissions for shared user later on 15792 final PackageParser.Package deletedPkg; 15793 final PackageSetting deletedPs; 15794 // reader 15795 synchronized (mPackages) { 15796 deletedPkg = mPackages.get(packageName); 15797 deletedPs = mSettings.mPackages.get(packageName); 15798 if (outInfo != null) { 15799 outInfo.removedPackage = packageName; 15800 outInfo.removedUsers = deletedPs != null 15801 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 15802 : null; 15803 } 15804 } 15805 15806 removePackageLI(ps, (flags & REMOVE_CHATTY) != 0); 15807 15808 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 15809 final PackageParser.Package resolvedPkg; 15810 if (deletedPkg != null) { 15811 resolvedPkg = deletedPkg; 15812 } else { 15813 // We don't have a parsed package when it lives on an ejected 15814 // adopted storage device, so fake something together 15815 resolvedPkg = new PackageParser.Package(ps.name); 15816 resolvedPkg.setVolumeUuid(ps.volumeUuid); 15817 } 15818 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 15819 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15820 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 15821 if (outInfo != null) { 15822 outInfo.dataRemoved = true; 15823 } 15824 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 15825 } 15826 15827 // writer 15828 synchronized (mPackages) { 15829 if (deletedPs != null) { 15830 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 15831 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 15832 clearDefaultBrowserIfNeeded(packageName); 15833 if (outInfo != null) { 15834 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 15835 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 15836 } 15837 updatePermissionsLPw(deletedPs.name, null, 0); 15838 if (deletedPs.sharedUser != null) { 15839 // Remove permissions associated with package. Since runtime 15840 // permissions are per user we have to kill the removed package 15841 // or packages running under the shared user of the removed 15842 // package if revoking the permissions requested only by the removed 15843 // package is successful and this causes a change in gids. 15844 for (int userId : UserManagerService.getInstance().getUserIds()) { 15845 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 15846 userId); 15847 if (userIdToKill == UserHandle.USER_ALL 15848 || userIdToKill >= UserHandle.USER_SYSTEM) { 15849 // If gids changed for this user, kill all affected packages. 15850 mHandler.post(new Runnable() { 15851 @Override 15852 public void run() { 15853 // This has to happen with no lock held. 15854 killApplication(deletedPs.name, deletedPs.appId, 15855 KILL_APP_REASON_GIDS_CHANGED); 15856 } 15857 }); 15858 break; 15859 } 15860 } 15861 } 15862 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 15863 } 15864 // make sure to preserve per-user disabled state if this removal was just 15865 // a downgrade of a system app to the factory package 15866 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 15867 if (DEBUG_REMOVE) { 15868 Slog.d(TAG, "Propagating install state across downgrade"); 15869 } 15870 for (int userId : allUserHandles) { 15871 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15872 if (DEBUG_REMOVE) { 15873 Slog.d(TAG, " user " + userId + " => " + installed); 15874 } 15875 ps.setInstalled(installed, userId); 15876 } 15877 } 15878 } 15879 // can downgrade to reader 15880 if (writeSettings) { 15881 // Save settings now 15882 mSettings.writeLPr(); 15883 } 15884 } 15885 if (outInfo != null) { 15886 // A user ID was deleted here. Go through all users and remove it 15887 // from KeyStore. 15888 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 15889 } 15890 } 15891 15892 static boolean locationIsPrivileged(File path) { 15893 try { 15894 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 15895 .getCanonicalPath(); 15896 return path.getCanonicalPath().startsWith(privilegedAppDir); 15897 } catch (IOException e) { 15898 Slog.e(TAG, "Unable to access code path " + path); 15899 } 15900 return false; 15901 } 15902 15903 /* 15904 * Tries to delete system package. 15905 */ 15906 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 15907 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 15908 boolean writeSettings) { 15909 if (deletedPs.parentPackageName != null) { 15910 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 15911 return false; 15912 } 15913 15914 final boolean applyUserRestrictions 15915 = (allUserHandles != null) && (outInfo.origUsers != null); 15916 final PackageSetting disabledPs; 15917 // Confirm if the system package has been updated 15918 // An updated system app can be deleted. This will also have to restore 15919 // the system pkg from system partition 15920 // reader 15921 synchronized (mPackages) { 15922 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 15923 } 15924 15925 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 15926 + " disabledPs=" + disabledPs); 15927 15928 if (disabledPs == null) { 15929 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 15930 return false; 15931 } else if (DEBUG_REMOVE) { 15932 Slog.d(TAG, "Deleting system pkg from data partition"); 15933 } 15934 15935 if (DEBUG_REMOVE) { 15936 if (applyUserRestrictions) { 15937 Slog.d(TAG, "Remembering install states:"); 15938 for (int userId : allUserHandles) { 15939 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 15940 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 15941 } 15942 } 15943 } 15944 15945 // Delete the updated package 15946 outInfo.isRemovedPackageSystemUpdate = true; 15947 if (outInfo.removedChildPackages != null) { 15948 final int childCount = (deletedPs.childPackageNames != null) 15949 ? deletedPs.childPackageNames.size() : 0; 15950 for (int i = 0; i < childCount; i++) { 15951 String childPackageName = deletedPs.childPackageNames.get(i); 15952 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 15953 .contains(childPackageName)) { 15954 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15955 childPackageName); 15956 if (childInfo != null) { 15957 childInfo.isRemovedPackageSystemUpdate = true; 15958 } 15959 } 15960 } 15961 } 15962 15963 if (disabledPs.versionCode < deletedPs.versionCode) { 15964 // Delete data for downgrades 15965 flags &= ~PackageManager.DELETE_KEEP_DATA; 15966 } else { 15967 // Preserve data by setting flag 15968 flags |= PackageManager.DELETE_KEEP_DATA; 15969 } 15970 15971 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 15972 outInfo, writeSettings, disabledPs.pkg); 15973 if (!ret) { 15974 return false; 15975 } 15976 15977 // writer 15978 synchronized (mPackages) { 15979 // Reinstate the old system package 15980 enableSystemPackageLPw(disabledPs.pkg); 15981 // Remove any native libraries from the upgraded package. 15982 removeNativeBinariesLI(deletedPs); 15983 } 15984 15985 // Install the system package 15986 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 15987 int parseFlags = mDefParseFlags 15988 | PackageParser.PARSE_MUST_BE_APK 15989 | PackageParser.PARSE_IS_SYSTEM 15990 | PackageParser.PARSE_IS_SYSTEM_DIR; 15991 if (locationIsPrivileged(disabledPs.codePath)) { 15992 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 15993 } 15994 15995 final PackageParser.Package newPkg; 15996 try { 15997 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 15998 } catch (PackageManagerException e) { 15999 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 16000 + e.getMessage()); 16001 return false; 16002 } 16003 16004 prepareAppDataAfterInstallLIF(newPkg); 16005 16006 // writer 16007 synchronized (mPackages) { 16008 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 16009 16010 // Propagate the permissions state as we do not want to drop on the floor 16011 // runtime permissions. The update permissions method below will take 16012 // care of removing obsolete permissions and grant install permissions. 16013 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 16014 updatePermissionsLPw(newPkg.packageName, newPkg, 16015 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 16016 16017 if (applyUserRestrictions) { 16018 if (DEBUG_REMOVE) { 16019 Slog.d(TAG, "Propagating install state across reinstall"); 16020 } 16021 for (int userId : allUserHandles) { 16022 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 16023 if (DEBUG_REMOVE) { 16024 Slog.d(TAG, " user " + userId + " => " + installed); 16025 } 16026 ps.setInstalled(installed, userId); 16027 16028 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 16029 } 16030 // Regardless of writeSettings we need to ensure that this restriction 16031 // state propagation is persisted 16032 mSettings.writeAllUsersPackageRestrictionsLPr(); 16033 } 16034 // can downgrade to reader here 16035 if (writeSettings) { 16036 mSettings.writeLPr(); 16037 } 16038 } 16039 return true; 16040 } 16041 16042 private boolean deleteInstalledPackageLIF(PackageSetting ps, 16043 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 16044 PackageRemovedInfo outInfo, boolean writeSettings, 16045 PackageParser.Package replacingPackage) { 16046 synchronized (mPackages) { 16047 if (outInfo != null) { 16048 outInfo.uid = ps.appId; 16049 } 16050 16051 if (outInfo != null && outInfo.removedChildPackages != null) { 16052 final int childCount = (ps.childPackageNames != null) 16053 ? ps.childPackageNames.size() : 0; 16054 for (int i = 0; i < childCount; i++) { 16055 String childPackageName = ps.childPackageNames.get(i); 16056 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 16057 if (childPs == null) { 16058 return false; 16059 } 16060 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 16061 childPackageName); 16062 if (childInfo != null) { 16063 childInfo.uid = childPs.appId; 16064 } 16065 } 16066 } 16067 } 16068 16069 // Delete package data from internal structures and also remove data if flag is set 16070 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 16071 16072 // Delete the child packages data 16073 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 16074 for (int i = 0; i < childCount; i++) { 16075 PackageSetting childPs; 16076 synchronized (mPackages) { 16077 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 16078 } 16079 if (childPs != null) { 16080 PackageRemovedInfo childOutInfo = (outInfo != null 16081 && outInfo.removedChildPackages != null) 16082 ? outInfo.removedChildPackages.get(childPs.name) : null; 16083 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 16084 && (replacingPackage != null 16085 && !replacingPackage.hasChildPackage(childPs.name)) 16086 ? flags & ~DELETE_KEEP_DATA : flags; 16087 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 16088 deleteFlags, writeSettings); 16089 } 16090 } 16091 16092 // Delete application code and resources only for parent packages 16093 if (ps.parentPackageName == null) { 16094 if (deleteCodeAndResources && (outInfo != null)) { 16095 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 16096 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 16097 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 16098 } 16099 } 16100 16101 return true; 16102 } 16103 16104 @Override 16105 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 16106 int userId) { 16107 mContext.enforceCallingOrSelfPermission( 16108 android.Manifest.permission.DELETE_PACKAGES, null); 16109 synchronized (mPackages) { 16110 PackageSetting ps = mSettings.mPackages.get(packageName); 16111 if (ps == null) { 16112 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 16113 return false; 16114 } 16115 if (!ps.getInstalled(userId)) { 16116 // Can't block uninstall for an app that is not installed or enabled. 16117 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 16118 return false; 16119 } 16120 ps.setBlockUninstall(blockUninstall, userId); 16121 mSettings.writePackageRestrictionsLPr(userId); 16122 } 16123 return true; 16124 } 16125 16126 @Override 16127 public boolean getBlockUninstallForUser(String packageName, int userId) { 16128 synchronized (mPackages) { 16129 PackageSetting ps = mSettings.mPackages.get(packageName); 16130 if (ps == null) { 16131 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 16132 return false; 16133 } 16134 return ps.getBlockUninstall(userId); 16135 } 16136 } 16137 16138 @Override 16139 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 16140 int callingUid = Binder.getCallingUid(); 16141 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 16142 throw new SecurityException( 16143 "setRequiredForSystemUser can only be run by the system or root"); 16144 } 16145 synchronized (mPackages) { 16146 PackageSetting ps = mSettings.mPackages.get(packageName); 16147 if (ps == null) { 16148 Log.w(TAG, "Package doesn't exist: " + packageName); 16149 return false; 16150 } 16151 if (systemUserApp) { 16152 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 16153 } else { 16154 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 16155 } 16156 mSettings.writeLPr(); 16157 } 16158 return true; 16159 } 16160 16161 /* 16162 * This method handles package deletion in general 16163 */ 16164 private boolean deletePackageLIF(String packageName, UserHandle user, 16165 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 16166 PackageRemovedInfo outInfo, boolean writeSettings, 16167 PackageParser.Package replacingPackage) { 16168 if (packageName == null) { 16169 Slog.w(TAG, "Attempt to delete null packageName."); 16170 return false; 16171 } 16172 16173 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 16174 16175 PackageSetting ps; 16176 16177 synchronized (mPackages) { 16178 ps = mSettings.mPackages.get(packageName); 16179 if (ps == null) { 16180 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16181 return false; 16182 } 16183 16184 if (ps.parentPackageName != null && (!isSystemApp(ps) 16185 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 16186 if (DEBUG_REMOVE) { 16187 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 16188 + ((user == null) ? UserHandle.USER_ALL : user)); 16189 } 16190 final int removedUserId = (user != null) ? user.getIdentifier() 16191 : UserHandle.USER_ALL; 16192 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 16193 return false; 16194 } 16195 markPackageUninstalledForUserLPw(ps, user); 16196 scheduleWritePackageRestrictionsLocked(user); 16197 return true; 16198 } 16199 } 16200 16201 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 16202 && user.getIdentifier() != UserHandle.USER_ALL)) { 16203 // The caller is asking that the package only be deleted for a single 16204 // user. To do this, we just mark its uninstalled state and delete 16205 // its data. If this is a system app, we only allow this to happen if 16206 // they have set the special DELETE_SYSTEM_APP which requests different 16207 // semantics than normal for uninstalling system apps. 16208 markPackageUninstalledForUserLPw(ps, user); 16209 16210 if (!isSystemApp(ps)) { 16211 // Do not uninstall the APK if an app should be cached 16212 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 16213 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 16214 // Other user still have this package installed, so all 16215 // we need to do is clear this user's data and save that 16216 // it is uninstalled. 16217 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 16218 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16219 return false; 16220 } 16221 scheduleWritePackageRestrictionsLocked(user); 16222 return true; 16223 } else { 16224 // We need to set it back to 'installed' so the uninstall 16225 // broadcasts will be sent correctly. 16226 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 16227 ps.setInstalled(true, user.getIdentifier()); 16228 } 16229 } else { 16230 // This is a system app, so we assume that the 16231 // other users still have this package installed, so all 16232 // we need to do is clear this user's data and save that 16233 // it is uninstalled. 16234 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 16235 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16236 return false; 16237 } 16238 scheduleWritePackageRestrictionsLocked(user); 16239 return true; 16240 } 16241 } 16242 16243 // If we are deleting a composite package for all users, keep track 16244 // of result for each child. 16245 if (ps.childPackageNames != null && outInfo != null) { 16246 synchronized (mPackages) { 16247 final int childCount = ps.childPackageNames.size(); 16248 outInfo.removedChildPackages = new ArrayMap<>(childCount); 16249 for (int i = 0; i < childCount; i++) { 16250 String childPackageName = ps.childPackageNames.get(i); 16251 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 16252 childInfo.removedPackage = childPackageName; 16253 outInfo.removedChildPackages.put(childPackageName, childInfo); 16254 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 16255 if (childPs != null) { 16256 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 16257 } 16258 } 16259 } 16260 } 16261 16262 boolean ret = false; 16263 if (isSystemApp(ps)) { 16264 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 16265 // When an updated system application is deleted we delete the existing resources 16266 // as well and fall back to existing code in system partition 16267 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 16268 } else { 16269 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 16270 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 16271 outInfo, writeSettings, replacingPackage); 16272 } 16273 16274 // Take a note whether we deleted the package for all users 16275 if (outInfo != null) { 16276 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 16277 if (outInfo.removedChildPackages != null) { 16278 synchronized (mPackages) { 16279 final int childCount = outInfo.removedChildPackages.size(); 16280 for (int i = 0; i < childCount; i++) { 16281 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 16282 if (childInfo != null) { 16283 childInfo.removedForAllUsers = mPackages.get( 16284 childInfo.removedPackage) == null; 16285 } 16286 } 16287 } 16288 } 16289 // If we uninstalled an update to a system app there may be some 16290 // child packages that appeared as they are declared in the system 16291 // app but were not declared in the update. 16292 if (isSystemApp(ps)) { 16293 synchronized (mPackages) { 16294 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 16295 final int childCount = (updatedPs.childPackageNames != null) 16296 ? updatedPs.childPackageNames.size() : 0; 16297 for (int i = 0; i < childCount; i++) { 16298 String childPackageName = updatedPs.childPackageNames.get(i); 16299 if (outInfo.removedChildPackages == null 16300 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 16301 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 16302 if (childPs == null) { 16303 continue; 16304 } 16305 PackageInstalledInfo installRes = new PackageInstalledInfo(); 16306 installRes.name = childPackageName; 16307 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 16308 installRes.pkg = mPackages.get(childPackageName); 16309 installRes.uid = childPs.pkg.applicationInfo.uid; 16310 if (outInfo.appearedChildPackages == null) { 16311 outInfo.appearedChildPackages = new ArrayMap<>(); 16312 } 16313 outInfo.appearedChildPackages.put(childPackageName, installRes); 16314 } 16315 } 16316 } 16317 } 16318 } 16319 16320 return ret; 16321 } 16322 16323 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 16324 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 16325 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 16326 for (int nextUserId : userIds) { 16327 if (DEBUG_REMOVE) { 16328 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 16329 } 16330 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 16331 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 16332 false /*hidden*/, false /*suspended*/, null, null, null, 16333 false /*blockUninstall*/, 16334 ps.readUserState(nextUserId).domainVerificationStatus, 0); 16335 } 16336 } 16337 16338 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 16339 PackageRemovedInfo outInfo) { 16340 final PackageParser.Package pkg; 16341 synchronized (mPackages) { 16342 pkg = mPackages.get(ps.name); 16343 } 16344 16345 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 16346 : new int[] {userId}; 16347 for (int nextUserId : userIds) { 16348 if (DEBUG_REMOVE) { 16349 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 16350 + nextUserId); 16351 } 16352 16353 destroyAppDataLIF(pkg, userId, 16354 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16355 destroyAppProfilesLIF(pkg, userId); 16356 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 16357 schedulePackageCleaning(ps.name, nextUserId, false); 16358 synchronized (mPackages) { 16359 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 16360 scheduleWritePackageRestrictionsLocked(nextUserId); 16361 } 16362 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 16363 } 16364 } 16365 16366 if (outInfo != null) { 16367 outInfo.removedPackage = ps.name; 16368 outInfo.removedAppId = ps.appId; 16369 outInfo.removedUsers = userIds; 16370 } 16371 16372 return true; 16373 } 16374 16375 private final class ClearStorageConnection implements ServiceConnection { 16376 IMediaContainerService mContainerService; 16377 16378 @Override 16379 public void onServiceConnected(ComponentName name, IBinder service) { 16380 synchronized (this) { 16381 mContainerService = IMediaContainerService.Stub.asInterface(service); 16382 notifyAll(); 16383 } 16384 } 16385 16386 @Override 16387 public void onServiceDisconnected(ComponentName name) { 16388 } 16389 } 16390 16391 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 16392 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 16393 16394 final boolean mounted; 16395 if (Environment.isExternalStorageEmulated()) { 16396 mounted = true; 16397 } else { 16398 final String status = Environment.getExternalStorageState(); 16399 16400 mounted = status.equals(Environment.MEDIA_MOUNTED) 16401 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 16402 } 16403 16404 if (!mounted) { 16405 return; 16406 } 16407 16408 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 16409 int[] users; 16410 if (userId == UserHandle.USER_ALL) { 16411 users = sUserManager.getUserIds(); 16412 } else { 16413 users = new int[] { userId }; 16414 } 16415 final ClearStorageConnection conn = new ClearStorageConnection(); 16416 if (mContext.bindServiceAsUser( 16417 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 16418 try { 16419 for (int curUser : users) { 16420 long timeout = SystemClock.uptimeMillis() + 5000; 16421 synchronized (conn) { 16422 long now; 16423 while (conn.mContainerService == null && 16424 (now = SystemClock.uptimeMillis()) < timeout) { 16425 try { 16426 conn.wait(timeout - now); 16427 } catch (InterruptedException e) { 16428 } 16429 } 16430 } 16431 if (conn.mContainerService == null) { 16432 return; 16433 } 16434 16435 final UserEnvironment userEnv = new UserEnvironment(curUser); 16436 clearDirectory(conn.mContainerService, 16437 userEnv.buildExternalStorageAppCacheDirs(packageName)); 16438 if (allData) { 16439 clearDirectory(conn.mContainerService, 16440 userEnv.buildExternalStorageAppDataDirs(packageName)); 16441 clearDirectory(conn.mContainerService, 16442 userEnv.buildExternalStorageAppMediaDirs(packageName)); 16443 } 16444 } 16445 } finally { 16446 mContext.unbindService(conn); 16447 } 16448 } 16449 } 16450 16451 @Override 16452 public void clearApplicationProfileData(String packageName) { 16453 enforceSystemOrRoot("Only the system can clear all profile data"); 16454 16455 final PackageParser.Package pkg; 16456 synchronized (mPackages) { 16457 pkg = mPackages.get(packageName); 16458 } 16459 16460 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 16461 synchronized (mInstallLock) { 16462 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 16463 destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL, 16464 true /* removeBaseMarker */); 16465 } 16466 } 16467 } 16468 16469 @Override 16470 public void clearApplicationUserData(final String packageName, 16471 final IPackageDataObserver observer, final int userId) { 16472 mContext.enforceCallingOrSelfPermission( 16473 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 16474 16475 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16476 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 16477 16478 if (mProtectedPackages.isPackageDataProtected(userId, packageName)) { 16479 throw new SecurityException("Cannot clear data for a protected package: " 16480 + packageName); 16481 } 16482 // Queue up an async operation since the package deletion may take a little while. 16483 mHandler.post(new Runnable() { 16484 public void run() { 16485 mHandler.removeCallbacks(this); 16486 final boolean succeeded; 16487 try (PackageFreezer freezer = freezePackage(packageName, 16488 "clearApplicationUserData")) { 16489 synchronized (mInstallLock) { 16490 succeeded = clearApplicationUserDataLIF(packageName, userId); 16491 } 16492 clearExternalStorageDataSync(packageName, userId, true); 16493 } 16494 if (succeeded) { 16495 // invoke DeviceStorageMonitor's update method to clear any notifications 16496 DeviceStorageMonitorInternal dsm = LocalServices 16497 .getService(DeviceStorageMonitorInternal.class); 16498 if (dsm != null) { 16499 dsm.checkMemory(); 16500 } 16501 } 16502 if(observer != null) { 16503 try { 16504 observer.onRemoveCompleted(packageName, succeeded); 16505 } catch (RemoteException e) { 16506 Log.i(TAG, "Observer no longer exists."); 16507 } 16508 } //end if observer 16509 } //end run 16510 }); 16511 } 16512 16513 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 16514 if (packageName == null) { 16515 Slog.w(TAG, "Attempt to delete null packageName."); 16516 return false; 16517 } 16518 16519 // Try finding details about the requested package 16520 PackageParser.Package pkg; 16521 synchronized (mPackages) { 16522 pkg = mPackages.get(packageName); 16523 if (pkg == null) { 16524 final PackageSetting ps = mSettings.mPackages.get(packageName); 16525 if (ps != null) { 16526 pkg = ps.pkg; 16527 } 16528 } 16529 16530 if (pkg == null) { 16531 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16532 return false; 16533 } 16534 16535 PackageSetting ps = (PackageSetting) pkg.mExtras; 16536 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16537 } 16538 16539 clearAppDataLIF(pkg, userId, 16540 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16541 16542 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16543 removeKeystoreDataIfNeeded(userId, appId); 16544 16545 UserManagerInternal umInternal = getUserManagerInternal(); 16546 final int flags; 16547 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 16548 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 16549 } else if (umInternal.isUserRunning(userId)) { 16550 flags = StorageManager.FLAG_STORAGE_DE; 16551 } else { 16552 flags = 0; 16553 } 16554 prepareAppDataContentsLIF(pkg, userId, flags); 16555 16556 return true; 16557 } 16558 16559 /** 16560 * Reverts user permission state changes (permissions and flags) in 16561 * all packages for a given user. 16562 * 16563 * @param userId The device user for which to do a reset. 16564 */ 16565 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 16566 final int packageCount = mPackages.size(); 16567 for (int i = 0; i < packageCount; i++) { 16568 PackageParser.Package pkg = mPackages.valueAt(i); 16569 PackageSetting ps = (PackageSetting) pkg.mExtras; 16570 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16571 } 16572 } 16573 16574 private void resetNetworkPolicies(int userId) { 16575 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 16576 } 16577 16578 /** 16579 * Reverts user permission state changes (permissions and flags). 16580 * 16581 * @param ps The package for which to reset. 16582 * @param userId The device user for which to do a reset. 16583 */ 16584 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 16585 final PackageSetting ps, final int userId) { 16586 if (ps.pkg == null) { 16587 return; 16588 } 16589 16590 // These are flags that can change base on user actions. 16591 final int userSettableMask = FLAG_PERMISSION_USER_SET 16592 | FLAG_PERMISSION_USER_FIXED 16593 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 16594 | FLAG_PERMISSION_REVIEW_REQUIRED; 16595 16596 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 16597 | FLAG_PERMISSION_POLICY_FIXED; 16598 16599 boolean writeInstallPermissions = false; 16600 boolean writeRuntimePermissions = false; 16601 16602 final int permissionCount = ps.pkg.requestedPermissions.size(); 16603 for (int i = 0; i < permissionCount; i++) { 16604 String permission = ps.pkg.requestedPermissions.get(i); 16605 16606 BasePermission bp = mSettings.mPermissions.get(permission); 16607 if (bp == null) { 16608 continue; 16609 } 16610 16611 // If shared user we just reset the state to which only this app contributed. 16612 if (ps.sharedUser != null) { 16613 boolean used = false; 16614 final int packageCount = ps.sharedUser.packages.size(); 16615 for (int j = 0; j < packageCount; j++) { 16616 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 16617 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 16618 && pkg.pkg.requestedPermissions.contains(permission)) { 16619 used = true; 16620 break; 16621 } 16622 } 16623 if (used) { 16624 continue; 16625 } 16626 } 16627 16628 PermissionsState permissionsState = ps.getPermissionsState(); 16629 16630 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 16631 16632 // Always clear the user settable flags. 16633 final boolean hasInstallState = permissionsState.getInstallPermissionState( 16634 bp.name) != null; 16635 // If permission review is enabled and this is a legacy app, mark the 16636 // permission as requiring a review as this is the initial state. 16637 int flags = 0; 16638 if (Build.PERMISSIONS_REVIEW_REQUIRED 16639 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 16640 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 16641 } 16642 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 16643 if (hasInstallState) { 16644 writeInstallPermissions = true; 16645 } else { 16646 writeRuntimePermissions = true; 16647 } 16648 } 16649 16650 // Below is only runtime permission handling. 16651 if (!bp.isRuntime()) { 16652 continue; 16653 } 16654 16655 // Never clobber system or policy. 16656 if ((oldFlags & policyOrSystemFlags) != 0) { 16657 continue; 16658 } 16659 16660 // If this permission was granted by default, make sure it is. 16661 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 16662 if (permissionsState.grantRuntimePermission(bp, userId) 16663 != PERMISSION_OPERATION_FAILURE) { 16664 writeRuntimePermissions = true; 16665 } 16666 // If permission review is enabled the permissions for a legacy apps 16667 // are represented as constantly granted runtime ones, so don't revoke. 16668 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 16669 // Otherwise, reset the permission. 16670 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 16671 switch (revokeResult) { 16672 case PERMISSION_OPERATION_SUCCESS: 16673 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 16674 writeRuntimePermissions = true; 16675 final int appId = ps.appId; 16676 mHandler.post(new Runnable() { 16677 @Override 16678 public void run() { 16679 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 16680 } 16681 }); 16682 } break; 16683 } 16684 } 16685 } 16686 16687 // Synchronously write as we are taking permissions away. 16688 if (writeRuntimePermissions) { 16689 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 16690 } 16691 16692 // Synchronously write as we are taking permissions away. 16693 if (writeInstallPermissions) { 16694 mSettings.writeLPr(); 16695 } 16696 } 16697 16698 /** 16699 * Remove entries from the keystore daemon. Will only remove it if the 16700 * {@code appId} is valid. 16701 */ 16702 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 16703 if (appId < 0) { 16704 return; 16705 } 16706 16707 final KeyStore keyStore = KeyStore.getInstance(); 16708 if (keyStore != null) { 16709 if (userId == UserHandle.USER_ALL) { 16710 for (final int individual : sUserManager.getUserIds()) { 16711 keyStore.clearUid(UserHandle.getUid(individual, appId)); 16712 } 16713 } else { 16714 keyStore.clearUid(UserHandle.getUid(userId, appId)); 16715 } 16716 } else { 16717 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 16718 } 16719 } 16720 16721 @Override 16722 public void deleteApplicationCacheFiles(final String packageName, 16723 final IPackageDataObserver observer) { 16724 final int userId = UserHandle.getCallingUserId(); 16725 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 16726 } 16727 16728 @Override 16729 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 16730 final IPackageDataObserver observer) { 16731 mContext.enforceCallingOrSelfPermission( 16732 android.Manifest.permission.DELETE_CACHE_FILES, null); 16733 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16734 /* requireFullPermission= */ true, /* checkShell= */ false, 16735 "delete application cache files"); 16736 16737 final PackageParser.Package pkg; 16738 synchronized (mPackages) { 16739 pkg = mPackages.get(packageName); 16740 } 16741 16742 // Queue up an async operation since the package deletion may take a little while. 16743 mHandler.post(new Runnable() { 16744 public void run() { 16745 synchronized (mInstallLock) { 16746 final int flags = StorageManager.FLAG_STORAGE_DE 16747 | StorageManager.FLAG_STORAGE_CE; 16748 // We're only clearing cache files, so we don't care if the 16749 // app is unfrozen and still able to run 16750 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 16751 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16752 } 16753 clearExternalStorageDataSync(packageName, userId, false); 16754 if (observer != null) { 16755 try { 16756 observer.onRemoveCompleted(packageName, true); 16757 } catch (RemoteException e) { 16758 Log.i(TAG, "Observer no longer exists."); 16759 } 16760 } 16761 } 16762 }); 16763 } 16764 16765 @Override 16766 public void getPackageSizeInfo(final String packageName, int userHandle, 16767 final IPackageStatsObserver observer) { 16768 mContext.enforceCallingOrSelfPermission( 16769 android.Manifest.permission.GET_PACKAGE_SIZE, null); 16770 if (packageName == null) { 16771 throw new IllegalArgumentException("Attempt to get size of null packageName"); 16772 } 16773 16774 PackageStats stats = new PackageStats(packageName, userHandle); 16775 16776 /* 16777 * Queue up an async operation since the package measurement may take a 16778 * little while. 16779 */ 16780 Message msg = mHandler.obtainMessage(INIT_COPY); 16781 msg.obj = new MeasureParams(stats, observer); 16782 mHandler.sendMessage(msg); 16783 } 16784 16785 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 16786 final PackageSetting ps; 16787 synchronized (mPackages) { 16788 ps = mSettings.mPackages.get(packageName); 16789 if (ps == null) { 16790 Slog.w(TAG, "Failed to find settings for " + packageName); 16791 return false; 16792 } 16793 } 16794 try { 16795 mInstaller.getAppSize(ps.volumeUuid, packageName, userId, 16796 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 16797 ps.getCeDataInode(userId), ps.codePathString, stats); 16798 } catch (InstallerException e) { 16799 Slog.w(TAG, String.valueOf(e)); 16800 return false; 16801 } 16802 16803 // For now, ignore code size of packages on system partition 16804 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 16805 stats.codeSize = 0; 16806 } 16807 16808 return true; 16809 } 16810 16811 private int getUidTargetSdkVersionLockedLPr(int uid) { 16812 Object obj = mSettings.getUserIdLPr(uid); 16813 if (obj instanceof SharedUserSetting) { 16814 final SharedUserSetting sus = (SharedUserSetting) obj; 16815 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 16816 final Iterator<PackageSetting> it = sus.packages.iterator(); 16817 while (it.hasNext()) { 16818 final PackageSetting ps = it.next(); 16819 if (ps.pkg != null) { 16820 int v = ps.pkg.applicationInfo.targetSdkVersion; 16821 if (v < vers) vers = v; 16822 } 16823 } 16824 return vers; 16825 } else if (obj instanceof PackageSetting) { 16826 final PackageSetting ps = (PackageSetting) obj; 16827 if (ps.pkg != null) { 16828 return ps.pkg.applicationInfo.targetSdkVersion; 16829 } 16830 } 16831 return Build.VERSION_CODES.CUR_DEVELOPMENT; 16832 } 16833 16834 @Override 16835 public void addPreferredActivity(IntentFilter filter, int match, 16836 ComponentName[] set, ComponentName activity, int userId) { 16837 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16838 "Adding preferred"); 16839 } 16840 16841 private void addPreferredActivityInternal(IntentFilter filter, int match, 16842 ComponentName[] set, ComponentName activity, boolean always, int userId, 16843 String opname) { 16844 // writer 16845 int callingUid = Binder.getCallingUid(); 16846 enforceCrossUserPermission(callingUid, userId, 16847 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 16848 if (filter.countActions() == 0) { 16849 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16850 return; 16851 } 16852 synchronized (mPackages) { 16853 if (mContext.checkCallingOrSelfPermission( 16854 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16855 != PackageManager.PERMISSION_GRANTED) { 16856 if (getUidTargetSdkVersionLockedLPr(callingUid) 16857 < Build.VERSION_CODES.FROYO) { 16858 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 16859 + callingUid); 16860 return; 16861 } 16862 mContext.enforceCallingOrSelfPermission( 16863 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16864 } 16865 16866 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 16867 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 16868 + userId + ":"); 16869 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16870 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 16871 scheduleWritePackageRestrictionsLocked(userId); 16872 } 16873 } 16874 16875 @Override 16876 public void replacePreferredActivity(IntentFilter filter, int match, 16877 ComponentName[] set, ComponentName activity, int userId) { 16878 if (filter.countActions() != 1) { 16879 throw new IllegalArgumentException( 16880 "replacePreferredActivity expects filter to have only 1 action."); 16881 } 16882 if (filter.countDataAuthorities() != 0 16883 || filter.countDataPaths() != 0 16884 || filter.countDataSchemes() > 1 16885 || filter.countDataTypes() != 0) { 16886 throw new IllegalArgumentException( 16887 "replacePreferredActivity expects filter to have no data authorities, " + 16888 "paths, or types; and at most one scheme."); 16889 } 16890 16891 final int callingUid = Binder.getCallingUid(); 16892 enforceCrossUserPermission(callingUid, userId, 16893 true /* requireFullPermission */, false /* checkShell */, 16894 "replace preferred activity"); 16895 synchronized (mPackages) { 16896 if (mContext.checkCallingOrSelfPermission( 16897 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16898 != PackageManager.PERMISSION_GRANTED) { 16899 if (getUidTargetSdkVersionLockedLPr(callingUid) 16900 < Build.VERSION_CODES.FROYO) { 16901 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 16902 + Binder.getCallingUid()); 16903 return; 16904 } 16905 mContext.enforceCallingOrSelfPermission( 16906 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16907 } 16908 16909 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16910 if (pir != null) { 16911 // Get all of the existing entries that exactly match this filter. 16912 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 16913 if (existing != null && existing.size() == 1) { 16914 PreferredActivity cur = existing.get(0); 16915 if (DEBUG_PREFERRED) { 16916 Slog.i(TAG, "Checking replace of preferred:"); 16917 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16918 if (!cur.mPref.mAlways) { 16919 Slog.i(TAG, " -- CUR; not mAlways!"); 16920 } else { 16921 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 16922 Slog.i(TAG, " -- CUR: mSet=" 16923 + Arrays.toString(cur.mPref.mSetComponents)); 16924 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 16925 Slog.i(TAG, " -- NEW: mMatch=" 16926 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 16927 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 16928 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 16929 } 16930 } 16931 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 16932 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 16933 && cur.mPref.sameSet(set)) { 16934 // Setting the preferred activity to what it happens to be already 16935 if (DEBUG_PREFERRED) { 16936 Slog.i(TAG, "Replacing with same preferred activity " 16937 + cur.mPref.mShortComponent + " for user " 16938 + userId + ":"); 16939 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16940 } 16941 return; 16942 } 16943 } 16944 16945 if (existing != null) { 16946 if (DEBUG_PREFERRED) { 16947 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 16948 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16949 } 16950 for (int i = 0; i < existing.size(); i++) { 16951 PreferredActivity pa = existing.get(i); 16952 if (DEBUG_PREFERRED) { 16953 Slog.i(TAG, "Removing existing preferred activity " 16954 + pa.mPref.mComponent + ":"); 16955 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 16956 } 16957 pir.removeFilter(pa); 16958 } 16959 } 16960 } 16961 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16962 "Replacing preferred"); 16963 } 16964 } 16965 16966 @Override 16967 public void clearPackagePreferredActivities(String packageName) { 16968 final int uid = Binder.getCallingUid(); 16969 // writer 16970 synchronized (mPackages) { 16971 PackageParser.Package pkg = mPackages.get(packageName); 16972 if (pkg == null || pkg.applicationInfo.uid != uid) { 16973 if (mContext.checkCallingOrSelfPermission( 16974 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16975 != PackageManager.PERMISSION_GRANTED) { 16976 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 16977 < Build.VERSION_CODES.FROYO) { 16978 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 16979 + Binder.getCallingUid()); 16980 return; 16981 } 16982 mContext.enforceCallingOrSelfPermission( 16983 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16984 } 16985 } 16986 16987 int user = UserHandle.getCallingUserId(); 16988 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 16989 scheduleWritePackageRestrictionsLocked(user); 16990 } 16991 } 16992 } 16993 16994 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16995 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 16996 ArrayList<PreferredActivity> removed = null; 16997 boolean changed = false; 16998 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16999 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 17000 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17001 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 17002 continue; 17003 } 17004 Iterator<PreferredActivity> it = pir.filterIterator(); 17005 while (it.hasNext()) { 17006 PreferredActivity pa = it.next(); 17007 // Mark entry for removal only if it matches the package name 17008 // and the entry is of type "always". 17009 if (packageName == null || 17010 (pa.mPref.mComponent.getPackageName().equals(packageName) 17011 && pa.mPref.mAlways)) { 17012 if (removed == null) { 17013 removed = new ArrayList<PreferredActivity>(); 17014 } 17015 removed.add(pa); 17016 } 17017 } 17018 if (removed != null) { 17019 for (int j=0; j<removed.size(); j++) { 17020 PreferredActivity pa = removed.get(j); 17021 pir.removeFilter(pa); 17022 } 17023 changed = true; 17024 } 17025 } 17026 return changed; 17027 } 17028 17029 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 17030 private void clearIntentFilterVerificationsLPw(int userId) { 17031 final int packageCount = mPackages.size(); 17032 for (int i = 0; i < packageCount; i++) { 17033 PackageParser.Package pkg = mPackages.valueAt(i); 17034 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 17035 } 17036 } 17037 17038 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 17039 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 17040 if (userId == UserHandle.USER_ALL) { 17041 if (mSettings.removeIntentFilterVerificationLPw(packageName, 17042 sUserManager.getUserIds())) { 17043 for (int oneUserId : sUserManager.getUserIds()) { 17044 scheduleWritePackageRestrictionsLocked(oneUserId); 17045 } 17046 } 17047 } else { 17048 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 17049 scheduleWritePackageRestrictionsLocked(userId); 17050 } 17051 } 17052 } 17053 17054 void clearDefaultBrowserIfNeeded(String packageName) { 17055 for (int oneUserId : sUserManager.getUserIds()) { 17056 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 17057 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 17058 if (packageName.equals(defaultBrowserPackageName)) { 17059 setDefaultBrowserPackageName(null, oneUserId); 17060 } 17061 } 17062 } 17063 17064 @Override 17065 public void resetApplicationPreferences(int userId) { 17066 mContext.enforceCallingOrSelfPermission( 17067 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17068 final long identity = Binder.clearCallingIdentity(); 17069 // writer 17070 try { 17071 synchronized (mPackages) { 17072 clearPackagePreferredActivitiesLPw(null, userId); 17073 mSettings.applyDefaultPreferredAppsLPw(this, userId); 17074 // TODO: We have to reset the default SMS and Phone. This requires 17075 // significant refactoring to keep all default apps in the package 17076 // manager (cleaner but more work) or have the services provide 17077 // callbacks to the package manager to request a default app reset. 17078 applyFactoryDefaultBrowserLPw(userId); 17079 clearIntentFilterVerificationsLPw(userId); 17080 primeDomainVerificationsLPw(userId); 17081 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 17082 scheduleWritePackageRestrictionsLocked(userId); 17083 } 17084 resetNetworkPolicies(userId); 17085 } finally { 17086 Binder.restoreCallingIdentity(identity); 17087 } 17088 } 17089 17090 @Override 17091 public int getPreferredActivities(List<IntentFilter> outFilters, 17092 List<ComponentName> outActivities, String packageName) { 17093 17094 int num = 0; 17095 final int userId = UserHandle.getCallingUserId(); 17096 // reader 17097 synchronized (mPackages) { 17098 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 17099 if (pir != null) { 17100 final Iterator<PreferredActivity> it = pir.filterIterator(); 17101 while (it.hasNext()) { 17102 final PreferredActivity pa = it.next(); 17103 if (packageName == null 17104 || (pa.mPref.mComponent.getPackageName().equals(packageName) 17105 && pa.mPref.mAlways)) { 17106 if (outFilters != null) { 17107 outFilters.add(new IntentFilter(pa)); 17108 } 17109 if (outActivities != null) { 17110 outActivities.add(pa.mPref.mComponent); 17111 } 17112 } 17113 } 17114 } 17115 } 17116 17117 return num; 17118 } 17119 17120 @Override 17121 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 17122 int userId) { 17123 int callingUid = Binder.getCallingUid(); 17124 if (callingUid != Process.SYSTEM_UID) { 17125 throw new SecurityException( 17126 "addPersistentPreferredActivity can only be run by the system"); 17127 } 17128 if (filter.countActions() == 0) { 17129 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 17130 return; 17131 } 17132 synchronized (mPackages) { 17133 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 17134 ":"); 17135 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17136 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 17137 new PersistentPreferredActivity(filter, activity)); 17138 scheduleWritePackageRestrictionsLocked(userId); 17139 } 17140 } 17141 17142 @Override 17143 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 17144 int callingUid = Binder.getCallingUid(); 17145 if (callingUid != Process.SYSTEM_UID) { 17146 throw new SecurityException( 17147 "clearPackagePersistentPreferredActivities can only be run by the system"); 17148 } 17149 ArrayList<PersistentPreferredActivity> removed = null; 17150 boolean changed = false; 17151 synchronized (mPackages) { 17152 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 17153 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 17154 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 17155 .valueAt(i); 17156 if (userId != thisUserId) { 17157 continue; 17158 } 17159 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 17160 while (it.hasNext()) { 17161 PersistentPreferredActivity ppa = it.next(); 17162 // Mark entry for removal only if it matches the package name. 17163 if (ppa.mComponent.getPackageName().equals(packageName)) { 17164 if (removed == null) { 17165 removed = new ArrayList<PersistentPreferredActivity>(); 17166 } 17167 removed.add(ppa); 17168 } 17169 } 17170 if (removed != null) { 17171 for (int j=0; j<removed.size(); j++) { 17172 PersistentPreferredActivity ppa = removed.get(j); 17173 ppir.removeFilter(ppa); 17174 } 17175 changed = true; 17176 } 17177 } 17178 17179 if (changed) { 17180 scheduleWritePackageRestrictionsLocked(userId); 17181 } 17182 } 17183 } 17184 17185 /** 17186 * Common machinery for picking apart a restored XML blob and passing 17187 * it to a caller-supplied functor to be applied to the running system. 17188 */ 17189 private void restoreFromXml(XmlPullParser parser, int userId, 17190 String expectedStartTag, BlobXmlRestorer functor) 17191 throws IOException, XmlPullParserException { 17192 int type; 17193 while ((type = parser.next()) != XmlPullParser.START_TAG 17194 && type != XmlPullParser.END_DOCUMENT) { 17195 } 17196 if (type != XmlPullParser.START_TAG) { 17197 // oops didn't find a start tag?! 17198 if (DEBUG_BACKUP) { 17199 Slog.e(TAG, "Didn't find start tag during restore"); 17200 } 17201 return; 17202 } 17203Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 17204 // this is supposed to be TAG_PREFERRED_BACKUP 17205 if (!expectedStartTag.equals(parser.getName())) { 17206 if (DEBUG_BACKUP) { 17207 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 17208 } 17209 return; 17210 } 17211 17212 // skip interfering stuff, then we're aligned with the backing implementation 17213 while ((type = parser.next()) == XmlPullParser.TEXT) { } 17214Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 17215 functor.apply(parser, userId); 17216 } 17217 17218 private interface BlobXmlRestorer { 17219 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 17220 } 17221 17222 /** 17223 * Non-Binder method, support for the backup/restore mechanism: write the 17224 * full set of preferred activities in its canonical XML format. Returns the 17225 * XML output as a byte array, or null if there is none. 17226 */ 17227 @Override 17228 public byte[] getPreferredActivityBackup(int userId) { 17229 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17230 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 17231 } 17232 17233 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17234 try { 17235 final XmlSerializer serializer = new FastXmlSerializer(); 17236 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17237 serializer.startDocument(null, true); 17238 serializer.startTag(null, TAG_PREFERRED_BACKUP); 17239 17240 synchronized (mPackages) { 17241 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 17242 } 17243 17244 serializer.endTag(null, TAG_PREFERRED_BACKUP); 17245 serializer.endDocument(); 17246 serializer.flush(); 17247 } catch (Exception e) { 17248 if (DEBUG_BACKUP) { 17249 Slog.e(TAG, "Unable to write preferred activities for backup", e); 17250 } 17251 return null; 17252 } 17253 17254 return dataStream.toByteArray(); 17255 } 17256 17257 @Override 17258 public void restorePreferredActivities(byte[] backup, int userId) { 17259 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17260 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17261 } 17262 17263 try { 17264 final XmlPullParser parser = Xml.newPullParser(); 17265 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17266 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 17267 new BlobXmlRestorer() { 17268 @Override 17269 public void apply(XmlPullParser parser, int userId) 17270 throws XmlPullParserException, IOException { 17271 synchronized (mPackages) { 17272 mSettings.readPreferredActivitiesLPw(parser, userId); 17273 } 17274 } 17275 } ); 17276 } catch (Exception e) { 17277 if (DEBUG_BACKUP) { 17278 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17279 } 17280 } 17281 } 17282 17283 /** 17284 * Non-Binder method, support for the backup/restore mechanism: write the 17285 * default browser (etc) settings in its canonical XML format. Returns the default 17286 * browser XML representation as a byte array, or null if there is none. 17287 */ 17288 @Override 17289 public byte[] getDefaultAppsBackup(int userId) { 17290 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17291 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 17292 } 17293 17294 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17295 try { 17296 final XmlSerializer serializer = new FastXmlSerializer(); 17297 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17298 serializer.startDocument(null, true); 17299 serializer.startTag(null, TAG_DEFAULT_APPS); 17300 17301 synchronized (mPackages) { 17302 mSettings.writeDefaultAppsLPr(serializer, userId); 17303 } 17304 17305 serializer.endTag(null, TAG_DEFAULT_APPS); 17306 serializer.endDocument(); 17307 serializer.flush(); 17308 } catch (Exception e) { 17309 if (DEBUG_BACKUP) { 17310 Slog.e(TAG, "Unable to write default apps for backup", e); 17311 } 17312 return null; 17313 } 17314 17315 return dataStream.toByteArray(); 17316 } 17317 17318 @Override 17319 public void restoreDefaultApps(byte[] backup, int userId) { 17320 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17321 throw new SecurityException("Only the system may call restoreDefaultApps()"); 17322 } 17323 17324 try { 17325 final XmlPullParser parser = Xml.newPullParser(); 17326 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17327 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 17328 new BlobXmlRestorer() { 17329 @Override 17330 public void apply(XmlPullParser parser, int userId) 17331 throws XmlPullParserException, IOException { 17332 synchronized (mPackages) { 17333 mSettings.readDefaultAppsLPw(parser, userId); 17334 } 17335 } 17336 } ); 17337 } catch (Exception e) { 17338 if (DEBUG_BACKUP) { 17339 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 17340 } 17341 } 17342 } 17343 17344 @Override 17345 public byte[] getIntentFilterVerificationBackup(int userId) { 17346 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17347 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 17348 } 17349 17350 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17351 try { 17352 final XmlSerializer serializer = new FastXmlSerializer(); 17353 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17354 serializer.startDocument(null, true); 17355 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 17356 17357 synchronized (mPackages) { 17358 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 17359 } 17360 17361 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 17362 serializer.endDocument(); 17363 serializer.flush(); 17364 } catch (Exception e) { 17365 if (DEBUG_BACKUP) { 17366 Slog.e(TAG, "Unable to write default apps for backup", e); 17367 } 17368 return null; 17369 } 17370 17371 return dataStream.toByteArray(); 17372 } 17373 17374 @Override 17375 public void restoreIntentFilterVerification(byte[] backup, int userId) { 17376 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17377 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17378 } 17379 17380 try { 17381 final XmlPullParser parser = Xml.newPullParser(); 17382 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17383 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 17384 new BlobXmlRestorer() { 17385 @Override 17386 public void apply(XmlPullParser parser, int userId) 17387 throws XmlPullParserException, IOException { 17388 synchronized (mPackages) { 17389 mSettings.readAllDomainVerificationsLPr(parser, userId); 17390 mSettings.writeLPr(); 17391 } 17392 } 17393 } ); 17394 } catch (Exception e) { 17395 if (DEBUG_BACKUP) { 17396 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17397 } 17398 } 17399 } 17400 17401 @Override 17402 public byte[] getPermissionGrantBackup(int userId) { 17403 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17404 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 17405 } 17406 17407 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17408 try { 17409 final XmlSerializer serializer = new FastXmlSerializer(); 17410 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17411 serializer.startDocument(null, true); 17412 serializer.startTag(null, TAG_PERMISSION_BACKUP); 17413 17414 synchronized (mPackages) { 17415 serializeRuntimePermissionGrantsLPr(serializer, userId); 17416 } 17417 17418 serializer.endTag(null, TAG_PERMISSION_BACKUP); 17419 serializer.endDocument(); 17420 serializer.flush(); 17421 } catch (Exception e) { 17422 if (DEBUG_BACKUP) { 17423 Slog.e(TAG, "Unable to write default apps for backup", e); 17424 } 17425 return null; 17426 } 17427 17428 return dataStream.toByteArray(); 17429 } 17430 17431 @Override 17432 public void restorePermissionGrants(byte[] backup, int userId) { 17433 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17434 throw new SecurityException("Only the system may call restorePermissionGrants()"); 17435 } 17436 17437 try { 17438 final XmlPullParser parser = Xml.newPullParser(); 17439 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17440 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 17441 new BlobXmlRestorer() { 17442 @Override 17443 public void apply(XmlPullParser parser, int userId) 17444 throws XmlPullParserException, IOException { 17445 synchronized (mPackages) { 17446 processRestoredPermissionGrantsLPr(parser, userId); 17447 } 17448 } 17449 } ); 17450 } catch (Exception e) { 17451 if (DEBUG_BACKUP) { 17452 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17453 } 17454 } 17455 } 17456 17457 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 17458 throws IOException { 17459 serializer.startTag(null, TAG_ALL_GRANTS); 17460 17461 final int N = mSettings.mPackages.size(); 17462 for (int i = 0; i < N; i++) { 17463 final PackageSetting ps = mSettings.mPackages.valueAt(i); 17464 boolean pkgGrantsKnown = false; 17465 17466 PermissionsState packagePerms = ps.getPermissionsState(); 17467 17468 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 17469 final int grantFlags = state.getFlags(); 17470 // only look at grants that are not system/policy fixed 17471 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 17472 final boolean isGranted = state.isGranted(); 17473 // And only back up the user-twiddled state bits 17474 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 17475 final String packageName = mSettings.mPackages.keyAt(i); 17476 if (!pkgGrantsKnown) { 17477 serializer.startTag(null, TAG_GRANT); 17478 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 17479 pkgGrantsKnown = true; 17480 } 17481 17482 final boolean userSet = 17483 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 17484 final boolean userFixed = 17485 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 17486 final boolean revoke = 17487 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 17488 17489 serializer.startTag(null, TAG_PERMISSION); 17490 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 17491 if (isGranted) { 17492 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 17493 } 17494 if (userSet) { 17495 serializer.attribute(null, ATTR_USER_SET, "true"); 17496 } 17497 if (userFixed) { 17498 serializer.attribute(null, ATTR_USER_FIXED, "true"); 17499 } 17500 if (revoke) { 17501 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 17502 } 17503 serializer.endTag(null, TAG_PERMISSION); 17504 } 17505 } 17506 } 17507 17508 if (pkgGrantsKnown) { 17509 serializer.endTag(null, TAG_GRANT); 17510 } 17511 } 17512 17513 serializer.endTag(null, TAG_ALL_GRANTS); 17514 } 17515 17516 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 17517 throws XmlPullParserException, IOException { 17518 String pkgName = null; 17519 int outerDepth = parser.getDepth(); 17520 int type; 17521 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 17522 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 17523 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 17524 continue; 17525 } 17526 17527 final String tagName = parser.getName(); 17528 if (tagName.equals(TAG_GRANT)) { 17529 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 17530 if (DEBUG_BACKUP) { 17531 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 17532 } 17533 } else if (tagName.equals(TAG_PERMISSION)) { 17534 17535 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 17536 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 17537 17538 int newFlagSet = 0; 17539 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 17540 newFlagSet |= FLAG_PERMISSION_USER_SET; 17541 } 17542 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 17543 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 17544 } 17545 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 17546 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 17547 } 17548 if (DEBUG_BACKUP) { 17549 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 17550 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 17551 } 17552 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17553 if (ps != null) { 17554 // Already installed so we apply the grant immediately 17555 if (DEBUG_BACKUP) { 17556 Slog.v(TAG, " + already installed; applying"); 17557 } 17558 PermissionsState perms = ps.getPermissionsState(); 17559 BasePermission bp = mSettings.mPermissions.get(permName); 17560 if (bp != null) { 17561 if (isGranted) { 17562 perms.grantRuntimePermission(bp, userId); 17563 } 17564 if (newFlagSet != 0) { 17565 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 17566 } 17567 } 17568 } else { 17569 // Need to wait for post-restore install to apply the grant 17570 if (DEBUG_BACKUP) { 17571 Slog.v(TAG, " - not yet installed; saving for later"); 17572 } 17573 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 17574 isGranted, newFlagSet, userId); 17575 } 17576 } else { 17577 PackageManagerService.reportSettingsProblem(Log.WARN, 17578 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 17579 XmlUtils.skipCurrentTag(parser); 17580 } 17581 } 17582 17583 scheduleWriteSettingsLocked(); 17584 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 17585 } 17586 17587 @Override 17588 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 17589 int sourceUserId, int targetUserId, int flags) { 17590 mContext.enforceCallingOrSelfPermission( 17591 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17592 int callingUid = Binder.getCallingUid(); 17593 enforceOwnerRights(ownerPackage, callingUid); 17594 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17595 if (intentFilter.countActions() == 0) { 17596 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 17597 return; 17598 } 17599 synchronized (mPackages) { 17600 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 17601 ownerPackage, targetUserId, flags); 17602 CrossProfileIntentResolver resolver = 17603 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17604 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 17605 // We have all those whose filter is equal. Now checking if the rest is equal as well. 17606 if (existing != null) { 17607 int size = existing.size(); 17608 for (int i = 0; i < size; i++) { 17609 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 17610 return; 17611 } 17612 } 17613 } 17614 resolver.addFilter(newFilter); 17615 scheduleWritePackageRestrictionsLocked(sourceUserId); 17616 } 17617 } 17618 17619 @Override 17620 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 17621 mContext.enforceCallingOrSelfPermission( 17622 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17623 int callingUid = Binder.getCallingUid(); 17624 enforceOwnerRights(ownerPackage, callingUid); 17625 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17626 synchronized (mPackages) { 17627 CrossProfileIntentResolver resolver = 17628 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17629 ArraySet<CrossProfileIntentFilter> set = 17630 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 17631 for (CrossProfileIntentFilter filter : set) { 17632 if (filter.getOwnerPackage().equals(ownerPackage)) { 17633 resolver.removeFilter(filter); 17634 } 17635 } 17636 scheduleWritePackageRestrictionsLocked(sourceUserId); 17637 } 17638 } 17639 17640 // Enforcing that callingUid is owning pkg on userId 17641 private void enforceOwnerRights(String pkg, int callingUid) { 17642 // The system owns everything. 17643 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 17644 return; 17645 } 17646 int callingUserId = UserHandle.getUserId(callingUid); 17647 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 17648 if (pi == null) { 17649 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 17650 + callingUserId); 17651 } 17652 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 17653 throw new SecurityException("Calling uid " + callingUid 17654 + " does not own package " + pkg); 17655 } 17656 } 17657 17658 @Override 17659 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 17660 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 17661 } 17662 17663 private Intent getHomeIntent() { 17664 Intent intent = new Intent(Intent.ACTION_MAIN); 17665 intent.addCategory(Intent.CATEGORY_HOME); 17666 intent.addCategory(Intent.CATEGORY_DEFAULT); 17667 return intent; 17668 } 17669 17670 private IntentFilter getHomeFilter() { 17671 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 17672 filter.addCategory(Intent.CATEGORY_HOME); 17673 filter.addCategory(Intent.CATEGORY_DEFAULT); 17674 return filter; 17675 } 17676 17677 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 17678 int userId) { 17679 Intent intent = getHomeIntent(); 17680 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 17681 PackageManager.GET_META_DATA, userId); 17682 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 17683 true, false, false, userId); 17684 17685 allHomeCandidates.clear(); 17686 if (list != null) { 17687 for (ResolveInfo ri : list) { 17688 allHomeCandidates.add(ri); 17689 } 17690 } 17691 return (preferred == null || preferred.activityInfo == null) 17692 ? null 17693 : new ComponentName(preferred.activityInfo.packageName, 17694 preferred.activityInfo.name); 17695 } 17696 17697 @Override 17698 public void setHomeActivity(ComponentName comp, int userId) { 17699 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 17700 getHomeActivitiesAsUser(homeActivities, userId); 17701 17702 boolean found = false; 17703 17704 final int size = homeActivities.size(); 17705 final ComponentName[] set = new ComponentName[size]; 17706 for (int i = 0; i < size; i++) { 17707 final ResolveInfo candidate = homeActivities.get(i); 17708 final ActivityInfo info = candidate.activityInfo; 17709 final ComponentName activityName = new ComponentName(info.packageName, info.name); 17710 set[i] = activityName; 17711 if (!found && activityName.equals(comp)) { 17712 found = true; 17713 } 17714 } 17715 if (!found) { 17716 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 17717 + userId); 17718 } 17719 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 17720 set, comp, userId); 17721 } 17722 17723 private @Nullable String getSetupWizardPackageName() { 17724 final Intent intent = new Intent(Intent.ACTION_MAIN); 17725 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 17726 17727 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 17728 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 17729 | MATCH_DISABLED_COMPONENTS, 17730 UserHandle.myUserId()); 17731 if (matches.size() == 1) { 17732 return matches.get(0).getComponentInfo().packageName; 17733 } else { 17734 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 17735 + ": matches=" + matches); 17736 return null; 17737 } 17738 } 17739 17740 @Override 17741 public void setApplicationEnabledSetting(String appPackageName, 17742 int newState, int flags, int userId, String callingPackage) { 17743 if (!sUserManager.exists(userId)) return; 17744 if (callingPackage == null) { 17745 callingPackage = Integer.toString(Binder.getCallingUid()); 17746 } 17747 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 17748 } 17749 17750 @Override 17751 public void setComponentEnabledSetting(ComponentName componentName, 17752 int newState, int flags, int userId) { 17753 if (!sUserManager.exists(userId)) return; 17754 setEnabledSetting(componentName.getPackageName(), 17755 componentName.getClassName(), newState, flags, userId, null); 17756 } 17757 17758 private void setEnabledSetting(final String packageName, String className, int newState, 17759 final int flags, int userId, String callingPackage) { 17760 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 17761 || newState == COMPONENT_ENABLED_STATE_ENABLED 17762 || newState == COMPONENT_ENABLED_STATE_DISABLED 17763 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17764 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 17765 throw new IllegalArgumentException("Invalid new component state: " 17766 + newState); 17767 } 17768 PackageSetting pkgSetting; 17769 final int uid = Binder.getCallingUid(); 17770 final int permission; 17771 if (uid == Process.SYSTEM_UID) { 17772 permission = PackageManager.PERMISSION_GRANTED; 17773 } else { 17774 permission = mContext.checkCallingOrSelfPermission( 17775 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17776 } 17777 enforceCrossUserPermission(uid, userId, 17778 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 17779 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17780 boolean sendNow = false; 17781 boolean isApp = (className == null); 17782 String componentName = isApp ? packageName : className; 17783 int packageUid = -1; 17784 ArrayList<String> components; 17785 17786 // writer 17787 synchronized (mPackages) { 17788 pkgSetting = mSettings.mPackages.get(packageName); 17789 if (pkgSetting == null) { 17790 if (className == null) { 17791 throw new IllegalArgumentException("Unknown package: " + packageName); 17792 } 17793 throw new IllegalArgumentException( 17794 "Unknown component: " + packageName + "/" + className); 17795 } 17796 } 17797 17798 // Limit who can change which apps 17799 if (!UserHandle.isSameApp(uid, pkgSetting.appId)) { 17800 // Don't allow apps that don't have permission to modify other apps 17801 if (!allowedByPermission) { 17802 throw new SecurityException( 17803 "Permission Denial: attempt to change component state from pid=" 17804 + Binder.getCallingPid() 17805 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 17806 } 17807 // Don't allow changing protected packages. 17808 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 17809 throw new SecurityException("Cannot disable a protected package: " + packageName); 17810 } 17811 } 17812 17813 synchronized (mPackages) { 17814 if (uid == Process.SHELL_UID) { 17815 // Shell can only change whole packages between ENABLED and DISABLED_USER states 17816 int oldState = pkgSetting.getEnabled(userId); 17817 if (className == null 17818 && 17819 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 17820 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 17821 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 17822 && 17823 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17824 || newState == COMPONENT_ENABLED_STATE_DEFAULT 17825 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 17826 // ok 17827 } else { 17828 throw new SecurityException( 17829 "Shell cannot change component state for " + packageName + "/" 17830 + className + " to " + newState); 17831 } 17832 } 17833 if (className == null) { 17834 // We're dealing with an application/package level state change 17835 if (pkgSetting.getEnabled(userId) == newState) { 17836 // Nothing to do 17837 return; 17838 } 17839 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 17840 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 17841 // Don't care about who enables an app. 17842 callingPackage = null; 17843 } 17844 pkgSetting.setEnabled(newState, userId, callingPackage); 17845 // pkgSetting.pkg.mSetEnabled = newState; 17846 } else { 17847 // We're dealing with a component level state change 17848 // First, verify that this is a valid class name. 17849 PackageParser.Package pkg = pkgSetting.pkg; 17850 if (pkg == null || !pkg.hasComponentClassName(className)) { 17851 if (pkg != null && 17852 pkg.applicationInfo.targetSdkVersion >= 17853 Build.VERSION_CODES.JELLY_BEAN) { 17854 throw new IllegalArgumentException("Component class " + className 17855 + " does not exist in " + packageName); 17856 } else { 17857 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 17858 + className + " does not exist in " + packageName); 17859 } 17860 } 17861 switch (newState) { 17862 case COMPONENT_ENABLED_STATE_ENABLED: 17863 if (!pkgSetting.enableComponentLPw(className, userId)) { 17864 return; 17865 } 17866 break; 17867 case COMPONENT_ENABLED_STATE_DISABLED: 17868 if (!pkgSetting.disableComponentLPw(className, userId)) { 17869 return; 17870 } 17871 break; 17872 case COMPONENT_ENABLED_STATE_DEFAULT: 17873 if (!pkgSetting.restoreComponentLPw(className, userId)) { 17874 return; 17875 } 17876 break; 17877 default: 17878 Slog.e(TAG, "Invalid new component state: " + newState); 17879 return; 17880 } 17881 } 17882 scheduleWritePackageRestrictionsLocked(userId); 17883 components = mPendingBroadcasts.get(userId, packageName); 17884 final boolean newPackage = components == null; 17885 if (newPackage) { 17886 components = new ArrayList<String>(); 17887 } 17888 if (!components.contains(componentName)) { 17889 components.add(componentName); 17890 } 17891 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 17892 sendNow = true; 17893 // Purge entry from pending broadcast list if another one exists already 17894 // since we are sending one right away. 17895 mPendingBroadcasts.remove(userId, packageName); 17896 } else { 17897 if (newPackage) { 17898 mPendingBroadcasts.put(userId, packageName, components); 17899 } 17900 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 17901 // Schedule a message 17902 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 17903 } 17904 } 17905 } 17906 17907 long callingId = Binder.clearCallingIdentity(); 17908 try { 17909 if (sendNow) { 17910 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 17911 sendPackageChangedBroadcast(packageName, 17912 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 17913 } 17914 } finally { 17915 Binder.restoreCallingIdentity(callingId); 17916 } 17917 } 17918 17919 @Override 17920 public void flushPackageRestrictionsAsUser(int userId) { 17921 if (!sUserManager.exists(userId)) { 17922 return; 17923 } 17924 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 17925 false /* checkShell */, "flushPackageRestrictions"); 17926 synchronized (mPackages) { 17927 mSettings.writePackageRestrictionsLPr(userId); 17928 mDirtyUsers.remove(userId); 17929 if (mDirtyUsers.isEmpty()) { 17930 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 17931 } 17932 } 17933 } 17934 17935 private void sendPackageChangedBroadcast(String packageName, 17936 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 17937 if (DEBUG_INSTALL) 17938 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 17939 + componentNames); 17940 Bundle extras = new Bundle(4); 17941 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 17942 String nameList[] = new String[componentNames.size()]; 17943 componentNames.toArray(nameList); 17944 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 17945 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 17946 extras.putInt(Intent.EXTRA_UID, packageUid); 17947 // If this is not reporting a change of the overall package, then only send it 17948 // to registered receivers. We don't want to launch a swath of apps for every 17949 // little component state change. 17950 final int flags = !componentNames.contains(packageName) 17951 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 17952 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 17953 new int[] {UserHandle.getUserId(packageUid)}); 17954 } 17955 17956 @Override 17957 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 17958 if (!sUserManager.exists(userId)) return; 17959 final int uid = Binder.getCallingUid(); 17960 final int permission = mContext.checkCallingOrSelfPermission( 17961 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17962 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17963 enforceCrossUserPermission(uid, userId, 17964 true /* requireFullPermission */, true /* checkShell */, "stop package"); 17965 // writer 17966 synchronized (mPackages) { 17967 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 17968 allowedByPermission, uid, userId)) { 17969 scheduleWritePackageRestrictionsLocked(userId); 17970 } 17971 } 17972 } 17973 17974 @Override 17975 public String getInstallerPackageName(String packageName) { 17976 // reader 17977 synchronized (mPackages) { 17978 return mSettings.getInstallerPackageNameLPr(packageName); 17979 } 17980 } 17981 17982 public boolean isOrphaned(String packageName) { 17983 // reader 17984 synchronized (mPackages) { 17985 return mSettings.isOrphaned(packageName); 17986 } 17987 } 17988 17989 @Override 17990 public int getApplicationEnabledSetting(String packageName, int userId) { 17991 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17992 int uid = Binder.getCallingUid(); 17993 enforceCrossUserPermission(uid, userId, 17994 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 17995 // reader 17996 synchronized (mPackages) { 17997 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 17998 } 17999 } 18000 18001 @Override 18002 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 18003 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 18004 int uid = Binder.getCallingUid(); 18005 enforceCrossUserPermission(uid, userId, 18006 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 18007 // reader 18008 synchronized (mPackages) { 18009 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 18010 } 18011 } 18012 18013 @Override 18014 public void enterSafeMode() { 18015 enforceSystemOrRoot("Only the system can request entering safe mode"); 18016 18017 if (!mSystemReady) { 18018 mSafeMode = true; 18019 } 18020 } 18021 18022 @Override 18023 public void systemReady() { 18024 mSystemReady = true; 18025 18026 // Read the compatibilty setting when the system is ready. 18027 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 18028 mContext.getContentResolver(), 18029 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 18030 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 18031 if (DEBUG_SETTINGS) { 18032 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 18033 } 18034 18035 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 18036 18037 synchronized (mPackages) { 18038 // Verify that all of the preferred activity components actually 18039 // exist. It is possible for applications to be updated and at 18040 // that point remove a previously declared activity component that 18041 // had been set as a preferred activity. We try to clean this up 18042 // the next time we encounter that preferred activity, but it is 18043 // possible for the user flow to never be able to return to that 18044 // situation so here we do a sanity check to make sure we haven't 18045 // left any junk around. 18046 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 18047 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18048 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18049 removed.clear(); 18050 for (PreferredActivity pa : pir.filterSet()) { 18051 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 18052 removed.add(pa); 18053 } 18054 } 18055 if (removed.size() > 0) { 18056 for (int r=0; r<removed.size(); r++) { 18057 PreferredActivity pa = removed.get(r); 18058 Slog.w(TAG, "Removing dangling preferred activity: " 18059 + pa.mPref.mComponent); 18060 pir.removeFilter(pa); 18061 } 18062 mSettings.writePackageRestrictionsLPr( 18063 mSettings.mPreferredActivities.keyAt(i)); 18064 } 18065 } 18066 18067 for (int userId : UserManagerService.getInstance().getUserIds()) { 18068 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 18069 grantPermissionsUserIds = ArrayUtils.appendInt( 18070 grantPermissionsUserIds, userId); 18071 } 18072 } 18073 } 18074 sUserManager.systemReady(); 18075 18076 // If we upgraded grant all default permissions before kicking off. 18077 for (int userId : grantPermissionsUserIds) { 18078 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 18079 } 18080 18081 // Kick off any messages waiting for system ready 18082 if (mPostSystemReadyMessages != null) { 18083 for (Message msg : mPostSystemReadyMessages) { 18084 msg.sendToTarget(); 18085 } 18086 mPostSystemReadyMessages = null; 18087 } 18088 18089 // Watch for external volumes that come and go over time 18090 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18091 storage.registerListener(mStorageListener); 18092 18093 mInstallerService.systemReady(); 18094 mPackageDexOptimizer.systemReady(); 18095 18096 MountServiceInternal mountServiceInternal = LocalServices.getService( 18097 MountServiceInternal.class); 18098 mountServiceInternal.addExternalStoragePolicy( 18099 new MountServiceInternal.ExternalStorageMountPolicy() { 18100 @Override 18101 public int getMountMode(int uid, String packageName) { 18102 if (Process.isIsolated(uid)) { 18103 return Zygote.MOUNT_EXTERNAL_NONE; 18104 } 18105 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 18106 return Zygote.MOUNT_EXTERNAL_DEFAULT; 18107 } 18108 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 18109 return Zygote.MOUNT_EXTERNAL_DEFAULT; 18110 } 18111 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 18112 return Zygote.MOUNT_EXTERNAL_READ; 18113 } 18114 return Zygote.MOUNT_EXTERNAL_WRITE; 18115 } 18116 18117 @Override 18118 public boolean hasExternalStorage(int uid, String packageName) { 18119 return true; 18120 } 18121 }); 18122 18123 // Now that we're mostly running, clean up stale users and apps 18124 reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 18125 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 18126 } 18127 18128 @Override 18129 public boolean isSafeMode() { 18130 return mSafeMode; 18131 } 18132 18133 @Override 18134 public boolean hasSystemUidErrors() { 18135 return mHasSystemUidErrors; 18136 } 18137 18138 static String arrayToString(int[] array) { 18139 StringBuffer buf = new StringBuffer(128); 18140 buf.append('['); 18141 if (array != null) { 18142 for (int i=0; i<array.length; i++) { 18143 if (i > 0) buf.append(", "); 18144 buf.append(array[i]); 18145 } 18146 } 18147 buf.append(']'); 18148 return buf.toString(); 18149 } 18150 18151 static class DumpState { 18152 public static final int DUMP_LIBS = 1 << 0; 18153 public static final int DUMP_FEATURES = 1 << 1; 18154 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 18155 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 18156 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 18157 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 18158 public static final int DUMP_PERMISSIONS = 1 << 6; 18159 public static final int DUMP_PACKAGES = 1 << 7; 18160 public static final int DUMP_SHARED_USERS = 1 << 8; 18161 public static final int DUMP_MESSAGES = 1 << 9; 18162 public static final int DUMP_PROVIDERS = 1 << 10; 18163 public static final int DUMP_VERIFIERS = 1 << 11; 18164 public static final int DUMP_PREFERRED = 1 << 12; 18165 public static final int DUMP_PREFERRED_XML = 1 << 13; 18166 public static final int DUMP_KEYSETS = 1 << 14; 18167 public static final int DUMP_VERSION = 1 << 15; 18168 public static final int DUMP_INSTALLS = 1 << 16; 18169 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 18170 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 18171 public static final int DUMP_FROZEN = 1 << 19; 18172 public static final int DUMP_DEXOPT = 1 << 20; 18173 18174 public static final int OPTION_SHOW_FILTERS = 1 << 0; 18175 18176 private int mTypes; 18177 18178 private int mOptions; 18179 18180 private boolean mTitlePrinted; 18181 18182 private SharedUserSetting mSharedUser; 18183 18184 public boolean isDumping(int type) { 18185 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 18186 return true; 18187 } 18188 18189 return (mTypes & type) != 0; 18190 } 18191 18192 public void setDump(int type) { 18193 mTypes |= type; 18194 } 18195 18196 public boolean isOptionEnabled(int option) { 18197 return (mOptions & option) != 0; 18198 } 18199 18200 public void setOptionEnabled(int option) { 18201 mOptions |= option; 18202 } 18203 18204 public boolean onTitlePrinted() { 18205 final boolean printed = mTitlePrinted; 18206 mTitlePrinted = true; 18207 return printed; 18208 } 18209 18210 public boolean getTitlePrinted() { 18211 return mTitlePrinted; 18212 } 18213 18214 public void setTitlePrinted(boolean enabled) { 18215 mTitlePrinted = enabled; 18216 } 18217 18218 public SharedUserSetting getSharedUser() { 18219 return mSharedUser; 18220 } 18221 18222 public void setSharedUser(SharedUserSetting user) { 18223 mSharedUser = user; 18224 } 18225 } 18226 18227 @Override 18228 public void onShellCommand(FileDescriptor in, FileDescriptor out, 18229 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 18230 (new PackageManagerShellCommand(this)).exec( 18231 this, in, out, err, args, resultReceiver); 18232 } 18233 18234 @Override 18235 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 18236 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 18237 != PackageManager.PERMISSION_GRANTED) { 18238 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 18239 + Binder.getCallingPid() 18240 + ", uid=" + Binder.getCallingUid() 18241 + " without permission " 18242 + android.Manifest.permission.DUMP); 18243 return; 18244 } 18245 18246 DumpState dumpState = new DumpState(); 18247 boolean fullPreferred = false; 18248 boolean checkin = false; 18249 18250 String packageName = null; 18251 ArraySet<String> permissionNames = null; 18252 18253 int opti = 0; 18254 while (opti < args.length) { 18255 String opt = args[opti]; 18256 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 18257 break; 18258 } 18259 opti++; 18260 18261 if ("-a".equals(opt)) { 18262 // Right now we only know how to print all. 18263 } else if ("-h".equals(opt)) { 18264 pw.println("Package manager dump options:"); 18265 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 18266 pw.println(" --checkin: dump for a checkin"); 18267 pw.println(" -f: print details of intent filters"); 18268 pw.println(" -h: print this help"); 18269 pw.println(" cmd may be one of:"); 18270 pw.println(" l[ibraries]: list known shared libraries"); 18271 pw.println(" f[eatures]: list device features"); 18272 pw.println(" k[eysets]: print known keysets"); 18273 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 18274 pw.println(" perm[issions]: dump permissions"); 18275 pw.println(" permission [name ...]: dump declaration and use of given permission"); 18276 pw.println(" pref[erred]: print preferred package settings"); 18277 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 18278 pw.println(" prov[iders]: dump content providers"); 18279 pw.println(" p[ackages]: dump installed packages"); 18280 pw.println(" s[hared-users]: dump shared user IDs"); 18281 pw.println(" m[essages]: print collected runtime messages"); 18282 pw.println(" v[erifiers]: print package verifier info"); 18283 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 18284 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 18285 pw.println(" version: print database version info"); 18286 pw.println(" write: write current settings now"); 18287 pw.println(" installs: details about install sessions"); 18288 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 18289 pw.println(" dexopt: dump dexopt state"); 18290 pw.println(" <package.name>: info about given package"); 18291 return; 18292 } else if ("--checkin".equals(opt)) { 18293 checkin = true; 18294 } else if ("-f".equals(opt)) { 18295 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18296 } else { 18297 pw.println("Unknown argument: " + opt + "; use -h for help"); 18298 } 18299 } 18300 18301 // Is the caller requesting to dump a particular piece of data? 18302 if (opti < args.length) { 18303 String cmd = args[opti]; 18304 opti++; 18305 // Is this a package name? 18306 if ("android".equals(cmd) || cmd.contains(".")) { 18307 packageName = cmd; 18308 // When dumping a single package, we always dump all of its 18309 // filter information since the amount of data will be reasonable. 18310 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18311 } else if ("check-permission".equals(cmd)) { 18312 if (opti >= args.length) { 18313 pw.println("Error: check-permission missing permission argument"); 18314 return; 18315 } 18316 String perm = args[opti]; 18317 opti++; 18318 if (opti >= args.length) { 18319 pw.println("Error: check-permission missing package argument"); 18320 return; 18321 } 18322 String pkg = args[opti]; 18323 opti++; 18324 int user = UserHandle.getUserId(Binder.getCallingUid()); 18325 if (opti < args.length) { 18326 try { 18327 user = Integer.parseInt(args[opti]); 18328 } catch (NumberFormatException e) { 18329 pw.println("Error: check-permission user argument is not a number: " 18330 + args[opti]); 18331 return; 18332 } 18333 } 18334 pw.println(checkPermission(perm, pkg, user)); 18335 return; 18336 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 18337 dumpState.setDump(DumpState.DUMP_LIBS); 18338 } else if ("f".equals(cmd) || "features".equals(cmd)) { 18339 dumpState.setDump(DumpState.DUMP_FEATURES); 18340 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 18341 if (opti >= args.length) { 18342 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 18343 | DumpState.DUMP_SERVICE_RESOLVERS 18344 | DumpState.DUMP_RECEIVER_RESOLVERS 18345 | DumpState.DUMP_CONTENT_RESOLVERS); 18346 } else { 18347 while (opti < args.length) { 18348 String name = args[opti]; 18349 if ("a".equals(name) || "activity".equals(name)) { 18350 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 18351 } else if ("s".equals(name) || "service".equals(name)) { 18352 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 18353 } else if ("r".equals(name) || "receiver".equals(name)) { 18354 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 18355 } else if ("c".equals(name) || "content".equals(name)) { 18356 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 18357 } else { 18358 pw.println("Error: unknown resolver table type: " + name); 18359 return; 18360 } 18361 opti++; 18362 } 18363 } 18364 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 18365 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 18366 } else if ("permission".equals(cmd)) { 18367 if (opti >= args.length) { 18368 pw.println("Error: permission requires permission name"); 18369 return; 18370 } 18371 permissionNames = new ArraySet<>(); 18372 while (opti < args.length) { 18373 permissionNames.add(args[opti]); 18374 opti++; 18375 } 18376 dumpState.setDump(DumpState.DUMP_PERMISSIONS 18377 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 18378 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 18379 dumpState.setDump(DumpState.DUMP_PREFERRED); 18380 } else if ("preferred-xml".equals(cmd)) { 18381 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 18382 if (opti < args.length && "--full".equals(args[opti])) { 18383 fullPreferred = true; 18384 opti++; 18385 } 18386 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 18387 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 18388 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 18389 dumpState.setDump(DumpState.DUMP_PACKAGES); 18390 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 18391 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 18392 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 18393 dumpState.setDump(DumpState.DUMP_PROVIDERS); 18394 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 18395 dumpState.setDump(DumpState.DUMP_MESSAGES); 18396 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 18397 dumpState.setDump(DumpState.DUMP_VERIFIERS); 18398 } else if ("i".equals(cmd) || "ifv".equals(cmd) 18399 || "intent-filter-verifiers".equals(cmd)) { 18400 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 18401 } else if ("version".equals(cmd)) { 18402 dumpState.setDump(DumpState.DUMP_VERSION); 18403 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 18404 dumpState.setDump(DumpState.DUMP_KEYSETS); 18405 } else if ("installs".equals(cmd)) { 18406 dumpState.setDump(DumpState.DUMP_INSTALLS); 18407 } else if ("frozen".equals(cmd)) { 18408 dumpState.setDump(DumpState.DUMP_FROZEN); 18409 } else if ("dexopt".equals(cmd)) { 18410 dumpState.setDump(DumpState.DUMP_DEXOPT); 18411 } else if ("write".equals(cmd)) { 18412 synchronized (mPackages) { 18413 mSettings.writeLPr(); 18414 pw.println("Settings written."); 18415 return; 18416 } 18417 } 18418 } 18419 18420 if (checkin) { 18421 pw.println("vers,1"); 18422 } 18423 18424 // reader 18425 synchronized (mPackages) { 18426 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 18427 if (!checkin) { 18428 if (dumpState.onTitlePrinted()) 18429 pw.println(); 18430 pw.println("Database versions:"); 18431 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 18432 } 18433 } 18434 18435 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 18436 if (!checkin) { 18437 if (dumpState.onTitlePrinted()) 18438 pw.println(); 18439 pw.println("Verifiers:"); 18440 pw.print(" Required: "); 18441 pw.print(mRequiredVerifierPackage); 18442 pw.print(" (uid="); 18443 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18444 UserHandle.USER_SYSTEM)); 18445 pw.println(")"); 18446 } else if (mRequiredVerifierPackage != null) { 18447 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 18448 pw.print(","); 18449 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18450 UserHandle.USER_SYSTEM)); 18451 } 18452 } 18453 18454 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 18455 packageName == null) { 18456 if (mIntentFilterVerifierComponent != null) { 18457 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 18458 if (!checkin) { 18459 if (dumpState.onTitlePrinted()) 18460 pw.println(); 18461 pw.println("Intent Filter Verifier:"); 18462 pw.print(" Using: "); 18463 pw.print(verifierPackageName); 18464 pw.print(" (uid="); 18465 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18466 UserHandle.USER_SYSTEM)); 18467 pw.println(")"); 18468 } else if (verifierPackageName != null) { 18469 pw.print("ifv,"); pw.print(verifierPackageName); 18470 pw.print(","); 18471 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18472 UserHandle.USER_SYSTEM)); 18473 } 18474 } else { 18475 pw.println(); 18476 pw.println("No Intent Filter Verifier available!"); 18477 } 18478 } 18479 18480 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 18481 boolean printedHeader = false; 18482 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 18483 while (it.hasNext()) { 18484 String name = it.next(); 18485 SharedLibraryEntry ent = mSharedLibraries.get(name); 18486 if (!checkin) { 18487 if (!printedHeader) { 18488 if (dumpState.onTitlePrinted()) 18489 pw.println(); 18490 pw.println("Libraries:"); 18491 printedHeader = true; 18492 } 18493 pw.print(" "); 18494 } else { 18495 pw.print("lib,"); 18496 } 18497 pw.print(name); 18498 if (!checkin) { 18499 pw.print(" -> "); 18500 } 18501 if (ent.path != null) { 18502 if (!checkin) { 18503 pw.print("(jar) "); 18504 pw.print(ent.path); 18505 } else { 18506 pw.print(",jar,"); 18507 pw.print(ent.path); 18508 } 18509 } else { 18510 if (!checkin) { 18511 pw.print("(apk) "); 18512 pw.print(ent.apk); 18513 } else { 18514 pw.print(",apk,"); 18515 pw.print(ent.apk); 18516 } 18517 } 18518 pw.println(); 18519 } 18520 } 18521 18522 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 18523 if (dumpState.onTitlePrinted()) 18524 pw.println(); 18525 if (!checkin) { 18526 pw.println("Features:"); 18527 } 18528 18529 for (FeatureInfo feat : mAvailableFeatures.values()) { 18530 if (checkin) { 18531 pw.print("feat,"); 18532 pw.print(feat.name); 18533 pw.print(","); 18534 pw.println(feat.version); 18535 } else { 18536 pw.print(" "); 18537 pw.print(feat.name); 18538 if (feat.version > 0) { 18539 pw.print(" version="); 18540 pw.print(feat.version); 18541 } 18542 pw.println(); 18543 } 18544 } 18545 } 18546 18547 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 18548 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 18549 : "Activity Resolver Table:", " ", packageName, 18550 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18551 dumpState.setTitlePrinted(true); 18552 } 18553 } 18554 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 18555 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 18556 : "Receiver Resolver Table:", " ", packageName, 18557 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18558 dumpState.setTitlePrinted(true); 18559 } 18560 } 18561 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 18562 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 18563 : "Service Resolver Table:", " ", packageName, 18564 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18565 dumpState.setTitlePrinted(true); 18566 } 18567 } 18568 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 18569 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 18570 : "Provider Resolver Table:", " ", packageName, 18571 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18572 dumpState.setTitlePrinted(true); 18573 } 18574 } 18575 18576 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 18577 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18578 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18579 int user = mSettings.mPreferredActivities.keyAt(i); 18580 if (pir.dump(pw, 18581 dumpState.getTitlePrinted() 18582 ? "\nPreferred Activities User " + user + ":" 18583 : "Preferred Activities User " + user + ":", " ", 18584 packageName, true, false)) { 18585 dumpState.setTitlePrinted(true); 18586 } 18587 } 18588 } 18589 18590 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 18591 pw.flush(); 18592 FileOutputStream fout = new FileOutputStream(fd); 18593 BufferedOutputStream str = new BufferedOutputStream(fout); 18594 XmlSerializer serializer = new FastXmlSerializer(); 18595 try { 18596 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 18597 serializer.startDocument(null, true); 18598 serializer.setFeature( 18599 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 18600 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 18601 serializer.endDocument(); 18602 serializer.flush(); 18603 } catch (IllegalArgumentException e) { 18604 pw.println("Failed writing: " + e); 18605 } catch (IllegalStateException e) { 18606 pw.println("Failed writing: " + e); 18607 } catch (IOException e) { 18608 pw.println("Failed writing: " + e); 18609 } 18610 } 18611 18612 if (!checkin 18613 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 18614 && packageName == null) { 18615 pw.println(); 18616 int count = mSettings.mPackages.size(); 18617 if (count == 0) { 18618 pw.println("No applications!"); 18619 pw.println(); 18620 } else { 18621 final String prefix = " "; 18622 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 18623 if (allPackageSettings.size() == 0) { 18624 pw.println("No domain preferred apps!"); 18625 pw.println(); 18626 } else { 18627 pw.println("App verification status:"); 18628 pw.println(); 18629 count = 0; 18630 for (PackageSetting ps : allPackageSettings) { 18631 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 18632 if (ivi == null || ivi.getPackageName() == null) continue; 18633 pw.println(prefix + "Package: " + ivi.getPackageName()); 18634 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 18635 pw.println(prefix + "Status: " + ivi.getStatusString()); 18636 pw.println(); 18637 count++; 18638 } 18639 if (count == 0) { 18640 pw.println(prefix + "No app verification established."); 18641 pw.println(); 18642 } 18643 for (int userId : sUserManager.getUserIds()) { 18644 pw.println("App linkages for user " + userId + ":"); 18645 pw.println(); 18646 count = 0; 18647 for (PackageSetting ps : allPackageSettings) { 18648 final long status = ps.getDomainVerificationStatusForUser(userId); 18649 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 18650 continue; 18651 } 18652 pw.println(prefix + "Package: " + ps.name); 18653 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 18654 String statusStr = IntentFilterVerificationInfo. 18655 getStatusStringFromValue(status); 18656 pw.println(prefix + "Status: " + statusStr); 18657 pw.println(); 18658 count++; 18659 } 18660 if (count == 0) { 18661 pw.println(prefix + "No configured app linkages."); 18662 pw.println(); 18663 } 18664 } 18665 } 18666 } 18667 } 18668 18669 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 18670 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 18671 if (packageName == null && permissionNames == null) { 18672 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 18673 if (iperm == 0) { 18674 if (dumpState.onTitlePrinted()) 18675 pw.println(); 18676 pw.println("AppOp Permissions:"); 18677 } 18678 pw.print(" AppOp Permission "); 18679 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 18680 pw.println(":"); 18681 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 18682 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 18683 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 18684 } 18685 } 18686 } 18687 } 18688 18689 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 18690 boolean printedSomething = false; 18691 for (PackageParser.Provider p : mProviders.mProviders.values()) { 18692 if (packageName != null && !packageName.equals(p.info.packageName)) { 18693 continue; 18694 } 18695 if (!printedSomething) { 18696 if (dumpState.onTitlePrinted()) 18697 pw.println(); 18698 pw.println("Registered ContentProviders:"); 18699 printedSomething = true; 18700 } 18701 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 18702 pw.print(" "); pw.println(p.toString()); 18703 } 18704 printedSomething = false; 18705 for (Map.Entry<String, PackageParser.Provider> entry : 18706 mProvidersByAuthority.entrySet()) { 18707 PackageParser.Provider p = entry.getValue(); 18708 if (packageName != null && !packageName.equals(p.info.packageName)) { 18709 continue; 18710 } 18711 if (!printedSomething) { 18712 if (dumpState.onTitlePrinted()) 18713 pw.println(); 18714 pw.println("ContentProvider Authorities:"); 18715 printedSomething = true; 18716 } 18717 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 18718 pw.print(" "); pw.println(p.toString()); 18719 if (p.info != null && p.info.applicationInfo != null) { 18720 final String appInfo = p.info.applicationInfo.toString(); 18721 pw.print(" applicationInfo="); pw.println(appInfo); 18722 } 18723 } 18724 } 18725 18726 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 18727 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 18728 } 18729 18730 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 18731 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 18732 } 18733 18734 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 18735 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 18736 } 18737 18738 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 18739 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 18740 } 18741 18742 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 18743 // XXX should handle packageName != null by dumping only install data that 18744 // the given package is involved with. 18745 if (dumpState.onTitlePrinted()) pw.println(); 18746 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 18747 } 18748 18749 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 18750 // XXX should handle packageName != null by dumping only install data that 18751 // the given package is involved with. 18752 if (dumpState.onTitlePrinted()) pw.println(); 18753 18754 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18755 ipw.println(); 18756 ipw.println("Frozen packages:"); 18757 ipw.increaseIndent(); 18758 if (mFrozenPackages.size() == 0) { 18759 ipw.println("(none)"); 18760 } else { 18761 for (int i = 0; i < mFrozenPackages.size(); i++) { 18762 ipw.println(mFrozenPackages.valueAt(i)); 18763 } 18764 } 18765 ipw.decreaseIndent(); 18766 } 18767 18768 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 18769 if (dumpState.onTitlePrinted()) pw.println(); 18770 dumpDexoptStateLPr(pw, packageName); 18771 } 18772 18773 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 18774 if (dumpState.onTitlePrinted()) pw.println(); 18775 mSettings.dumpReadMessagesLPr(pw, dumpState); 18776 18777 pw.println(); 18778 pw.println("Package warning messages:"); 18779 BufferedReader in = null; 18780 String line = null; 18781 try { 18782 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18783 while ((line = in.readLine()) != null) { 18784 if (line.contains("ignored: updated version")) continue; 18785 pw.println(line); 18786 } 18787 } catch (IOException ignored) { 18788 } finally { 18789 IoUtils.closeQuietly(in); 18790 } 18791 } 18792 18793 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 18794 BufferedReader in = null; 18795 String line = null; 18796 try { 18797 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18798 while ((line = in.readLine()) != null) { 18799 if (line.contains("ignored: updated version")) continue; 18800 pw.print("msg,"); 18801 pw.println(line); 18802 } 18803 } catch (IOException ignored) { 18804 } finally { 18805 IoUtils.closeQuietly(in); 18806 } 18807 } 18808 } 18809 } 18810 18811 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 18812 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18813 ipw.println(); 18814 ipw.println("Dexopt state:"); 18815 ipw.increaseIndent(); 18816 Collection<PackageParser.Package> packages = null; 18817 if (packageName != null) { 18818 PackageParser.Package targetPackage = mPackages.get(packageName); 18819 if (targetPackage != null) { 18820 packages = Collections.singletonList(targetPackage); 18821 } else { 18822 ipw.println("Unable to find package: " + packageName); 18823 return; 18824 } 18825 } else { 18826 packages = mPackages.values(); 18827 } 18828 18829 for (PackageParser.Package pkg : packages) { 18830 ipw.println("[" + pkg.packageName + "]"); 18831 ipw.increaseIndent(); 18832 mPackageDexOptimizer.dumpDexoptState(ipw, pkg); 18833 ipw.decreaseIndent(); 18834 } 18835 } 18836 18837 private String dumpDomainString(String packageName) { 18838 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 18839 .getList(); 18840 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 18841 18842 ArraySet<String> result = new ArraySet<>(); 18843 if (iviList.size() > 0) { 18844 for (IntentFilterVerificationInfo ivi : iviList) { 18845 for (String host : ivi.getDomains()) { 18846 result.add(host); 18847 } 18848 } 18849 } 18850 if (filters != null && filters.size() > 0) { 18851 for (IntentFilter filter : filters) { 18852 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 18853 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 18854 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 18855 result.addAll(filter.getHostsList()); 18856 } 18857 } 18858 } 18859 18860 StringBuilder sb = new StringBuilder(result.size() * 16); 18861 for (String domain : result) { 18862 if (sb.length() > 0) sb.append(" "); 18863 sb.append(domain); 18864 } 18865 return sb.toString(); 18866 } 18867 18868 // ------- apps on sdcard specific code ------- 18869 static final boolean DEBUG_SD_INSTALL = false; 18870 18871 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 18872 18873 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 18874 18875 private boolean mMediaMounted = false; 18876 18877 static String getEncryptKey() { 18878 try { 18879 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 18880 SD_ENCRYPTION_KEYSTORE_NAME); 18881 if (sdEncKey == null) { 18882 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 18883 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 18884 if (sdEncKey == null) { 18885 Slog.e(TAG, "Failed to create encryption keys"); 18886 return null; 18887 } 18888 } 18889 return sdEncKey; 18890 } catch (NoSuchAlgorithmException nsae) { 18891 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 18892 return null; 18893 } catch (IOException ioe) { 18894 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 18895 return null; 18896 } 18897 } 18898 18899 /* 18900 * Update media status on PackageManager. 18901 */ 18902 @Override 18903 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 18904 int callingUid = Binder.getCallingUid(); 18905 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 18906 throw new SecurityException("Media status can only be updated by the system"); 18907 } 18908 // reader; this apparently protects mMediaMounted, but should probably 18909 // be a different lock in that case. 18910 synchronized (mPackages) { 18911 Log.i(TAG, "Updating external media status from " 18912 + (mMediaMounted ? "mounted" : "unmounted") + " to " 18913 + (mediaStatus ? "mounted" : "unmounted")); 18914 if (DEBUG_SD_INSTALL) 18915 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 18916 + ", mMediaMounted=" + mMediaMounted); 18917 if (mediaStatus == mMediaMounted) { 18918 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 18919 : 0, -1); 18920 mHandler.sendMessage(msg); 18921 return; 18922 } 18923 mMediaMounted = mediaStatus; 18924 } 18925 // Queue up an async operation since the package installation may take a 18926 // little while. 18927 mHandler.post(new Runnable() { 18928 public void run() { 18929 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 18930 } 18931 }); 18932 } 18933 18934 /** 18935 * Called by MountService when the initial ASECs to scan are available. 18936 * Should block until all the ASEC containers are finished being scanned. 18937 */ 18938 public void scanAvailableAsecs() { 18939 updateExternalMediaStatusInner(true, false, false); 18940 } 18941 18942 /* 18943 * Collect information of applications on external media, map them against 18944 * existing containers and update information based on current mount status. 18945 * Please note that we always have to report status if reportStatus has been 18946 * set to true especially when unloading packages. 18947 */ 18948 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 18949 boolean externalStorage) { 18950 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 18951 int[] uidArr = EmptyArray.INT; 18952 18953 final String[] list = PackageHelper.getSecureContainerList(); 18954 if (ArrayUtils.isEmpty(list)) { 18955 Log.i(TAG, "No secure containers found"); 18956 } else { 18957 // Process list of secure containers and categorize them 18958 // as active or stale based on their package internal state. 18959 18960 // reader 18961 synchronized (mPackages) { 18962 for (String cid : list) { 18963 // Leave stages untouched for now; installer service owns them 18964 if (PackageInstallerService.isStageName(cid)) continue; 18965 18966 if (DEBUG_SD_INSTALL) 18967 Log.i(TAG, "Processing container " + cid); 18968 String pkgName = getAsecPackageName(cid); 18969 if (pkgName == null) { 18970 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 18971 continue; 18972 } 18973 if (DEBUG_SD_INSTALL) 18974 Log.i(TAG, "Looking for pkg : " + pkgName); 18975 18976 final PackageSetting ps = mSettings.mPackages.get(pkgName); 18977 if (ps == null) { 18978 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 18979 continue; 18980 } 18981 18982 /* 18983 * Skip packages that are not external if we're unmounting 18984 * external storage. 18985 */ 18986 if (externalStorage && !isMounted && !isExternal(ps)) { 18987 continue; 18988 } 18989 18990 final AsecInstallArgs args = new AsecInstallArgs(cid, 18991 getAppDexInstructionSets(ps), ps.isForwardLocked()); 18992 // The package status is changed only if the code path 18993 // matches between settings and the container id. 18994 if (ps.codePathString != null 18995 && ps.codePathString.startsWith(args.getCodePath())) { 18996 if (DEBUG_SD_INSTALL) { 18997 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 18998 + " at code path: " + ps.codePathString); 18999 } 19000 19001 // We do have a valid package installed on sdcard 19002 processCids.put(args, ps.codePathString); 19003 final int uid = ps.appId; 19004 if (uid != -1) { 19005 uidArr = ArrayUtils.appendInt(uidArr, uid); 19006 } 19007 } else { 19008 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 19009 + ps.codePathString); 19010 } 19011 } 19012 } 19013 19014 Arrays.sort(uidArr); 19015 } 19016 19017 // Process packages with valid entries. 19018 if (isMounted) { 19019 if (DEBUG_SD_INSTALL) 19020 Log.i(TAG, "Loading packages"); 19021 loadMediaPackages(processCids, uidArr, externalStorage); 19022 startCleaningPackages(); 19023 mInstallerService.onSecureContainersAvailable(); 19024 } else { 19025 if (DEBUG_SD_INSTALL) 19026 Log.i(TAG, "Unloading packages"); 19027 unloadMediaPackages(processCids, uidArr, reportStatus); 19028 } 19029 } 19030 19031 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19032 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 19033 final int size = infos.size(); 19034 final String[] packageNames = new String[size]; 19035 final int[] packageUids = new int[size]; 19036 for (int i = 0; i < size; i++) { 19037 final ApplicationInfo info = infos.get(i); 19038 packageNames[i] = info.packageName; 19039 packageUids[i] = info.uid; 19040 } 19041 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 19042 finishedReceiver); 19043 } 19044 19045 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19046 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 19047 sendResourcesChangedBroadcast(mediaStatus, replacing, 19048 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 19049 } 19050 19051 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19052 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 19053 int size = pkgList.length; 19054 if (size > 0) { 19055 // Send broadcasts here 19056 Bundle extras = new Bundle(); 19057 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 19058 if (uidArr != null) { 19059 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 19060 } 19061 if (replacing) { 19062 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 19063 } 19064 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 19065 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 19066 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 19067 } 19068 } 19069 19070 /* 19071 * Look at potentially valid container ids from processCids If package 19072 * information doesn't match the one on record or package scanning fails, 19073 * the cid is added to list of removeCids. We currently don't delete stale 19074 * containers. 19075 */ 19076 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 19077 boolean externalStorage) { 19078 ArrayList<String> pkgList = new ArrayList<String>(); 19079 Set<AsecInstallArgs> keys = processCids.keySet(); 19080 19081 for (AsecInstallArgs args : keys) { 19082 String codePath = processCids.get(args); 19083 if (DEBUG_SD_INSTALL) 19084 Log.i(TAG, "Loading container : " + args.cid); 19085 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 19086 try { 19087 // Make sure there are no container errors first. 19088 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 19089 Slog.e(TAG, "Failed to mount cid : " + args.cid 19090 + " when installing from sdcard"); 19091 continue; 19092 } 19093 // Check code path here. 19094 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 19095 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 19096 + " does not match one in settings " + codePath); 19097 continue; 19098 } 19099 // Parse package 19100 int parseFlags = mDefParseFlags; 19101 if (args.isExternalAsec()) { 19102 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 19103 } 19104 if (args.isFwdLocked()) { 19105 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 19106 } 19107 19108 synchronized (mInstallLock) { 19109 PackageParser.Package pkg = null; 19110 try { 19111 // Sadly we don't know the package name yet to freeze it 19112 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 19113 SCAN_IGNORE_FROZEN, 0, null); 19114 } catch (PackageManagerException e) { 19115 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 19116 } 19117 // Scan the package 19118 if (pkg != null) { 19119 /* 19120 * TODO why is the lock being held? doPostInstall is 19121 * called in other places without the lock. This needs 19122 * to be straightened out. 19123 */ 19124 // writer 19125 synchronized (mPackages) { 19126 retCode = PackageManager.INSTALL_SUCCEEDED; 19127 pkgList.add(pkg.packageName); 19128 // Post process args 19129 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 19130 pkg.applicationInfo.uid); 19131 } 19132 } else { 19133 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 19134 } 19135 } 19136 19137 } finally { 19138 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 19139 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 19140 } 19141 } 19142 } 19143 // writer 19144 synchronized (mPackages) { 19145 // If the platform SDK has changed since the last time we booted, 19146 // we need to re-grant app permission to catch any new ones that 19147 // appear. This is really a hack, and means that apps can in some 19148 // cases get permissions that the user didn't initially explicitly 19149 // allow... it would be nice to have some better way to handle 19150 // this situation. 19151 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 19152 : mSettings.getInternalVersion(); 19153 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 19154 : StorageManager.UUID_PRIVATE_INTERNAL; 19155 19156 int updateFlags = UPDATE_PERMISSIONS_ALL; 19157 if (ver.sdkVersion != mSdkVersion) { 19158 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19159 + mSdkVersion + "; regranting permissions for external"); 19160 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19161 } 19162 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19163 19164 // Yay, everything is now upgraded 19165 ver.forceCurrent(); 19166 19167 // can downgrade to reader 19168 // Persist settings 19169 mSettings.writeLPr(); 19170 } 19171 // Send a broadcast to let everyone know we are done processing 19172 if (pkgList.size() > 0) { 19173 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 19174 } 19175 } 19176 19177 /* 19178 * Utility method to unload a list of specified containers 19179 */ 19180 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 19181 // Just unmount all valid containers. 19182 for (AsecInstallArgs arg : cidArgs) { 19183 synchronized (mInstallLock) { 19184 arg.doPostDeleteLI(false); 19185 } 19186 } 19187 } 19188 19189 /* 19190 * Unload packages mounted on external media. This involves deleting package 19191 * data from internal structures, sending broadcasts about disabled packages, 19192 * gc'ing to free up references, unmounting all secure containers 19193 * corresponding to packages on external media, and posting a 19194 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 19195 * that we always have to post this message if status has been requested no 19196 * matter what. 19197 */ 19198 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 19199 final boolean reportStatus) { 19200 if (DEBUG_SD_INSTALL) 19201 Log.i(TAG, "unloading media packages"); 19202 ArrayList<String> pkgList = new ArrayList<String>(); 19203 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 19204 final Set<AsecInstallArgs> keys = processCids.keySet(); 19205 for (AsecInstallArgs args : keys) { 19206 String pkgName = args.getPackageName(); 19207 if (DEBUG_SD_INSTALL) 19208 Log.i(TAG, "Trying to unload pkg : " + pkgName); 19209 // Delete package internally 19210 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19211 synchronized (mInstallLock) { 19212 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19213 final boolean res; 19214 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 19215 "unloadMediaPackages")) { 19216 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 19217 null); 19218 } 19219 if (res) { 19220 pkgList.add(pkgName); 19221 } else { 19222 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 19223 failedList.add(args); 19224 } 19225 } 19226 } 19227 19228 // reader 19229 synchronized (mPackages) { 19230 // We didn't update the settings after removing each package; 19231 // write them now for all packages. 19232 mSettings.writeLPr(); 19233 } 19234 19235 // We have to absolutely send UPDATED_MEDIA_STATUS only 19236 // after confirming that all the receivers processed the ordered 19237 // broadcast when packages get disabled, force a gc to clean things up. 19238 // and unload all the containers. 19239 if (pkgList.size() > 0) { 19240 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 19241 new IIntentReceiver.Stub() { 19242 public void performReceive(Intent intent, int resultCode, String data, 19243 Bundle extras, boolean ordered, boolean sticky, 19244 int sendingUser) throws RemoteException { 19245 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 19246 reportStatus ? 1 : 0, 1, keys); 19247 mHandler.sendMessage(msg); 19248 } 19249 }); 19250 } else { 19251 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 19252 keys); 19253 mHandler.sendMessage(msg); 19254 } 19255 } 19256 19257 private void loadPrivatePackages(final VolumeInfo vol) { 19258 mHandler.post(new Runnable() { 19259 @Override 19260 public void run() { 19261 loadPrivatePackagesInner(vol); 19262 } 19263 }); 19264 } 19265 19266 private void loadPrivatePackagesInner(VolumeInfo vol) { 19267 final String volumeUuid = vol.fsUuid; 19268 if (TextUtils.isEmpty(volumeUuid)) { 19269 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 19270 return; 19271 } 19272 19273 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 19274 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 19275 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 19276 19277 final VersionInfo ver; 19278 final List<PackageSetting> packages; 19279 synchronized (mPackages) { 19280 ver = mSettings.findOrCreateVersion(volumeUuid); 19281 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19282 } 19283 19284 for (PackageSetting ps : packages) { 19285 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 19286 synchronized (mInstallLock) { 19287 final PackageParser.Package pkg; 19288 try { 19289 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 19290 loaded.add(pkg.applicationInfo); 19291 19292 } catch (PackageManagerException e) { 19293 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 19294 } 19295 19296 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 19297 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 19298 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 19299 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 19300 } 19301 } 19302 } 19303 19304 // Reconcile app data for all started/unlocked users 19305 final StorageManager sm = mContext.getSystemService(StorageManager.class); 19306 final UserManager um = mContext.getSystemService(UserManager.class); 19307 UserManagerInternal umInternal = getUserManagerInternal(); 19308 for (UserInfo user : um.getUsers()) { 19309 final int flags; 19310 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 19311 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19312 } else if (umInternal.isUserRunning(user.id)) { 19313 flags = StorageManager.FLAG_STORAGE_DE; 19314 } else { 19315 continue; 19316 } 19317 19318 try { 19319 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 19320 synchronized (mInstallLock) { 19321 reconcileAppsDataLI(volumeUuid, user.id, flags); 19322 } 19323 } catch (IllegalStateException e) { 19324 // Device was probably ejected, and we'll process that event momentarily 19325 Slog.w(TAG, "Failed to prepare storage: " + e); 19326 } 19327 } 19328 19329 synchronized (mPackages) { 19330 int updateFlags = UPDATE_PERMISSIONS_ALL; 19331 if (ver.sdkVersion != mSdkVersion) { 19332 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19333 + mSdkVersion + "; regranting permissions for " + volumeUuid); 19334 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19335 } 19336 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19337 19338 // Yay, everything is now upgraded 19339 ver.forceCurrent(); 19340 19341 mSettings.writeLPr(); 19342 } 19343 19344 for (PackageFreezer freezer : freezers) { 19345 freezer.close(); 19346 } 19347 19348 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 19349 sendResourcesChangedBroadcast(true, false, loaded, null); 19350 } 19351 19352 private void unloadPrivatePackages(final VolumeInfo vol) { 19353 mHandler.post(new Runnable() { 19354 @Override 19355 public void run() { 19356 unloadPrivatePackagesInner(vol); 19357 } 19358 }); 19359 } 19360 19361 private void unloadPrivatePackagesInner(VolumeInfo vol) { 19362 final String volumeUuid = vol.fsUuid; 19363 if (TextUtils.isEmpty(volumeUuid)) { 19364 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 19365 return; 19366 } 19367 19368 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 19369 synchronized (mInstallLock) { 19370 synchronized (mPackages) { 19371 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 19372 for (PackageSetting ps : packages) { 19373 if (ps.pkg == null) continue; 19374 19375 final ApplicationInfo info = ps.pkg.applicationInfo; 19376 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19377 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19378 19379 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 19380 "unloadPrivatePackagesInner")) { 19381 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 19382 false, null)) { 19383 unloaded.add(info); 19384 } else { 19385 Slog.w(TAG, "Failed to unload " + ps.codePath); 19386 } 19387 } 19388 19389 // Try very hard to release any references to this package 19390 // so we don't risk the system server being killed due to 19391 // open FDs 19392 AttributeCache.instance().removePackage(ps.name); 19393 } 19394 19395 mSettings.writeLPr(); 19396 } 19397 } 19398 19399 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 19400 sendResourcesChangedBroadcast(false, false, unloaded, null); 19401 19402 // Try very hard to release any references to this path so we don't risk 19403 // the system server being killed due to open FDs 19404 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 19405 19406 for (int i = 0; i < 3; i++) { 19407 System.gc(); 19408 System.runFinalization(); 19409 } 19410 } 19411 19412 /** 19413 * Prepare storage areas for given user on all mounted devices. 19414 */ 19415 void prepareUserData(int userId, int userSerial, int flags) { 19416 synchronized (mInstallLock) { 19417 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19418 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19419 final String volumeUuid = vol.getFsUuid(); 19420 prepareUserDataLI(volumeUuid, userId, userSerial, flags, true); 19421 } 19422 } 19423 } 19424 19425 private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags, 19426 boolean allowRecover) { 19427 // Prepare storage and verify that serial numbers are consistent; if 19428 // there's a mismatch we need to destroy to avoid leaking data 19429 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19430 try { 19431 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags); 19432 19433 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) { 19434 UserManagerService.enforceSerialNumber( 19435 Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial); 19436 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19437 UserManagerService.enforceSerialNumber( 19438 Environment.getDataSystemDeDirectory(userId), userSerial); 19439 } 19440 } 19441 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) { 19442 UserManagerService.enforceSerialNumber( 19443 Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial); 19444 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19445 UserManagerService.enforceSerialNumber( 19446 Environment.getDataSystemCeDirectory(userId), userSerial); 19447 } 19448 } 19449 19450 synchronized (mInstallLock) { 19451 mInstaller.createUserData(volumeUuid, userId, userSerial, flags); 19452 } 19453 } catch (Exception e) { 19454 logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid 19455 + " because we failed to prepare: " + e); 19456 destroyUserDataLI(volumeUuid, userId, 19457 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19458 19459 if (allowRecover) { 19460 // Try one last time; if we fail again we're really in trouble 19461 prepareUserDataLI(volumeUuid, userId, userSerial, flags, false); 19462 } 19463 } 19464 } 19465 19466 /** 19467 * Destroy storage areas for given user on all mounted devices. 19468 */ 19469 void destroyUserData(int userId, int flags) { 19470 synchronized (mInstallLock) { 19471 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19472 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19473 final String volumeUuid = vol.getFsUuid(); 19474 destroyUserDataLI(volumeUuid, userId, flags); 19475 } 19476 } 19477 } 19478 19479 private void destroyUserDataLI(String volumeUuid, int userId, int flags) { 19480 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19481 try { 19482 // Clean up app data, profile data, and media data 19483 mInstaller.destroyUserData(volumeUuid, userId, flags); 19484 19485 // Clean up system data 19486 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19487 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19488 FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId)); 19489 FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId)); 19490 } 19491 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19492 FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId)); 19493 } 19494 } 19495 19496 // Data with special labels is now gone, so finish the job 19497 storage.destroyUserStorage(volumeUuid, userId, flags); 19498 19499 } catch (Exception e) { 19500 logCriticalInfo(Log.WARN, 19501 "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e); 19502 } 19503 } 19504 19505 /** 19506 * Examine all users present on given mounted volume, and destroy data 19507 * belonging to users that are no longer valid, or whose user ID has been 19508 * recycled. 19509 */ 19510 private void reconcileUsers(String volumeUuid) { 19511 final List<File> files = new ArrayList<>(); 19512 Collections.addAll(files, FileUtils 19513 .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid))); 19514 Collections.addAll(files, FileUtils 19515 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid))); 19516 Collections.addAll(files, FileUtils 19517 .listFilesOrEmpty(Environment.getDataSystemDeDirectory())); 19518 Collections.addAll(files, FileUtils 19519 .listFilesOrEmpty(Environment.getDataSystemCeDirectory())); 19520 for (File file : files) { 19521 if (!file.isDirectory()) continue; 19522 19523 final int userId; 19524 final UserInfo info; 19525 try { 19526 userId = Integer.parseInt(file.getName()); 19527 info = sUserManager.getUserInfo(userId); 19528 } catch (NumberFormatException e) { 19529 Slog.w(TAG, "Invalid user directory " + file); 19530 continue; 19531 } 19532 19533 boolean destroyUser = false; 19534 if (info == null) { 19535 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19536 + " because no matching user was found"); 19537 destroyUser = true; 19538 } else if (!mOnlyCore) { 19539 try { 19540 UserManagerService.enforceSerialNumber(file, info.serialNumber); 19541 } catch (IOException e) { 19542 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19543 + " because we failed to enforce serial number: " + e); 19544 destroyUser = true; 19545 } 19546 } 19547 19548 if (destroyUser) { 19549 synchronized (mInstallLock) { 19550 destroyUserDataLI(volumeUuid, userId, 19551 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19552 } 19553 } 19554 } 19555 } 19556 19557 private void assertPackageKnown(String volumeUuid, String packageName) 19558 throws PackageManagerException { 19559 synchronized (mPackages) { 19560 final PackageSetting ps = mSettings.mPackages.get(packageName); 19561 if (ps == null) { 19562 throw new PackageManagerException("Package " + packageName + " is unknown"); 19563 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19564 throw new PackageManagerException( 19565 "Package " + packageName + " found on unknown volume " + volumeUuid 19566 + "; expected volume " + ps.volumeUuid); 19567 } 19568 } 19569 } 19570 19571 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 19572 throws PackageManagerException { 19573 synchronized (mPackages) { 19574 final PackageSetting ps = mSettings.mPackages.get(packageName); 19575 if (ps == null) { 19576 throw new PackageManagerException("Package " + packageName + " is unknown"); 19577 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19578 throw new PackageManagerException( 19579 "Package " + packageName + " found on unknown volume " + volumeUuid 19580 + "; expected volume " + ps.volumeUuid); 19581 } else if (!ps.getInstalled(userId)) { 19582 throw new PackageManagerException( 19583 "Package " + packageName + " not installed for user " + userId); 19584 } 19585 } 19586 } 19587 19588 /** 19589 * Examine all apps present on given mounted volume, and destroy apps that 19590 * aren't expected, either due to uninstallation or reinstallation on 19591 * another volume. 19592 */ 19593 private void reconcileApps(String volumeUuid) { 19594 final File[] files = FileUtils 19595 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 19596 for (File file : files) { 19597 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 19598 && !PackageInstallerService.isStageName(file.getName()); 19599 if (!isPackage) { 19600 // Ignore entries which are not packages 19601 continue; 19602 } 19603 19604 try { 19605 final PackageLite pkg = PackageParser.parsePackageLite(file, 19606 PackageParser.PARSE_MUST_BE_APK); 19607 assertPackageKnown(volumeUuid, pkg.packageName); 19608 19609 } catch (PackageParserException | PackageManagerException e) { 19610 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19611 synchronized (mInstallLock) { 19612 removeCodePathLI(file); 19613 } 19614 } 19615 } 19616 } 19617 19618 /** 19619 * Reconcile all app data for the given user. 19620 * <p> 19621 * Verifies that directories exist and that ownership and labeling is 19622 * correct for all installed apps on all mounted volumes. 19623 */ 19624 void reconcileAppsData(int userId, int flags) { 19625 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19626 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19627 final String volumeUuid = vol.getFsUuid(); 19628 synchronized (mInstallLock) { 19629 reconcileAppsDataLI(volumeUuid, userId, flags); 19630 } 19631 } 19632 } 19633 19634 /** 19635 * Reconcile all app data on given mounted volume. 19636 * <p> 19637 * Destroys app data that isn't expected, either due to uninstallation or 19638 * reinstallation on another volume. 19639 * <p> 19640 * Verifies that directories exist and that ownership and labeling is 19641 * correct for all installed apps. 19642 */ 19643 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) { 19644 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 19645 + Integer.toHexString(flags)); 19646 19647 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 19648 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 19649 19650 boolean restoreconNeeded = false; 19651 19652 // First look for stale data that doesn't belong, and check if things 19653 // have changed since we did our last restorecon 19654 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19655 if (StorageManager.isFileEncryptedNativeOrEmulated() 19656 && !StorageManager.isUserKeyUnlocked(userId)) { 19657 throw new RuntimeException( 19658 "Yikes, someone asked us to reconcile CE storage while " + userId 19659 + " was still locked; this would have caused massive data loss!"); 19660 } 19661 19662 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 19663 19664 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 19665 for (File file : files) { 19666 final String packageName = file.getName(); 19667 try { 19668 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19669 } catch (PackageManagerException e) { 19670 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19671 try { 19672 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19673 StorageManager.FLAG_STORAGE_CE, 0); 19674 } catch (InstallerException e2) { 19675 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19676 } 19677 } 19678 } 19679 } 19680 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19681 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 19682 19683 final File[] files = FileUtils.listFilesOrEmpty(deDir); 19684 for (File file : files) { 19685 final String packageName = file.getName(); 19686 try { 19687 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19688 } catch (PackageManagerException e) { 19689 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19690 try { 19691 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19692 StorageManager.FLAG_STORAGE_DE, 0); 19693 } catch (InstallerException e2) { 19694 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19695 } 19696 } 19697 } 19698 } 19699 19700 // Ensure that data directories are ready to roll for all packages 19701 // installed for this volume and user 19702 final List<PackageSetting> packages; 19703 synchronized (mPackages) { 19704 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19705 } 19706 int preparedCount = 0; 19707 for (PackageSetting ps : packages) { 19708 final String packageName = ps.name; 19709 if (ps.pkg == null) { 19710 Slog.w(TAG, "Odd, missing scanned package " + packageName); 19711 // TODO: might be due to legacy ASEC apps; we should circle back 19712 // and reconcile again once they're scanned 19713 continue; 19714 } 19715 19716 if (ps.getInstalled(userId)) { 19717 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19718 19719 if (maybeMigrateAppDataLIF(ps.pkg, userId)) { 19720 // We may have just shuffled around app data directories, so 19721 // prepare them one more time 19722 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19723 } 19724 19725 preparedCount++; 19726 } 19727 } 19728 19729 if (restoreconNeeded) { 19730 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19731 SELinuxMMAC.setRestoreconDone(ceDir); 19732 } 19733 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19734 SELinuxMMAC.setRestoreconDone(deDir); 19735 } 19736 } 19737 19738 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 19739 + " packages; restoreconNeeded was " + restoreconNeeded); 19740 } 19741 19742 /** 19743 * Prepare app data for the given app just after it was installed or 19744 * upgraded. This method carefully only touches users that it's installed 19745 * for, and it forces a restorecon to handle any seinfo changes. 19746 * <p> 19747 * Verifies that directories exist and that ownership and labeling is 19748 * correct for all installed apps. If there is an ownership mismatch, it 19749 * will try recovering system apps by wiping data; third-party app data is 19750 * left intact. 19751 * <p> 19752 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 19753 */ 19754 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 19755 final PackageSetting ps; 19756 synchronized (mPackages) { 19757 ps = mSettings.mPackages.get(pkg.packageName); 19758 mSettings.writeKernelMappingLPr(ps); 19759 } 19760 19761 final UserManager um = mContext.getSystemService(UserManager.class); 19762 UserManagerInternal umInternal = getUserManagerInternal(); 19763 for (UserInfo user : um.getUsers()) { 19764 final int flags; 19765 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 19766 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19767 } else if (umInternal.isUserRunning(user.id)) { 19768 flags = StorageManager.FLAG_STORAGE_DE; 19769 } else { 19770 continue; 19771 } 19772 19773 if (ps.getInstalled(user.id)) { 19774 // Whenever an app changes, force a restorecon of its data 19775 // TODO: when user data is locked, mark that we're still dirty 19776 prepareAppDataLIF(pkg, user.id, flags, true); 19777 } 19778 } 19779 } 19780 19781 /** 19782 * Prepare app data for the given app. 19783 * <p> 19784 * Verifies that directories exist and that ownership and labeling is 19785 * correct for all installed apps. If there is an ownership mismatch, this 19786 * will try recovering system apps by wiping data; third-party app data is 19787 * left intact. 19788 */ 19789 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags, 19790 boolean restoreconNeeded) { 19791 if (pkg == null) { 19792 Slog.wtf(TAG, "Package was null!", new Throwable()); 19793 return; 19794 } 19795 prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded); 19796 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19797 for (int i = 0; i < childCount; i++) { 19798 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded); 19799 } 19800 } 19801 19802 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags, 19803 boolean restoreconNeeded) { 19804 if (DEBUG_APP_DATA) { 19805 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 19806 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 19807 } 19808 19809 final String volumeUuid = pkg.volumeUuid; 19810 final String packageName = pkg.packageName; 19811 final ApplicationInfo app = pkg.applicationInfo; 19812 final int appId = UserHandle.getAppId(app.uid); 19813 19814 Preconditions.checkNotNull(app.seinfo); 19815 19816 try { 19817 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19818 appId, app.seinfo, app.targetSdkVersion); 19819 } catch (InstallerException e) { 19820 if (app.isSystemApp()) { 19821 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 19822 + ", but trying to recover: " + e); 19823 destroyAppDataLeafLIF(pkg, userId, flags); 19824 try { 19825 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19826 appId, app.seinfo, app.targetSdkVersion); 19827 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 19828 } catch (InstallerException e2) { 19829 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 19830 } 19831 } else { 19832 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 19833 } 19834 } 19835 19836 if (restoreconNeeded) { 19837 try { 19838 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, 19839 app.seinfo); 19840 } catch (InstallerException e) { 19841 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 19842 } 19843 } 19844 19845 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19846 try { 19847 // CE storage is unlocked right now, so read out the inode and 19848 // remember for use later when it's locked 19849 // TODO: mark this structure as dirty so we persist it! 19850 final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId, 19851 StorageManager.FLAG_STORAGE_CE); 19852 synchronized (mPackages) { 19853 final PackageSetting ps = mSettings.mPackages.get(packageName); 19854 if (ps != null) { 19855 ps.setCeDataInode(ceDataInode, userId); 19856 } 19857 } 19858 } catch (InstallerException e) { 19859 Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e); 19860 } 19861 } 19862 19863 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19864 } 19865 19866 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 19867 if (pkg == null) { 19868 Slog.wtf(TAG, "Package was null!", new Throwable()); 19869 return; 19870 } 19871 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19872 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19873 for (int i = 0; i < childCount; i++) { 19874 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 19875 } 19876 } 19877 19878 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 19879 final String volumeUuid = pkg.volumeUuid; 19880 final String packageName = pkg.packageName; 19881 final ApplicationInfo app = pkg.applicationInfo; 19882 19883 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19884 // Create a native library symlink only if we have native libraries 19885 // and if the native libraries are 32 bit libraries. We do not provide 19886 // this symlink for 64 bit libraries. 19887 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 19888 final String nativeLibPath = app.nativeLibraryDir; 19889 try { 19890 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 19891 nativeLibPath, userId); 19892 } catch (InstallerException e) { 19893 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 19894 } 19895 } 19896 } 19897 } 19898 19899 /** 19900 * For system apps on non-FBE devices, this method migrates any existing 19901 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 19902 * requested by the app. 19903 */ 19904 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 19905 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 19906 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 19907 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 19908 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 19909 try { 19910 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 19911 storageTarget); 19912 } catch (InstallerException e) { 19913 logCriticalInfo(Log.WARN, 19914 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 19915 } 19916 return true; 19917 } else { 19918 return false; 19919 } 19920 } 19921 19922 public PackageFreezer freezePackage(String packageName, String killReason) { 19923 return freezePackage(packageName, UserHandle.USER_ALL, killReason); 19924 } 19925 19926 public PackageFreezer freezePackage(String packageName, int userId, String killReason) { 19927 return new PackageFreezer(packageName, userId, killReason); 19928 } 19929 19930 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 19931 String killReason) { 19932 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason); 19933 } 19934 19935 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags, 19936 String killReason) { 19937 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 19938 return new PackageFreezer(); 19939 } else { 19940 return freezePackage(packageName, userId, killReason); 19941 } 19942 } 19943 19944 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 19945 String killReason) { 19946 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason); 19947 } 19948 19949 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags, 19950 String killReason) { 19951 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 19952 return new PackageFreezer(); 19953 } else { 19954 return freezePackage(packageName, userId, killReason); 19955 } 19956 } 19957 19958 /** 19959 * Class that freezes and kills the given package upon creation, and 19960 * unfreezes it upon closing. This is typically used when doing surgery on 19961 * app code/data to prevent the app from running while you're working. 19962 */ 19963 private class PackageFreezer implements AutoCloseable { 19964 private final String mPackageName; 19965 private final PackageFreezer[] mChildren; 19966 19967 private final boolean mWeFroze; 19968 19969 private final AtomicBoolean mClosed = new AtomicBoolean(); 19970 private final CloseGuard mCloseGuard = CloseGuard.get(); 19971 19972 /** 19973 * Create and return a stub freezer that doesn't actually do anything, 19974 * typically used when someone requested 19975 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 19976 * {@link PackageManager#DELETE_DONT_KILL_APP}. 19977 */ 19978 public PackageFreezer() { 19979 mPackageName = null; 19980 mChildren = null; 19981 mWeFroze = false; 19982 mCloseGuard.open("close"); 19983 } 19984 19985 public PackageFreezer(String packageName, int userId, String killReason) { 19986 synchronized (mPackages) { 19987 mPackageName = packageName; 19988 mWeFroze = mFrozenPackages.add(mPackageName); 19989 19990 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 19991 if (ps != null) { 19992 killApplication(ps.name, ps.appId, userId, killReason); 19993 } 19994 19995 final PackageParser.Package p = mPackages.get(packageName); 19996 if (p != null && p.childPackages != null) { 19997 final int N = p.childPackages.size(); 19998 mChildren = new PackageFreezer[N]; 19999 for (int i = 0; i < N; i++) { 20000 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 20001 userId, killReason); 20002 } 20003 } else { 20004 mChildren = null; 20005 } 20006 } 20007 mCloseGuard.open("close"); 20008 } 20009 20010 @Override 20011 protected void finalize() throws Throwable { 20012 try { 20013 mCloseGuard.warnIfOpen(); 20014 close(); 20015 } finally { 20016 super.finalize(); 20017 } 20018 } 20019 20020 @Override 20021 public void close() { 20022 mCloseGuard.close(); 20023 if (mClosed.compareAndSet(false, true)) { 20024 synchronized (mPackages) { 20025 if (mWeFroze) { 20026 mFrozenPackages.remove(mPackageName); 20027 } 20028 20029 if (mChildren != null) { 20030 for (PackageFreezer freezer : mChildren) { 20031 freezer.close(); 20032 } 20033 } 20034 } 20035 } 20036 } 20037 } 20038 20039 /** 20040 * Verify that given package is currently frozen. 20041 */ 20042 private void checkPackageFrozen(String packageName) { 20043 synchronized (mPackages) { 20044 if (!mFrozenPackages.contains(packageName)) { 20045 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 20046 } 20047 } 20048 } 20049 20050 @Override 20051 public int movePackage(final String packageName, final String volumeUuid) { 20052 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 20053 20054 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 20055 final int moveId = mNextMoveId.getAndIncrement(); 20056 mHandler.post(new Runnable() { 20057 @Override 20058 public void run() { 20059 try { 20060 movePackageInternal(packageName, volumeUuid, moveId, user); 20061 } catch (PackageManagerException e) { 20062 Slog.w(TAG, "Failed to move " + packageName, e); 20063 mMoveCallbacks.notifyStatusChanged(moveId, 20064 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 20065 } 20066 } 20067 }); 20068 return moveId; 20069 } 20070 20071 private void movePackageInternal(final String packageName, final String volumeUuid, 20072 final int moveId, UserHandle user) throws PackageManagerException { 20073 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20074 final PackageManager pm = mContext.getPackageManager(); 20075 20076 final boolean currentAsec; 20077 final String currentVolumeUuid; 20078 final File codeFile; 20079 final String installerPackageName; 20080 final String packageAbiOverride; 20081 final int appId; 20082 final String seinfo; 20083 final String label; 20084 final int targetSdkVersion; 20085 final PackageFreezer freezer; 20086 final int[] installedUserIds; 20087 20088 // reader 20089 synchronized (mPackages) { 20090 final PackageParser.Package pkg = mPackages.get(packageName); 20091 final PackageSetting ps = mSettings.mPackages.get(packageName); 20092 if (pkg == null || ps == null) { 20093 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 20094 } 20095 20096 if (pkg.applicationInfo.isSystemApp()) { 20097 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 20098 "Cannot move system application"); 20099 } 20100 20101 if (pkg.applicationInfo.isExternalAsec()) { 20102 currentAsec = true; 20103 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 20104 } else if (pkg.applicationInfo.isForwardLocked()) { 20105 currentAsec = true; 20106 currentVolumeUuid = "forward_locked"; 20107 } else { 20108 currentAsec = false; 20109 currentVolumeUuid = ps.volumeUuid; 20110 20111 final File probe = new File(pkg.codePath); 20112 final File probeOat = new File(probe, "oat"); 20113 if (!probe.isDirectory() || !probeOat.isDirectory()) { 20114 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20115 "Move only supported for modern cluster style installs"); 20116 } 20117 } 20118 20119 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 20120 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20121 "Package already moved to " + volumeUuid); 20122 } 20123 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 20124 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 20125 "Device admin cannot be moved"); 20126 } 20127 20128 if (mFrozenPackages.contains(packageName)) { 20129 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 20130 "Failed to move already frozen package"); 20131 } 20132 20133 codeFile = new File(pkg.codePath); 20134 installerPackageName = ps.installerPackageName; 20135 packageAbiOverride = ps.cpuAbiOverrideString; 20136 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 20137 seinfo = pkg.applicationInfo.seinfo; 20138 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 20139 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 20140 freezer = freezePackage(packageName, "movePackageInternal"); 20141 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 20142 } 20143 20144 final Bundle extras = new Bundle(); 20145 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 20146 extras.putString(Intent.EXTRA_TITLE, label); 20147 mMoveCallbacks.notifyCreated(moveId, extras); 20148 20149 int installFlags; 20150 final boolean moveCompleteApp; 20151 final File measurePath; 20152 20153 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 20154 installFlags = INSTALL_INTERNAL; 20155 moveCompleteApp = !currentAsec; 20156 measurePath = Environment.getDataAppDirectory(volumeUuid); 20157 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 20158 installFlags = INSTALL_EXTERNAL; 20159 moveCompleteApp = false; 20160 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 20161 } else { 20162 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 20163 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 20164 || !volume.isMountedWritable()) { 20165 freezer.close(); 20166 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20167 "Move location not mounted private volume"); 20168 } 20169 20170 Preconditions.checkState(!currentAsec); 20171 20172 installFlags = INSTALL_INTERNAL; 20173 moveCompleteApp = true; 20174 measurePath = Environment.getDataAppDirectory(volumeUuid); 20175 } 20176 20177 final PackageStats stats = new PackageStats(null, -1); 20178 synchronized (mInstaller) { 20179 for (int userId : installedUserIds) { 20180 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 20181 freezer.close(); 20182 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20183 "Failed to measure package size"); 20184 } 20185 } 20186 } 20187 20188 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 20189 + stats.dataSize); 20190 20191 final long startFreeBytes = measurePath.getFreeSpace(); 20192 final long sizeBytes; 20193 if (moveCompleteApp) { 20194 sizeBytes = stats.codeSize + stats.dataSize; 20195 } else { 20196 sizeBytes = stats.codeSize; 20197 } 20198 20199 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 20200 freezer.close(); 20201 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20202 "Not enough free space to move"); 20203 } 20204 20205 mMoveCallbacks.notifyStatusChanged(moveId, 10); 20206 20207 final CountDownLatch installedLatch = new CountDownLatch(1); 20208 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 20209 @Override 20210 public void onUserActionRequired(Intent intent) throws RemoteException { 20211 throw new IllegalStateException(); 20212 } 20213 20214 @Override 20215 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 20216 Bundle extras) throws RemoteException { 20217 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 20218 + PackageManager.installStatusToString(returnCode, msg)); 20219 20220 installedLatch.countDown(); 20221 freezer.close(); 20222 20223 final int status = PackageManager.installStatusToPublicStatus(returnCode); 20224 switch (status) { 20225 case PackageInstaller.STATUS_SUCCESS: 20226 mMoveCallbacks.notifyStatusChanged(moveId, 20227 PackageManager.MOVE_SUCCEEDED); 20228 break; 20229 case PackageInstaller.STATUS_FAILURE_STORAGE: 20230 mMoveCallbacks.notifyStatusChanged(moveId, 20231 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 20232 break; 20233 default: 20234 mMoveCallbacks.notifyStatusChanged(moveId, 20235 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 20236 break; 20237 } 20238 } 20239 }; 20240 20241 final MoveInfo move; 20242 if (moveCompleteApp) { 20243 // Kick off a thread to report progress estimates 20244 new Thread() { 20245 @Override 20246 public void run() { 20247 while (true) { 20248 try { 20249 if (installedLatch.await(1, TimeUnit.SECONDS)) { 20250 break; 20251 } 20252 } catch (InterruptedException ignored) { 20253 } 20254 20255 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 20256 final int progress = 10 + (int) MathUtils.constrain( 20257 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 20258 mMoveCallbacks.notifyStatusChanged(moveId, progress); 20259 } 20260 } 20261 }.start(); 20262 20263 final String dataAppName = codeFile.getName(); 20264 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 20265 dataAppName, appId, seinfo, targetSdkVersion); 20266 } else { 20267 move = null; 20268 } 20269 20270 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 20271 20272 final Message msg = mHandler.obtainMessage(INIT_COPY); 20273 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 20274 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 20275 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 20276 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/); 20277 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 20278 msg.obj = params; 20279 20280 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 20281 System.identityHashCode(msg.obj)); 20282 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 20283 System.identityHashCode(msg.obj)); 20284 20285 mHandler.sendMessage(msg); 20286 } 20287 20288 @Override 20289 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 20290 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 20291 20292 final int realMoveId = mNextMoveId.getAndIncrement(); 20293 final Bundle extras = new Bundle(); 20294 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 20295 mMoveCallbacks.notifyCreated(realMoveId, extras); 20296 20297 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 20298 @Override 20299 public void onCreated(int moveId, Bundle extras) { 20300 // Ignored 20301 } 20302 20303 @Override 20304 public void onStatusChanged(int moveId, int status, long estMillis) { 20305 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 20306 } 20307 }; 20308 20309 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20310 storage.setPrimaryStorageUuid(volumeUuid, callback); 20311 return realMoveId; 20312 } 20313 20314 @Override 20315 public int getMoveStatus(int moveId) { 20316 mContext.enforceCallingOrSelfPermission( 20317 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20318 return mMoveCallbacks.mLastStatus.get(moveId); 20319 } 20320 20321 @Override 20322 public void registerMoveCallback(IPackageMoveObserver callback) { 20323 mContext.enforceCallingOrSelfPermission( 20324 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20325 mMoveCallbacks.register(callback); 20326 } 20327 20328 @Override 20329 public void unregisterMoveCallback(IPackageMoveObserver callback) { 20330 mContext.enforceCallingOrSelfPermission( 20331 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20332 mMoveCallbacks.unregister(callback); 20333 } 20334 20335 @Override 20336 public boolean setInstallLocation(int loc) { 20337 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 20338 null); 20339 if (getInstallLocation() == loc) { 20340 return true; 20341 } 20342 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 20343 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 20344 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 20345 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 20346 return true; 20347 } 20348 return false; 20349 } 20350 20351 @Override 20352 public int getInstallLocation() { 20353 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 20354 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 20355 PackageHelper.APP_INSTALL_AUTO); 20356 } 20357 20358 /** Called by UserManagerService */ 20359 void cleanUpUser(UserManagerService userManager, int userHandle) { 20360 synchronized (mPackages) { 20361 mDirtyUsers.remove(userHandle); 20362 mUserNeedsBadging.delete(userHandle); 20363 mSettings.removeUserLPw(userHandle); 20364 mPendingBroadcasts.remove(userHandle); 20365 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 20366 removeUnusedPackagesLPw(userManager, userHandle); 20367 } 20368 } 20369 20370 /** 20371 * We're removing userHandle and would like to remove any downloaded packages 20372 * that are no longer in use by any other user. 20373 * @param userHandle the user being removed 20374 */ 20375 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 20376 final boolean DEBUG_CLEAN_APKS = false; 20377 int [] users = userManager.getUserIds(); 20378 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 20379 while (psit.hasNext()) { 20380 PackageSetting ps = psit.next(); 20381 if (ps.pkg == null) { 20382 continue; 20383 } 20384 final String packageName = ps.pkg.packageName; 20385 // Skip over if system app 20386 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 20387 continue; 20388 } 20389 if (DEBUG_CLEAN_APKS) { 20390 Slog.i(TAG, "Checking package " + packageName); 20391 } 20392 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 20393 if (keep) { 20394 if (DEBUG_CLEAN_APKS) { 20395 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 20396 } 20397 } else { 20398 for (int i = 0; i < users.length; i++) { 20399 if (users[i] != userHandle && ps.getInstalled(users[i])) { 20400 keep = true; 20401 if (DEBUG_CLEAN_APKS) { 20402 Slog.i(TAG, " Keeping package " + packageName + " for user " 20403 + users[i]); 20404 } 20405 break; 20406 } 20407 } 20408 } 20409 if (!keep) { 20410 if (DEBUG_CLEAN_APKS) { 20411 Slog.i(TAG, " Removing package " + packageName); 20412 } 20413 mHandler.post(new Runnable() { 20414 public void run() { 20415 deletePackageX(packageName, userHandle, 0); 20416 } //end run 20417 }); 20418 } 20419 } 20420 } 20421 20422 /** Called by UserManagerService */ 20423 void createNewUser(int userId) { 20424 synchronized (mInstallLock) { 20425 mSettings.createNewUserLI(this, mInstaller, userId); 20426 } 20427 synchronized (mPackages) { 20428 scheduleWritePackageRestrictionsLocked(userId); 20429 scheduleWritePackageListLocked(userId); 20430 applyFactoryDefaultBrowserLPw(userId); 20431 primeDomainVerificationsLPw(userId); 20432 } 20433 } 20434 20435 void onBeforeUserStartUninitialized(final int userId) { 20436 synchronized (mPackages) { 20437 if (mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 20438 return; 20439 } 20440 } 20441 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 20442 // If permission review for legacy apps is required, we represent 20443 // dagerous permissions for such apps as always granted runtime 20444 // permissions to keep per user flag state whether review is needed. 20445 // Hence, if a new user is added we have to propagate dangerous 20446 // permission grants for these legacy apps. 20447 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 20448 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 20449 | UPDATE_PERMISSIONS_REPLACE_ALL); 20450 } 20451 } 20452 20453 @Override 20454 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 20455 mContext.enforceCallingOrSelfPermission( 20456 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 20457 "Only package verification agents can read the verifier device identity"); 20458 20459 synchronized (mPackages) { 20460 return mSettings.getVerifierDeviceIdentityLPw(); 20461 } 20462 } 20463 20464 @Override 20465 public void setPermissionEnforced(String permission, boolean enforced) { 20466 // TODO: Now that we no longer change GID for storage, this should to away. 20467 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 20468 "setPermissionEnforced"); 20469 if (READ_EXTERNAL_STORAGE.equals(permission)) { 20470 synchronized (mPackages) { 20471 if (mSettings.mReadExternalStorageEnforced == null 20472 || mSettings.mReadExternalStorageEnforced != enforced) { 20473 mSettings.mReadExternalStorageEnforced = enforced; 20474 mSettings.writeLPr(); 20475 } 20476 } 20477 // kill any non-foreground processes so we restart them and 20478 // grant/revoke the GID. 20479 final IActivityManager am = ActivityManagerNative.getDefault(); 20480 if (am != null) { 20481 final long token = Binder.clearCallingIdentity(); 20482 try { 20483 am.killProcessesBelowForeground("setPermissionEnforcement"); 20484 } catch (RemoteException e) { 20485 } finally { 20486 Binder.restoreCallingIdentity(token); 20487 } 20488 } 20489 } else { 20490 throw new IllegalArgumentException("No selective enforcement for " + permission); 20491 } 20492 } 20493 20494 @Override 20495 @Deprecated 20496 public boolean isPermissionEnforced(String permission) { 20497 return true; 20498 } 20499 20500 @Override 20501 public boolean isStorageLow() { 20502 final long token = Binder.clearCallingIdentity(); 20503 try { 20504 final DeviceStorageMonitorInternal 20505 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 20506 if (dsm != null) { 20507 return dsm.isMemoryLow(); 20508 } else { 20509 return false; 20510 } 20511 } finally { 20512 Binder.restoreCallingIdentity(token); 20513 } 20514 } 20515 20516 @Override 20517 public IPackageInstaller getPackageInstaller() { 20518 return mInstallerService; 20519 } 20520 20521 private boolean userNeedsBadging(int userId) { 20522 int index = mUserNeedsBadging.indexOfKey(userId); 20523 if (index < 0) { 20524 final UserInfo userInfo; 20525 final long token = Binder.clearCallingIdentity(); 20526 try { 20527 userInfo = sUserManager.getUserInfo(userId); 20528 } finally { 20529 Binder.restoreCallingIdentity(token); 20530 } 20531 final boolean b; 20532 if (userInfo != null && userInfo.isManagedProfile()) { 20533 b = true; 20534 } else { 20535 b = false; 20536 } 20537 mUserNeedsBadging.put(userId, b); 20538 return b; 20539 } 20540 return mUserNeedsBadging.valueAt(index); 20541 } 20542 20543 @Override 20544 public KeySet getKeySetByAlias(String packageName, String alias) { 20545 if (packageName == null || alias == null) { 20546 return null; 20547 } 20548 synchronized(mPackages) { 20549 final PackageParser.Package pkg = mPackages.get(packageName); 20550 if (pkg == null) { 20551 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20552 throw new IllegalArgumentException("Unknown package: " + packageName); 20553 } 20554 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20555 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 20556 } 20557 } 20558 20559 @Override 20560 public KeySet getSigningKeySet(String packageName) { 20561 if (packageName == null) { 20562 return null; 20563 } 20564 synchronized(mPackages) { 20565 final PackageParser.Package pkg = mPackages.get(packageName); 20566 if (pkg == null) { 20567 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20568 throw new IllegalArgumentException("Unknown package: " + packageName); 20569 } 20570 if (pkg.applicationInfo.uid != Binder.getCallingUid() 20571 && Process.SYSTEM_UID != Binder.getCallingUid()) { 20572 throw new SecurityException("May not access signing KeySet of other apps."); 20573 } 20574 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20575 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 20576 } 20577 } 20578 20579 @Override 20580 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 20581 if (packageName == null || ks == null) { 20582 return false; 20583 } 20584 synchronized(mPackages) { 20585 final PackageParser.Package pkg = mPackages.get(packageName); 20586 if (pkg == null) { 20587 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20588 throw new IllegalArgumentException("Unknown package: " + packageName); 20589 } 20590 IBinder ksh = ks.getToken(); 20591 if (ksh instanceof KeySetHandle) { 20592 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20593 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 20594 } 20595 return false; 20596 } 20597 } 20598 20599 @Override 20600 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 20601 if (packageName == null || ks == null) { 20602 return false; 20603 } 20604 synchronized(mPackages) { 20605 final PackageParser.Package pkg = mPackages.get(packageName); 20606 if (pkg == null) { 20607 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20608 throw new IllegalArgumentException("Unknown package: " + packageName); 20609 } 20610 IBinder ksh = ks.getToken(); 20611 if (ksh instanceof KeySetHandle) { 20612 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20613 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 20614 } 20615 return false; 20616 } 20617 } 20618 20619 private void deletePackageIfUnusedLPr(final String packageName) { 20620 PackageSetting ps = mSettings.mPackages.get(packageName); 20621 if (ps == null) { 20622 return; 20623 } 20624 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 20625 // TODO Implement atomic delete if package is unused 20626 // It is currently possible that the package will be deleted even if it is installed 20627 // after this method returns. 20628 mHandler.post(new Runnable() { 20629 public void run() { 20630 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 20631 } 20632 }); 20633 } 20634 } 20635 20636 /** 20637 * Check and throw if the given before/after packages would be considered a 20638 * downgrade. 20639 */ 20640 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 20641 throws PackageManagerException { 20642 if (after.versionCode < before.mVersionCode) { 20643 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20644 "Update version code " + after.versionCode + " is older than current " 20645 + before.mVersionCode); 20646 } else if (after.versionCode == before.mVersionCode) { 20647 if (after.baseRevisionCode < before.baseRevisionCode) { 20648 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20649 "Update base revision code " + after.baseRevisionCode 20650 + " is older than current " + before.baseRevisionCode); 20651 } 20652 20653 if (!ArrayUtils.isEmpty(after.splitNames)) { 20654 for (int i = 0; i < after.splitNames.length; i++) { 20655 final String splitName = after.splitNames[i]; 20656 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 20657 if (j != -1) { 20658 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 20659 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20660 "Update split " + splitName + " revision code " 20661 + after.splitRevisionCodes[i] + " is older than current " 20662 + before.splitRevisionCodes[j]); 20663 } 20664 } 20665 } 20666 } 20667 } 20668 } 20669 20670 private static class MoveCallbacks extends Handler { 20671 private static final int MSG_CREATED = 1; 20672 private static final int MSG_STATUS_CHANGED = 2; 20673 20674 private final RemoteCallbackList<IPackageMoveObserver> 20675 mCallbacks = new RemoteCallbackList<>(); 20676 20677 private final SparseIntArray mLastStatus = new SparseIntArray(); 20678 20679 public MoveCallbacks(Looper looper) { 20680 super(looper); 20681 } 20682 20683 public void register(IPackageMoveObserver callback) { 20684 mCallbacks.register(callback); 20685 } 20686 20687 public void unregister(IPackageMoveObserver callback) { 20688 mCallbacks.unregister(callback); 20689 } 20690 20691 @Override 20692 public void handleMessage(Message msg) { 20693 final SomeArgs args = (SomeArgs) msg.obj; 20694 final int n = mCallbacks.beginBroadcast(); 20695 for (int i = 0; i < n; i++) { 20696 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 20697 try { 20698 invokeCallback(callback, msg.what, args); 20699 } catch (RemoteException ignored) { 20700 } 20701 } 20702 mCallbacks.finishBroadcast(); 20703 args.recycle(); 20704 } 20705 20706 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 20707 throws RemoteException { 20708 switch (what) { 20709 case MSG_CREATED: { 20710 callback.onCreated(args.argi1, (Bundle) args.arg2); 20711 break; 20712 } 20713 case MSG_STATUS_CHANGED: { 20714 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 20715 break; 20716 } 20717 } 20718 } 20719 20720 private void notifyCreated(int moveId, Bundle extras) { 20721 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 20722 20723 final SomeArgs args = SomeArgs.obtain(); 20724 args.argi1 = moveId; 20725 args.arg2 = extras; 20726 obtainMessage(MSG_CREATED, args).sendToTarget(); 20727 } 20728 20729 private void notifyStatusChanged(int moveId, int status) { 20730 notifyStatusChanged(moveId, status, -1); 20731 } 20732 20733 private void notifyStatusChanged(int moveId, int status, long estMillis) { 20734 Slog.v(TAG, "Move " + moveId + " status " + status); 20735 20736 final SomeArgs args = SomeArgs.obtain(); 20737 args.argi1 = moveId; 20738 args.argi2 = status; 20739 args.arg3 = estMillis; 20740 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 20741 20742 synchronized (mLastStatus) { 20743 mLastStatus.put(moveId, status); 20744 } 20745 } 20746 } 20747 20748 private final static class OnPermissionChangeListeners extends Handler { 20749 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 20750 20751 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 20752 new RemoteCallbackList<>(); 20753 20754 public OnPermissionChangeListeners(Looper looper) { 20755 super(looper); 20756 } 20757 20758 @Override 20759 public void handleMessage(Message msg) { 20760 switch (msg.what) { 20761 case MSG_ON_PERMISSIONS_CHANGED: { 20762 final int uid = msg.arg1; 20763 handleOnPermissionsChanged(uid); 20764 } break; 20765 } 20766 } 20767 20768 public void addListenerLocked(IOnPermissionsChangeListener listener) { 20769 mPermissionListeners.register(listener); 20770 20771 } 20772 20773 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 20774 mPermissionListeners.unregister(listener); 20775 } 20776 20777 public void onPermissionsChanged(int uid) { 20778 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 20779 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 20780 } 20781 } 20782 20783 private void handleOnPermissionsChanged(int uid) { 20784 final int count = mPermissionListeners.beginBroadcast(); 20785 try { 20786 for (int i = 0; i < count; i++) { 20787 IOnPermissionsChangeListener callback = mPermissionListeners 20788 .getBroadcastItem(i); 20789 try { 20790 callback.onPermissionsChanged(uid); 20791 } catch (RemoteException e) { 20792 Log.e(TAG, "Permission listener is dead", e); 20793 } 20794 } 20795 } finally { 20796 mPermissionListeners.finishBroadcast(); 20797 } 20798 } 20799 } 20800 20801 private class PackageManagerInternalImpl extends PackageManagerInternal { 20802 @Override 20803 public void setLocationPackagesProvider(PackagesProvider provider) { 20804 synchronized (mPackages) { 20805 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 20806 } 20807 } 20808 20809 @Override 20810 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 20811 synchronized (mPackages) { 20812 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 20813 } 20814 } 20815 20816 @Override 20817 public void setSmsAppPackagesProvider(PackagesProvider provider) { 20818 synchronized (mPackages) { 20819 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 20820 } 20821 } 20822 20823 @Override 20824 public void setDialerAppPackagesProvider(PackagesProvider provider) { 20825 synchronized (mPackages) { 20826 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 20827 } 20828 } 20829 20830 @Override 20831 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 20832 synchronized (mPackages) { 20833 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 20834 } 20835 } 20836 20837 @Override 20838 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 20839 synchronized (mPackages) { 20840 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 20841 } 20842 } 20843 20844 @Override 20845 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 20846 synchronized (mPackages) { 20847 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 20848 packageName, userId); 20849 } 20850 } 20851 20852 @Override 20853 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 20854 synchronized (mPackages) { 20855 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 20856 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 20857 packageName, userId); 20858 } 20859 } 20860 20861 @Override 20862 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 20863 synchronized (mPackages) { 20864 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 20865 packageName, userId); 20866 } 20867 } 20868 20869 @Override 20870 public void setKeepUninstalledPackages(final List<String> packageList) { 20871 Preconditions.checkNotNull(packageList); 20872 List<String> removedFromList = null; 20873 synchronized (mPackages) { 20874 if (mKeepUninstalledPackages != null) { 20875 final int packagesCount = mKeepUninstalledPackages.size(); 20876 for (int i = 0; i < packagesCount; i++) { 20877 String oldPackage = mKeepUninstalledPackages.get(i); 20878 if (packageList != null && packageList.contains(oldPackage)) { 20879 continue; 20880 } 20881 if (removedFromList == null) { 20882 removedFromList = new ArrayList<>(); 20883 } 20884 removedFromList.add(oldPackage); 20885 } 20886 } 20887 mKeepUninstalledPackages = new ArrayList<>(packageList); 20888 if (removedFromList != null) { 20889 final int removedCount = removedFromList.size(); 20890 for (int i = 0; i < removedCount; i++) { 20891 deletePackageIfUnusedLPr(removedFromList.get(i)); 20892 } 20893 } 20894 } 20895 } 20896 20897 @Override 20898 public boolean isPermissionsReviewRequired(String packageName, int userId) { 20899 synchronized (mPackages) { 20900 // If we do not support permission review, done. 20901 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 20902 return false; 20903 } 20904 20905 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 20906 if (packageSetting == null) { 20907 return false; 20908 } 20909 20910 // Permission review applies only to apps not supporting the new permission model. 20911 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 20912 return false; 20913 } 20914 20915 // Legacy apps have the permission and get user consent on launch. 20916 PermissionsState permissionsState = packageSetting.getPermissionsState(); 20917 return permissionsState.isPermissionReviewRequired(userId); 20918 } 20919 } 20920 20921 @Override 20922 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 20923 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 20924 } 20925 20926 @Override 20927 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 20928 int userId) { 20929 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 20930 } 20931 20932 @Override 20933 public void setDeviceAndProfileOwnerPackages( 20934 int deviceOwnerUserId, String deviceOwnerPackage, 20935 SparseArray<String> profileOwnerPackages) { 20936 mProtectedPackages.setDeviceAndProfileOwnerPackages( 20937 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 20938 } 20939 20940 @Override 20941 public boolean isPackageDataProtected(int userId, String packageName) { 20942 return mProtectedPackages.isPackageDataProtected(userId, packageName); 20943 } 20944 } 20945 20946 @Override 20947 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 20948 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 20949 synchronized (mPackages) { 20950 final long identity = Binder.clearCallingIdentity(); 20951 try { 20952 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 20953 packageNames, userId); 20954 } finally { 20955 Binder.restoreCallingIdentity(identity); 20956 } 20957 } 20958 } 20959 20960 private static void enforceSystemOrPhoneCaller(String tag) { 20961 int callingUid = Binder.getCallingUid(); 20962 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 20963 throw new SecurityException( 20964 "Cannot call " + tag + " from UID " + callingUid); 20965 } 20966 } 20967 20968 boolean isHistoricalPackageUsageAvailable() { 20969 return mPackageUsage.isHistoricalPackageUsageAvailable(); 20970 } 20971 20972 /** 20973 * Return a <b>copy</b> of the collection of packages known to the package manager. 20974 * @return A copy of the values of mPackages. 20975 */ 20976 Collection<PackageParser.Package> getPackages() { 20977 synchronized (mPackages) { 20978 return new ArrayList<>(mPackages.values()); 20979 } 20980 } 20981 20982 /** 20983 * Logs process start information (including base APK hash) to the security log. 20984 * @hide 20985 */ 20986 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 20987 String apkFile, int pid) { 20988 if (!SecurityLog.isLoggingEnabled()) { 20989 return; 20990 } 20991 Bundle data = new Bundle(); 20992 data.putLong("startTimestamp", System.currentTimeMillis()); 20993 data.putString("processName", processName); 20994 data.putInt("uid", uid); 20995 data.putString("seinfo", seinfo); 20996 data.putString("apkFile", apkFile); 20997 data.putInt("pid", pid); 20998 Message msg = mProcessLoggingHandler.obtainMessage( 20999 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 21000 msg.setData(data); 21001 mProcessLoggingHandler.sendMessage(msg); 21002 } 21003} 21004