PackageManagerService.java revision 15ba58b8a48cb2bc64d1d71d7f96653c0f2ea34c
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 if (jarFile != null) { 8026 jarFile.close(); 8027 } 8028 } catch (IOException ignore) {} 8029 } 8030 return false; 8031 } 8032 8033 /** 8034 * Enforces code policy for the package. This ensures that if an APK has 8035 * declared hasCode="true" in its manifest that the APK actually contains 8036 * code. 8037 * 8038 * @throws PackageManagerException If bytecode could not be found when it should exist 8039 */ 8040 private static void enforceCodePolicy(PackageParser.Package pkg) 8041 throws PackageManagerException { 8042 final boolean shouldHaveCode = 8043 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 8044 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 8045 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8046 "Package " + pkg.baseCodePath + " code is missing"); 8047 } 8048 8049 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 8050 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 8051 final boolean splitShouldHaveCode = 8052 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 8053 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 8054 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8055 "Package " + pkg.splitCodePaths[i] + " code is missing"); 8056 } 8057 } 8058 } 8059 } 8060 8061 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 8062 final int policyFlags, final int scanFlags, long currentTime, UserHandle user) 8063 throws PackageManagerException { 8064 final File scanFile = new File(pkg.codePath); 8065 if (pkg.applicationInfo.getCodePath() == null || 8066 pkg.applicationInfo.getResourcePath() == null) { 8067 // Bail out. The resource and code paths haven't been set. 8068 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8069 "Code and resource paths haven't been set correctly"); 8070 } 8071 8072 // Apply policy 8073 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 8074 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 8075 if (pkg.applicationInfo.isDirectBootAware()) { 8076 // we're direct boot aware; set for all components 8077 for (PackageParser.Service s : pkg.services) { 8078 s.info.encryptionAware = s.info.directBootAware = true; 8079 } 8080 for (PackageParser.Provider p : pkg.providers) { 8081 p.info.encryptionAware = p.info.directBootAware = true; 8082 } 8083 for (PackageParser.Activity a : pkg.activities) { 8084 a.info.encryptionAware = a.info.directBootAware = true; 8085 } 8086 for (PackageParser.Activity r : pkg.receivers) { 8087 r.info.encryptionAware = r.info.directBootAware = true; 8088 } 8089 } 8090 } else { 8091 // Only allow system apps to be flagged as core apps. 8092 pkg.coreApp = false; 8093 // clear flags not applicable to regular apps 8094 pkg.applicationInfo.privateFlags &= 8095 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 8096 pkg.applicationInfo.privateFlags &= 8097 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 8098 } 8099 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 8100 8101 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 8102 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 8103 } 8104 8105 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 8106 enforceCodePolicy(pkg); 8107 } 8108 8109 if (mCustomResolverComponentName != null && 8110 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 8111 setUpCustomResolverActivity(pkg); 8112 } 8113 8114 if (pkg.packageName.equals("android")) { 8115 synchronized (mPackages) { 8116 if (mAndroidApplication != null) { 8117 Slog.w(TAG, "*************************************************"); 8118 Slog.w(TAG, "Core android package being redefined. Skipping."); 8119 Slog.w(TAG, " file=" + scanFile); 8120 Slog.w(TAG, "*************************************************"); 8121 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 8122 "Core android package being redefined. Skipping."); 8123 } 8124 8125 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8126 // Set up information for our fall-back user intent resolution activity. 8127 mPlatformPackage = pkg; 8128 pkg.mVersionCode = mSdkVersion; 8129 mAndroidApplication = pkg.applicationInfo; 8130 8131 if (!mResolverReplaced) { 8132 mResolveActivity.applicationInfo = mAndroidApplication; 8133 mResolveActivity.name = ResolverActivity.class.getName(); 8134 mResolveActivity.packageName = mAndroidApplication.packageName; 8135 mResolveActivity.processName = "system:ui"; 8136 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8137 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 8138 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 8139 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 8140 mResolveActivity.exported = true; 8141 mResolveActivity.enabled = true; 8142 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 8143 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 8144 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 8145 | ActivityInfo.CONFIG_SCREEN_LAYOUT 8146 | ActivityInfo.CONFIG_ORIENTATION 8147 | ActivityInfo.CONFIG_KEYBOARD 8148 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 8149 mResolveInfo.activityInfo = mResolveActivity; 8150 mResolveInfo.priority = 0; 8151 mResolveInfo.preferredOrder = 0; 8152 mResolveInfo.match = 0; 8153 mResolveComponentName = new ComponentName( 8154 mAndroidApplication.packageName, mResolveActivity.name); 8155 } 8156 } 8157 } 8158 } 8159 8160 if (DEBUG_PACKAGE_SCANNING) { 8161 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8162 Log.d(TAG, "Scanning package " + pkg.packageName); 8163 } 8164 8165 synchronized (mPackages) { 8166 if (mPackages.containsKey(pkg.packageName) 8167 || mSharedLibraries.containsKey(pkg.packageName)) { 8168 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 8169 "Application package " + pkg.packageName 8170 + " already installed. Skipping duplicate."); 8171 } 8172 8173 // If we're only installing presumed-existing packages, require that the 8174 // scanned APK is both already known and at the path previously established 8175 // for it. Previously unknown packages we pick up normally, but if we have an 8176 // a priori expectation about this package's install presence, enforce it. 8177 // With a singular exception for new system packages. When an OTA contains 8178 // a new system package, we allow the codepath to change from a system location 8179 // to the user-installed location. If we don't allow this change, any newer, 8180 // user-installed version of the application will be ignored. 8181 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 8182 if (mExpectingBetter.containsKey(pkg.packageName)) { 8183 logCriticalInfo(Log.WARN, 8184 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 8185 } else { 8186 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 8187 if (known != null) { 8188 if (DEBUG_PACKAGE_SCANNING) { 8189 Log.d(TAG, "Examining " + pkg.codePath 8190 + " and requiring known paths " + known.codePathString 8191 + " & " + known.resourcePathString); 8192 } 8193 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 8194 || !pkg.applicationInfo.getResourcePath().equals( 8195 known.resourcePathString)) { 8196 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 8197 "Application package " + pkg.packageName 8198 + " found at " + pkg.applicationInfo.getCodePath() 8199 + " but expected at " + known.codePathString 8200 + "; ignoring."); 8201 } 8202 } 8203 } 8204 } 8205 } 8206 8207 // Initialize package source and resource directories 8208 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 8209 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 8210 8211 SharedUserSetting suid = null; 8212 PackageSetting pkgSetting = null; 8213 8214 if (!isSystemApp(pkg)) { 8215 // Only system apps can use these features. 8216 pkg.mOriginalPackages = null; 8217 pkg.mRealPackage = null; 8218 pkg.mAdoptPermissions = null; 8219 } 8220 8221 // Getting the package setting may have a side-effect, so if we 8222 // are only checking if scan would succeed, stash a copy of the 8223 // old setting to restore at the end. 8224 PackageSetting nonMutatedPs = null; 8225 8226 // writer 8227 synchronized (mPackages) { 8228 if (pkg.mSharedUserId != null) { 8229 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 8230 if (suid == null) { 8231 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8232 "Creating application package " + pkg.packageName 8233 + " for shared user failed"); 8234 } 8235 if (DEBUG_PACKAGE_SCANNING) { 8236 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8237 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 8238 + "): packages=" + suid.packages); 8239 } 8240 } 8241 8242 // Check if we are renaming from an original package name. 8243 PackageSetting origPackage = null; 8244 String realName = null; 8245 if (pkg.mOriginalPackages != null) { 8246 // This package may need to be renamed to a previously 8247 // installed name. Let's check on that... 8248 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 8249 if (pkg.mOriginalPackages.contains(renamed)) { 8250 // This package had originally been installed as the 8251 // original name, and we have already taken care of 8252 // transitioning to the new one. Just update the new 8253 // one to continue using the old name. 8254 realName = pkg.mRealPackage; 8255 if (!pkg.packageName.equals(renamed)) { 8256 // Callers into this function may have already taken 8257 // care of renaming the package; only do it here if 8258 // it is not already done. 8259 pkg.setPackageName(renamed); 8260 } 8261 8262 } else { 8263 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 8264 if ((origPackage = mSettings.peekPackageLPr( 8265 pkg.mOriginalPackages.get(i))) != null) { 8266 // We do have the package already installed under its 8267 // original name... should we use it? 8268 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 8269 // New package is not compatible with original. 8270 origPackage = null; 8271 continue; 8272 } else if (origPackage.sharedUser != null) { 8273 // Make sure uid is compatible between packages. 8274 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 8275 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 8276 + " to " + pkg.packageName + ": old uid " 8277 + origPackage.sharedUser.name 8278 + " differs from " + pkg.mSharedUserId); 8279 origPackage = null; 8280 continue; 8281 } 8282 // TODO: Add case when shared user id is added [b/28144775] 8283 } else { 8284 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 8285 + pkg.packageName + " to old name " + origPackage.name); 8286 } 8287 break; 8288 } 8289 } 8290 } 8291 } 8292 8293 if (mTransferedPackages.contains(pkg.packageName)) { 8294 Slog.w(TAG, "Package " + pkg.packageName 8295 + " was transferred to another, but its .apk remains"); 8296 } 8297 8298 // See comments in nonMutatedPs declaration 8299 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8300 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 8301 if (foundPs != null) { 8302 nonMutatedPs = new PackageSetting(foundPs); 8303 } 8304 } 8305 8306 // Just create the setting, don't add it yet. For already existing packages 8307 // the PkgSetting exists already and doesn't have to be created. 8308 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 8309 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 8310 pkg.applicationInfo.primaryCpuAbi, 8311 pkg.applicationInfo.secondaryCpuAbi, 8312 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 8313 user, false); 8314 if (pkgSetting == null) { 8315 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8316 "Creating application package " + pkg.packageName + " failed"); 8317 } 8318 8319 if (pkgSetting.origPackage != null) { 8320 // If we are first transitioning from an original package, 8321 // fix up the new package's name now. We need to do this after 8322 // looking up the package under its new name, so getPackageLP 8323 // can take care of fiddling things correctly. 8324 pkg.setPackageName(origPackage.name); 8325 8326 // File a report about this. 8327 String msg = "New package " + pkgSetting.realName 8328 + " renamed to replace old package " + pkgSetting.name; 8329 reportSettingsProblem(Log.WARN, msg); 8330 8331 // Make a note of it. 8332 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8333 mTransferedPackages.add(origPackage.name); 8334 } 8335 8336 // No longer need to retain this. 8337 pkgSetting.origPackage = null; 8338 } 8339 8340 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 8341 // Make a note of it. 8342 mTransferedPackages.add(pkg.packageName); 8343 } 8344 8345 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 8346 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 8347 } 8348 8349 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8350 // Check all shared libraries and map to their actual file path. 8351 // We only do this here for apps not on a system dir, because those 8352 // are the only ones that can fail an install due to this. We 8353 // will take care of the system apps by updating all of their 8354 // library paths after the scan is done. 8355 updateSharedLibrariesLPw(pkg, null); 8356 } 8357 8358 if (mFoundPolicyFile) { 8359 SELinuxMMAC.assignSeinfoValue(pkg); 8360 } 8361 8362 pkg.applicationInfo.uid = pkgSetting.appId; 8363 pkg.mExtras = pkgSetting; 8364 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 8365 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 8366 // We just determined the app is signed correctly, so bring 8367 // over the latest parsed certs. 8368 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8369 } else { 8370 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8371 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8372 "Package " + pkg.packageName + " upgrade keys do not match the " 8373 + "previously installed version"); 8374 } else { 8375 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8376 String msg = "System package " + pkg.packageName 8377 + " signature changed; retaining data."; 8378 reportSettingsProblem(Log.WARN, msg); 8379 } 8380 } 8381 } else { 8382 try { 8383 verifySignaturesLP(pkgSetting, pkg); 8384 // We just determined the app is signed correctly, so bring 8385 // over the latest parsed certs. 8386 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8387 } catch (PackageManagerException e) { 8388 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8389 throw e; 8390 } 8391 // The signature has changed, but this package is in the system 8392 // image... let's recover! 8393 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8394 // However... if this package is part of a shared user, but it 8395 // doesn't match the signature of the shared user, let's fail. 8396 // What this means is that you can't change the signatures 8397 // associated with an overall shared user, which doesn't seem all 8398 // that unreasonable. 8399 if (pkgSetting.sharedUser != null) { 8400 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8401 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 8402 throw new PackageManagerException( 8403 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 8404 "Signature mismatch for shared user: " 8405 + pkgSetting.sharedUser); 8406 } 8407 } 8408 // File a report about this. 8409 String msg = "System package " + pkg.packageName 8410 + " signature changed; retaining data."; 8411 reportSettingsProblem(Log.WARN, msg); 8412 } 8413 } 8414 // Verify that this new package doesn't have any content providers 8415 // that conflict with existing packages. Only do this if the 8416 // package isn't already installed, since we don't want to break 8417 // things that are installed. 8418 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 8419 final int N = pkg.providers.size(); 8420 int i; 8421 for (i=0; i<N; i++) { 8422 PackageParser.Provider p = pkg.providers.get(i); 8423 if (p.info.authority != null) { 8424 String names[] = p.info.authority.split(";"); 8425 for (int j = 0; j < names.length; j++) { 8426 if (mProvidersByAuthority.containsKey(names[j])) { 8427 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8428 final String otherPackageName = 8429 ((other != null && other.getComponentName() != null) ? 8430 other.getComponentName().getPackageName() : "?"); 8431 throw new PackageManagerException( 8432 INSTALL_FAILED_CONFLICTING_PROVIDER, 8433 "Can't install because provider name " + names[j] 8434 + " (in package " + pkg.applicationInfo.packageName 8435 + ") is already used by " + otherPackageName); 8436 } 8437 } 8438 } 8439 } 8440 } 8441 8442 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 8443 // This package wants to adopt ownership of permissions from 8444 // another package. 8445 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 8446 final String origName = pkg.mAdoptPermissions.get(i); 8447 final PackageSetting orig = mSettings.peekPackageLPr(origName); 8448 if (orig != null) { 8449 if (verifyPackageUpdateLPr(orig, pkg)) { 8450 Slog.i(TAG, "Adopting permissions from " + origName + " to " 8451 + pkg.packageName); 8452 mSettings.transferPermissionsLPw(origName, pkg.packageName); 8453 } 8454 } 8455 } 8456 } 8457 } 8458 8459 final String pkgName = pkg.packageName; 8460 8461 final long scanFileTime = getLastModifiedTime(pkg, scanFile); 8462 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 8463 pkg.applicationInfo.processName = fixProcessName( 8464 pkg.applicationInfo.packageName, 8465 pkg.applicationInfo.processName, 8466 pkg.applicationInfo.uid); 8467 8468 if (pkg != mPlatformPackage) { 8469 // Get all of our default paths setup 8470 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 8471 } 8472 8473 final String path = scanFile.getPath(); 8474 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 8475 8476 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 8477 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 8478 8479 // Some system apps still use directory structure for native libraries 8480 // in which case we might end up not detecting abi solely based on apk 8481 // structure. Try to detect abi based on directory structure. 8482 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 8483 pkg.applicationInfo.primaryCpuAbi == null) { 8484 setBundledAppAbisAndRoots(pkg, pkgSetting); 8485 setNativeLibraryPaths(pkg); 8486 } 8487 8488 } else { 8489 if ((scanFlags & SCAN_MOVE) != 0) { 8490 // We haven't run dex-opt for this move (since we've moved the compiled output too) 8491 // but we already have this packages package info in the PackageSetting. We just 8492 // use that and derive the native library path based on the new codepath. 8493 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 8494 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 8495 } 8496 8497 // Set native library paths again. For moves, the path will be updated based on the 8498 // ABIs we've determined above. For non-moves, the path will be updated based on the 8499 // ABIs we determined during compilation, but the path will depend on the final 8500 // package path (after the rename away from the stage path). 8501 setNativeLibraryPaths(pkg); 8502 } 8503 8504 // This is a special case for the "system" package, where the ABI is 8505 // dictated by the zygote configuration (and init.rc). We should keep track 8506 // of this ABI so that we can deal with "normal" applications that run under 8507 // the same UID correctly. 8508 if (mPlatformPackage == pkg) { 8509 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 8510 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 8511 } 8512 8513 // If there's a mismatch between the abi-override in the package setting 8514 // and the abiOverride specified for the install. Warn about this because we 8515 // would've already compiled the app without taking the package setting into 8516 // account. 8517 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 8518 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 8519 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 8520 " for package " + pkg.packageName); 8521 } 8522 } 8523 8524 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8525 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8526 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 8527 8528 // Copy the derived override back to the parsed package, so that we can 8529 // update the package settings accordingly. 8530 pkg.cpuAbiOverride = cpuAbiOverride; 8531 8532 if (DEBUG_ABI_SELECTION) { 8533 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 8534 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 8535 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 8536 } 8537 8538 // Push the derived path down into PackageSettings so we know what to 8539 // clean up at uninstall time. 8540 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 8541 8542 if (DEBUG_ABI_SELECTION) { 8543 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 8544 " primary=" + pkg.applicationInfo.primaryCpuAbi + 8545 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 8546 } 8547 8548 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 8549 // We don't do this here during boot because we can do it all 8550 // at once after scanning all existing packages. 8551 // 8552 // We also do this *before* we perform dexopt on this package, so that 8553 // we can avoid redundant dexopts, and also to make sure we've got the 8554 // code and package path correct. 8555 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 8556 pkg, true /* boot complete */); 8557 } 8558 8559 if (mFactoryTest && pkg.requestedPermissions.contains( 8560 android.Manifest.permission.FACTORY_TEST)) { 8561 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 8562 } 8563 8564 ArrayList<PackageParser.Package> clientLibPkgs = null; 8565 8566 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8567 if (nonMutatedPs != null) { 8568 synchronized (mPackages) { 8569 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 8570 } 8571 } 8572 return pkg; 8573 } 8574 8575 // Only privileged apps and updated privileged apps can add child packages. 8576 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 8577 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 8578 throw new PackageManagerException("Only privileged apps and updated " 8579 + "privileged apps can add child packages. Ignoring package " 8580 + pkg.packageName); 8581 } 8582 final int childCount = pkg.childPackages.size(); 8583 for (int i = 0; i < childCount; i++) { 8584 PackageParser.Package childPkg = pkg.childPackages.get(i); 8585 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 8586 childPkg.packageName)) { 8587 throw new PackageManagerException("Cannot override a child package of " 8588 + "another disabled system app. Ignoring package " + pkg.packageName); 8589 } 8590 } 8591 } 8592 8593 // writer 8594 synchronized (mPackages) { 8595 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8596 // Only system apps can add new shared libraries. 8597 if (pkg.libraryNames != null) { 8598 for (int i=0; i<pkg.libraryNames.size(); i++) { 8599 String name = pkg.libraryNames.get(i); 8600 boolean allowed = false; 8601 if (pkg.isUpdatedSystemApp()) { 8602 // New library entries can only be added through the 8603 // system image. This is important to get rid of a lot 8604 // of nasty edge cases: for example if we allowed a non- 8605 // system update of the app to add a library, then uninstalling 8606 // the update would make the library go away, and assumptions 8607 // we made such as through app install filtering would now 8608 // have allowed apps on the device which aren't compatible 8609 // with it. Better to just have the restriction here, be 8610 // conservative, and create many fewer cases that can negatively 8611 // impact the user experience. 8612 final PackageSetting sysPs = mSettings 8613 .getDisabledSystemPkgLPr(pkg.packageName); 8614 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 8615 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 8616 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 8617 allowed = true; 8618 break; 8619 } 8620 } 8621 } 8622 } else { 8623 allowed = true; 8624 } 8625 if (allowed) { 8626 if (!mSharedLibraries.containsKey(name)) { 8627 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 8628 } else if (!name.equals(pkg.packageName)) { 8629 Slog.w(TAG, "Package " + pkg.packageName + " library " 8630 + name + " already exists; skipping"); 8631 } 8632 } else { 8633 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 8634 + name + " that is not declared on system image; skipping"); 8635 } 8636 } 8637 if ((scanFlags & SCAN_BOOTING) == 0) { 8638 // If we are not booting, we need to update any applications 8639 // that are clients of our shared library. If we are booting, 8640 // this will all be done once the scan is complete. 8641 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 8642 } 8643 } 8644 } 8645 } 8646 8647 if ((scanFlags & SCAN_BOOTING) != 0) { 8648 // No apps can run during boot scan, so they don't need to be frozen 8649 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 8650 // Caller asked to not kill app, so it's probably not frozen 8651 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 8652 // Caller asked us to ignore frozen check for some reason; they 8653 // probably didn't know the package name 8654 } else { 8655 // We're doing major surgery on this package, so it better be frozen 8656 // right now to keep it from launching 8657 checkPackageFrozen(pkgName); 8658 } 8659 8660 // Also need to kill any apps that are dependent on the library. 8661 if (clientLibPkgs != null) { 8662 for (int i=0; i<clientLibPkgs.size(); i++) { 8663 PackageParser.Package clientPkg = clientLibPkgs.get(i); 8664 killApplication(clientPkg.applicationInfo.packageName, 8665 clientPkg.applicationInfo.uid, "update lib"); 8666 } 8667 } 8668 8669 // Make sure we're not adding any bogus keyset info 8670 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8671 ksms.assertScannedPackageValid(pkg); 8672 8673 // writer 8674 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 8675 8676 boolean createIdmapFailed = false; 8677 synchronized (mPackages) { 8678 // We don't expect installation to fail beyond this point 8679 8680 if (pkgSetting.pkg != null) { 8681 // Note that |user| might be null during the initial boot scan. If a codePath 8682 // for an app has changed during a boot scan, it's due to an app update that's 8683 // part of the system partition and marker changes must be applied to all users. 8684 maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, 8685 (user != null) ? user : UserHandle.ALL); 8686 } 8687 8688 // Add the new setting to mSettings 8689 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 8690 // Add the new setting to mPackages 8691 mPackages.put(pkg.applicationInfo.packageName, pkg); 8692 // Make sure we don't accidentally delete its data. 8693 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 8694 while (iter.hasNext()) { 8695 PackageCleanItem item = iter.next(); 8696 if (pkgName.equals(item.packageName)) { 8697 iter.remove(); 8698 } 8699 } 8700 8701 // Take care of first install / last update times. 8702 if (currentTime != 0) { 8703 if (pkgSetting.firstInstallTime == 0) { 8704 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8705 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 8706 pkgSetting.lastUpdateTime = currentTime; 8707 } 8708 } else if (pkgSetting.firstInstallTime == 0) { 8709 // We need *something*. Take time time stamp of the file. 8710 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8711 } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8712 if (scanFileTime != pkgSetting.timeStamp) { 8713 // A package on the system image has changed; consider this 8714 // to be an update. 8715 pkgSetting.lastUpdateTime = scanFileTime; 8716 } 8717 } 8718 8719 // Add the package's KeySets to the global KeySetManagerService 8720 ksms.addScannedPackageLPw(pkg); 8721 8722 int N = pkg.providers.size(); 8723 StringBuilder r = null; 8724 int i; 8725 for (i=0; i<N; i++) { 8726 PackageParser.Provider p = pkg.providers.get(i); 8727 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 8728 p.info.processName, pkg.applicationInfo.uid); 8729 mProviders.addProvider(p); 8730 p.syncable = p.info.isSyncable; 8731 if (p.info.authority != null) { 8732 String names[] = p.info.authority.split(";"); 8733 p.info.authority = null; 8734 for (int j = 0; j < names.length; j++) { 8735 if (j == 1 && p.syncable) { 8736 // We only want the first authority for a provider to possibly be 8737 // syncable, so if we already added this provider using a different 8738 // authority clear the syncable flag. We copy the provider before 8739 // changing it because the mProviders object contains a reference 8740 // to a provider that we don't want to change. 8741 // Only do this for the second authority since the resulting provider 8742 // object can be the same for all future authorities for this provider. 8743 p = new PackageParser.Provider(p); 8744 p.syncable = false; 8745 } 8746 if (!mProvidersByAuthority.containsKey(names[j])) { 8747 mProvidersByAuthority.put(names[j], p); 8748 if (p.info.authority == null) { 8749 p.info.authority = names[j]; 8750 } else { 8751 p.info.authority = p.info.authority + ";" + names[j]; 8752 } 8753 if (DEBUG_PACKAGE_SCANNING) { 8754 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8755 Log.d(TAG, "Registered content provider: " + names[j] 8756 + ", className = " + p.info.name + ", isSyncable = " 8757 + p.info.isSyncable); 8758 } 8759 } else { 8760 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8761 Slog.w(TAG, "Skipping provider name " + names[j] + 8762 " (in package " + pkg.applicationInfo.packageName + 8763 "): name already used by " 8764 + ((other != null && other.getComponentName() != null) 8765 ? other.getComponentName().getPackageName() : "?")); 8766 } 8767 } 8768 } 8769 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8770 if (r == null) { 8771 r = new StringBuilder(256); 8772 } else { 8773 r.append(' '); 8774 } 8775 r.append(p.info.name); 8776 } 8777 } 8778 if (r != null) { 8779 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8780 } 8781 8782 N = pkg.services.size(); 8783 r = null; 8784 for (i=0; i<N; i++) { 8785 PackageParser.Service s = pkg.services.get(i); 8786 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8787 s.info.processName, pkg.applicationInfo.uid); 8788 mServices.addService(s); 8789 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8790 if (r == null) { 8791 r = new StringBuilder(256); 8792 } else { 8793 r.append(' '); 8794 } 8795 r.append(s.info.name); 8796 } 8797 } 8798 if (r != null) { 8799 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8800 } 8801 8802 N = pkg.receivers.size(); 8803 r = null; 8804 for (i=0; i<N; i++) { 8805 PackageParser.Activity a = pkg.receivers.get(i); 8806 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8807 a.info.processName, pkg.applicationInfo.uid); 8808 mReceivers.addActivity(a, "receiver"); 8809 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8810 if (r == null) { 8811 r = new StringBuilder(256); 8812 } else { 8813 r.append(' '); 8814 } 8815 r.append(a.info.name); 8816 } 8817 } 8818 if (r != null) { 8819 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8820 } 8821 8822 N = pkg.activities.size(); 8823 r = null; 8824 for (i=0; i<N; i++) { 8825 PackageParser.Activity a = pkg.activities.get(i); 8826 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8827 a.info.processName, pkg.applicationInfo.uid); 8828 mActivities.addActivity(a, "activity"); 8829 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8830 if (r == null) { 8831 r = new StringBuilder(256); 8832 } else { 8833 r.append(' '); 8834 } 8835 r.append(a.info.name); 8836 } 8837 } 8838 if (r != null) { 8839 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8840 } 8841 8842 N = pkg.permissionGroups.size(); 8843 r = null; 8844 for (i=0; i<N; i++) { 8845 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8846 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8847 if (cur == null) { 8848 mPermissionGroups.put(pg.info.name, pg); 8849 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8850 if (r == null) { 8851 r = new StringBuilder(256); 8852 } else { 8853 r.append(' '); 8854 } 8855 r.append(pg.info.name); 8856 } 8857 } else { 8858 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8859 + pg.info.packageName + " ignored: original from " 8860 + cur.info.packageName); 8861 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8862 if (r == null) { 8863 r = new StringBuilder(256); 8864 } else { 8865 r.append(' '); 8866 } 8867 r.append("DUP:"); 8868 r.append(pg.info.name); 8869 } 8870 } 8871 } 8872 if (r != null) { 8873 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8874 } 8875 8876 N = pkg.permissions.size(); 8877 r = null; 8878 for (i=0; i<N; i++) { 8879 PackageParser.Permission p = pkg.permissions.get(i); 8880 8881 // Assume by default that we did not install this permission into the system. 8882 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8883 8884 // Now that permission groups have a special meaning, we ignore permission 8885 // groups for legacy apps to prevent unexpected behavior. In particular, 8886 // permissions for one app being granted to someone just becase they happen 8887 // to be in a group defined by another app (before this had no implications). 8888 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8889 p.group = mPermissionGroups.get(p.info.group); 8890 // Warn for a permission in an unknown group. 8891 if (p.info.group != null && p.group == null) { 8892 Slog.w(TAG, "Permission " + p.info.name + " from package " 8893 + p.info.packageName + " in an unknown group " + p.info.group); 8894 } 8895 } 8896 8897 ArrayMap<String, BasePermission> permissionMap = 8898 p.tree ? mSettings.mPermissionTrees 8899 : mSettings.mPermissions; 8900 BasePermission bp = permissionMap.get(p.info.name); 8901 8902 // Allow system apps to redefine non-system permissions 8903 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8904 final boolean currentOwnerIsSystem = (bp.perm != null 8905 && isSystemApp(bp.perm.owner)); 8906 if (isSystemApp(p.owner)) { 8907 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8908 // It's a built-in permission and no owner, take ownership now 8909 bp.packageSetting = pkgSetting; 8910 bp.perm = p; 8911 bp.uid = pkg.applicationInfo.uid; 8912 bp.sourcePackage = p.info.packageName; 8913 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8914 } else if (!currentOwnerIsSystem) { 8915 String msg = "New decl " + p.owner + " of permission " 8916 + p.info.name + " is system; overriding " + bp.sourcePackage; 8917 reportSettingsProblem(Log.WARN, msg); 8918 bp = null; 8919 } 8920 } 8921 } 8922 8923 if (bp == null) { 8924 bp = new BasePermission(p.info.name, p.info.packageName, 8925 BasePermission.TYPE_NORMAL); 8926 permissionMap.put(p.info.name, bp); 8927 } 8928 8929 if (bp.perm == null) { 8930 if (bp.sourcePackage == null 8931 || bp.sourcePackage.equals(p.info.packageName)) { 8932 BasePermission tree = findPermissionTreeLP(p.info.name); 8933 if (tree == null 8934 || tree.sourcePackage.equals(p.info.packageName)) { 8935 bp.packageSetting = pkgSetting; 8936 bp.perm = p; 8937 bp.uid = pkg.applicationInfo.uid; 8938 bp.sourcePackage = p.info.packageName; 8939 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8940 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8941 if (r == null) { 8942 r = new StringBuilder(256); 8943 } else { 8944 r.append(' '); 8945 } 8946 r.append(p.info.name); 8947 } 8948 } else { 8949 Slog.w(TAG, "Permission " + p.info.name + " from package " 8950 + p.info.packageName + " ignored: base tree " 8951 + tree.name + " is from package " 8952 + tree.sourcePackage); 8953 } 8954 } else { 8955 Slog.w(TAG, "Permission " + p.info.name + " from package " 8956 + p.info.packageName + " ignored: original from " 8957 + bp.sourcePackage); 8958 } 8959 } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8960 if (r == null) { 8961 r = new StringBuilder(256); 8962 } else { 8963 r.append(' '); 8964 } 8965 r.append("DUP:"); 8966 r.append(p.info.name); 8967 } 8968 if (bp.perm == p) { 8969 bp.protectionLevel = p.info.protectionLevel; 8970 } 8971 } 8972 8973 if (r != null) { 8974 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 8975 } 8976 8977 N = pkg.instrumentation.size(); 8978 r = null; 8979 for (i=0; i<N; i++) { 8980 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8981 a.info.packageName = pkg.applicationInfo.packageName; 8982 a.info.sourceDir = pkg.applicationInfo.sourceDir; 8983 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 8984 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 8985 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 8986 a.info.dataDir = pkg.applicationInfo.dataDir; 8987 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 8988 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 8989 8990 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 8991 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 8992 mInstrumentation.put(a.getComponentName(), a); 8993 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8994 if (r == null) { 8995 r = new StringBuilder(256); 8996 } else { 8997 r.append(' '); 8998 } 8999 r.append(a.info.name); 9000 } 9001 } 9002 if (r != null) { 9003 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 9004 } 9005 9006 if (pkg.protectedBroadcasts != null) { 9007 N = pkg.protectedBroadcasts.size(); 9008 for (i=0; i<N; i++) { 9009 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 9010 } 9011 } 9012 9013 pkgSetting.setTimeStamp(scanFileTime); 9014 9015 // Create idmap files for pairs of (packages, overlay packages). 9016 // Note: "android", ie framework-res.apk, is handled by native layers. 9017 if (pkg.mOverlayTarget != null) { 9018 // This is an overlay package. 9019 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 9020 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 9021 mOverlays.put(pkg.mOverlayTarget, 9022 new ArrayMap<String, PackageParser.Package>()); 9023 } 9024 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 9025 map.put(pkg.packageName, pkg); 9026 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 9027 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 9028 createIdmapFailed = true; 9029 } 9030 } 9031 } else if (mOverlays.containsKey(pkg.packageName) && 9032 !pkg.packageName.equals("android")) { 9033 // This is a regular package, with one or more known overlay packages. 9034 createIdmapsForPackageLI(pkg); 9035 } 9036 } 9037 9038 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9039 9040 if (createIdmapFailed) { 9041 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 9042 "scanPackageLI failed to createIdmap"); 9043 } 9044 return pkg; 9045 } 9046 9047 private void maybeRenameForeignDexMarkers(PackageParser.Package existing, 9048 PackageParser.Package update, UserHandle user) { 9049 if (existing.applicationInfo == null || update.applicationInfo == null) { 9050 // This isn't due to an app installation. 9051 return; 9052 } 9053 9054 final File oldCodePath = new File(existing.applicationInfo.getCodePath()); 9055 final File newCodePath = new File(update.applicationInfo.getCodePath()); 9056 9057 // The codePath hasn't changed, so there's nothing for us to do. 9058 if (Objects.equals(oldCodePath, newCodePath)) { 9059 return; 9060 } 9061 9062 File canonicalNewCodePath; 9063 try { 9064 canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath)); 9065 } catch (IOException e) { 9066 Slog.w(TAG, "Failed to get canonical path.", e); 9067 return; 9068 } 9069 9070 // This is a bit of a hack. The oldCodePath doesn't exist at this point (because 9071 // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume 9072 // that the last component of the path (i.e, the name) doesn't need canonicalization 9073 // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now 9074 // but may change in the future. Hopefully this function won't exist at that point. 9075 final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(), 9076 oldCodePath.getName()); 9077 9078 // Calculate the prefixes of the markers. These are just the paths with "/" replaced 9079 // with "@". 9080 String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@'); 9081 if (!oldMarkerPrefix.endsWith("@")) { 9082 oldMarkerPrefix += "@"; 9083 } 9084 String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@'); 9085 if (!newMarkerPrefix.endsWith("@")) { 9086 newMarkerPrefix += "@"; 9087 } 9088 9089 List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly(); 9090 List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size()); 9091 for (String updatedPath : updatedPaths) { 9092 String updatedPathName = new File(updatedPath).getName(); 9093 markerSuffixes.add(updatedPathName.replace('/', '@')); 9094 } 9095 9096 for (int userId : resolveUserIds(user.getIdentifier())) { 9097 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId); 9098 9099 for (String markerSuffix : markerSuffixes) { 9100 File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix); 9101 File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix); 9102 if (oldForeignUseMark.exists()) { 9103 try { 9104 Os.rename(oldForeignUseMark.getAbsolutePath(), 9105 newForeignUseMark.getAbsolutePath()); 9106 } catch (ErrnoException e) { 9107 Slog.w(TAG, "Failed to rename foreign use marker", e); 9108 oldForeignUseMark.delete(); 9109 } 9110 } 9111 } 9112 } 9113 } 9114 9115 /** 9116 * Derive the ABI of a non-system package located at {@code scanFile}. This information 9117 * is derived purely on the basis of the contents of {@code scanFile} and 9118 * {@code cpuAbiOverride}. 9119 * 9120 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 9121 */ 9122 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 9123 String cpuAbiOverride, boolean extractLibs) 9124 throws PackageManagerException { 9125 // TODO: We can probably be smarter about this stuff. For installed apps, 9126 // we can calculate this information at install time once and for all. For 9127 // system apps, we can probably assume that this information doesn't change 9128 // after the first boot scan. As things stand, we do lots of unnecessary work. 9129 9130 // Give ourselves some initial paths; we'll come back for another 9131 // pass once we've determined ABI below. 9132 setNativeLibraryPaths(pkg); 9133 9134 // We would never need to extract libs for forward-locked and external packages, 9135 // since the container service will do it for us. We shouldn't attempt to 9136 // extract libs from system app when it was not updated. 9137 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 9138 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 9139 extractLibs = false; 9140 } 9141 9142 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 9143 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 9144 9145 NativeLibraryHelper.Handle handle = null; 9146 try { 9147 handle = NativeLibraryHelper.Handle.create(pkg); 9148 // TODO(multiArch): This can be null for apps that didn't go through the 9149 // usual installation process. We can calculate it again, like we 9150 // do during install time. 9151 // 9152 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 9153 // unnecessary. 9154 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 9155 9156 // Null out the abis so that they can be recalculated. 9157 pkg.applicationInfo.primaryCpuAbi = null; 9158 pkg.applicationInfo.secondaryCpuAbi = null; 9159 if (isMultiArch(pkg.applicationInfo)) { 9160 // Warn if we've set an abiOverride for multi-lib packages.. 9161 // By definition, we need to copy both 32 and 64 bit libraries for 9162 // such packages. 9163 if (pkg.cpuAbiOverride != null 9164 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 9165 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 9166 } 9167 9168 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 9169 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 9170 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 9171 if (extractLibs) { 9172 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9173 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 9174 useIsaSpecificSubdirs); 9175 } else { 9176 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 9177 } 9178 } 9179 9180 maybeThrowExceptionForMultiArchCopy( 9181 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 9182 9183 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 9184 if (extractLibs) { 9185 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9186 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 9187 useIsaSpecificSubdirs); 9188 } else { 9189 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 9190 } 9191 } 9192 9193 maybeThrowExceptionForMultiArchCopy( 9194 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 9195 9196 if (abi64 >= 0) { 9197 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 9198 } 9199 9200 if (abi32 >= 0) { 9201 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 9202 if (abi64 >= 0) { 9203 if (pkg.use32bitAbi) { 9204 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 9205 pkg.applicationInfo.primaryCpuAbi = abi; 9206 } else { 9207 pkg.applicationInfo.secondaryCpuAbi = abi; 9208 } 9209 } else { 9210 pkg.applicationInfo.primaryCpuAbi = abi; 9211 } 9212 } 9213 9214 } else { 9215 String[] abiList = (cpuAbiOverride != null) ? 9216 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 9217 9218 // Enable gross and lame hacks for apps that are built with old 9219 // SDK tools. We must scan their APKs for renderscript bitcode and 9220 // not launch them if it's present. Don't bother checking on devices 9221 // that don't have 64 bit support. 9222 boolean needsRenderScriptOverride = false; 9223 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 9224 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 9225 abiList = Build.SUPPORTED_32_BIT_ABIS; 9226 needsRenderScriptOverride = true; 9227 } 9228 9229 final int copyRet; 9230 if (extractLibs) { 9231 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9232 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 9233 } else { 9234 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 9235 } 9236 9237 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 9238 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 9239 "Error unpackaging native libs for app, errorCode=" + copyRet); 9240 } 9241 9242 if (copyRet >= 0) { 9243 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 9244 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 9245 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 9246 } else if (needsRenderScriptOverride) { 9247 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 9248 } 9249 } 9250 } catch (IOException ioe) { 9251 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 9252 } finally { 9253 IoUtils.closeQuietly(handle); 9254 } 9255 9256 // Now that we've calculated the ABIs and determined if it's an internal app, 9257 // we will go ahead and populate the nativeLibraryPath. 9258 setNativeLibraryPaths(pkg); 9259 } 9260 9261 /** 9262 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 9263 * i.e, so that all packages can be run inside a single process if required. 9264 * 9265 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 9266 * this function will either try and make the ABI for all packages in {@code packagesForUser} 9267 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 9268 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 9269 * updating a package that belongs to a shared user. 9270 * 9271 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 9272 * adds unnecessary complexity. 9273 */ 9274 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 9275 PackageParser.Package scannedPackage, boolean bootComplete) { 9276 String requiredInstructionSet = null; 9277 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 9278 requiredInstructionSet = VMRuntime.getInstructionSet( 9279 scannedPackage.applicationInfo.primaryCpuAbi); 9280 } 9281 9282 PackageSetting requirer = null; 9283 for (PackageSetting ps : packagesForUser) { 9284 // If packagesForUser contains scannedPackage, we skip it. This will happen 9285 // when scannedPackage is an update of an existing package. Without this check, 9286 // we will never be able to change the ABI of any package belonging to a shared 9287 // user, even if it's compatible with other packages. 9288 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9289 if (ps.primaryCpuAbiString == null) { 9290 continue; 9291 } 9292 9293 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 9294 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 9295 // We have a mismatch between instruction sets (say arm vs arm64) warn about 9296 // this but there's not much we can do. 9297 String errorMessage = "Instruction set mismatch, " 9298 + ((requirer == null) ? "[caller]" : requirer) 9299 + " requires " + requiredInstructionSet + " whereas " + ps 9300 + " requires " + instructionSet; 9301 Slog.w(TAG, errorMessage); 9302 } 9303 9304 if (requiredInstructionSet == null) { 9305 requiredInstructionSet = instructionSet; 9306 requirer = ps; 9307 } 9308 } 9309 } 9310 9311 if (requiredInstructionSet != null) { 9312 String adjustedAbi; 9313 if (requirer != null) { 9314 // requirer != null implies that either scannedPackage was null or that scannedPackage 9315 // did not require an ABI, in which case we have to adjust scannedPackage to match 9316 // the ABI of the set (which is the same as requirer's ABI) 9317 adjustedAbi = requirer.primaryCpuAbiString; 9318 if (scannedPackage != null) { 9319 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 9320 } 9321 } else { 9322 // requirer == null implies that we're updating all ABIs in the set to 9323 // match scannedPackage. 9324 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 9325 } 9326 9327 for (PackageSetting ps : packagesForUser) { 9328 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9329 if (ps.primaryCpuAbiString != null) { 9330 continue; 9331 } 9332 9333 ps.primaryCpuAbiString = adjustedAbi; 9334 if (ps.pkg != null && ps.pkg.applicationInfo != null && 9335 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 9336 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 9337 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 9338 + " (requirer=" 9339 + (requirer == null ? "null" : requirer.pkg.packageName) 9340 + ", scannedPackage=" 9341 + (scannedPackage != null ? scannedPackage.packageName : "null") 9342 + ")"); 9343 try { 9344 mInstaller.rmdex(ps.codePathString, 9345 getDexCodeInstructionSet(getPreferredInstructionSet())); 9346 } catch (InstallerException ignored) { 9347 } 9348 } 9349 } 9350 } 9351 } 9352 } 9353 9354 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 9355 synchronized (mPackages) { 9356 mResolverReplaced = true; 9357 // Set up information for custom user intent resolution activity. 9358 mResolveActivity.applicationInfo = pkg.applicationInfo; 9359 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 9360 mResolveActivity.packageName = pkg.applicationInfo.packageName; 9361 mResolveActivity.processName = pkg.applicationInfo.packageName; 9362 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9363 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9364 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9365 mResolveActivity.theme = 0; 9366 mResolveActivity.exported = true; 9367 mResolveActivity.enabled = true; 9368 mResolveInfo.activityInfo = mResolveActivity; 9369 mResolveInfo.priority = 0; 9370 mResolveInfo.preferredOrder = 0; 9371 mResolveInfo.match = 0; 9372 mResolveComponentName = mCustomResolverComponentName; 9373 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 9374 mResolveComponentName); 9375 } 9376 } 9377 9378 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 9379 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 9380 9381 // Set up information for ephemeral installer activity 9382 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 9383 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 9384 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 9385 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 9386 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9387 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9388 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9389 mEphemeralInstallerActivity.theme = 0; 9390 mEphemeralInstallerActivity.exported = true; 9391 mEphemeralInstallerActivity.enabled = true; 9392 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 9393 mEphemeralInstallerInfo.priority = 0; 9394 mEphemeralInstallerInfo.preferredOrder = 0; 9395 mEphemeralInstallerInfo.match = 0; 9396 9397 if (DEBUG_EPHEMERAL) { 9398 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 9399 } 9400 } 9401 9402 private static String calculateBundledApkRoot(final String codePathString) { 9403 final File codePath = new File(codePathString); 9404 final File codeRoot; 9405 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 9406 codeRoot = Environment.getRootDirectory(); 9407 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 9408 codeRoot = Environment.getOemDirectory(); 9409 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 9410 codeRoot = Environment.getVendorDirectory(); 9411 } else { 9412 // Unrecognized code path; take its top real segment as the apk root: 9413 // e.g. /something/app/blah.apk => /something 9414 try { 9415 File f = codePath.getCanonicalFile(); 9416 File parent = f.getParentFile(); // non-null because codePath is a file 9417 File tmp; 9418 while ((tmp = parent.getParentFile()) != null) { 9419 f = parent; 9420 parent = tmp; 9421 } 9422 codeRoot = f; 9423 Slog.w(TAG, "Unrecognized code path " 9424 + codePath + " - using " + codeRoot); 9425 } catch (IOException e) { 9426 // Can't canonicalize the code path -- shenanigans? 9427 Slog.w(TAG, "Can't canonicalize code path " + codePath); 9428 return Environment.getRootDirectory().getPath(); 9429 } 9430 } 9431 return codeRoot.getPath(); 9432 } 9433 9434 /** 9435 * Derive and set the location of native libraries for the given package, 9436 * which varies depending on where and how the package was installed. 9437 */ 9438 private void setNativeLibraryPaths(PackageParser.Package pkg) { 9439 final ApplicationInfo info = pkg.applicationInfo; 9440 final String codePath = pkg.codePath; 9441 final File codeFile = new File(codePath); 9442 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 9443 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 9444 9445 info.nativeLibraryRootDir = null; 9446 info.nativeLibraryRootRequiresIsa = false; 9447 info.nativeLibraryDir = null; 9448 info.secondaryNativeLibraryDir = null; 9449 9450 if (isApkFile(codeFile)) { 9451 // Monolithic install 9452 if (bundledApp) { 9453 // If "/system/lib64/apkname" exists, assume that is the per-package 9454 // native library directory to use; otherwise use "/system/lib/apkname". 9455 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 9456 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 9457 getPrimaryInstructionSet(info)); 9458 9459 // This is a bundled system app so choose the path based on the ABI. 9460 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 9461 // is just the default path. 9462 final String apkName = deriveCodePathName(codePath); 9463 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 9464 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 9465 apkName).getAbsolutePath(); 9466 9467 if (info.secondaryCpuAbi != null) { 9468 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 9469 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 9470 secondaryLibDir, apkName).getAbsolutePath(); 9471 } 9472 } else if (asecApp) { 9473 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 9474 .getAbsolutePath(); 9475 } else { 9476 final String apkName = deriveCodePathName(codePath); 9477 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 9478 .getAbsolutePath(); 9479 } 9480 9481 info.nativeLibraryRootRequiresIsa = false; 9482 info.nativeLibraryDir = info.nativeLibraryRootDir; 9483 } else { 9484 // Cluster install 9485 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 9486 info.nativeLibraryRootRequiresIsa = true; 9487 9488 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 9489 getPrimaryInstructionSet(info)).getAbsolutePath(); 9490 9491 if (info.secondaryCpuAbi != null) { 9492 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 9493 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 9494 } 9495 } 9496 } 9497 9498 /** 9499 * Calculate the abis and roots for a bundled app. These can uniquely 9500 * be determined from the contents of the system partition, i.e whether 9501 * it contains 64 or 32 bit shared libraries etc. We do not validate any 9502 * of this information, and instead assume that the system was built 9503 * sensibly. 9504 */ 9505 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 9506 PackageSetting pkgSetting) { 9507 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 9508 9509 // If "/system/lib64/apkname" exists, assume that is the per-package 9510 // native library directory to use; otherwise use "/system/lib/apkname". 9511 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 9512 setBundledAppAbi(pkg, apkRoot, apkName); 9513 // pkgSetting might be null during rescan following uninstall of updates 9514 // to a bundled app, so accommodate that possibility. The settings in 9515 // that case will be established later from the parsed package. 9516 // 9517 // If the settings aren't null, sync them up with what we've just derived. 9518 // note that apkRoot isn't stored in the package settings. 9519 if (pkgSetting != null) { 9520 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9521 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9522 } 9523 } 9524 9525 /** 9526 * Deduces the ABI of a bundled app and sets the relevant fields on the 9527 * parsed pkg object. 9528 * 9529 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 9530 * under which system libraries are installed. 9531 * @param apkName the name of the installed package. 9532 */ 9533 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 9534 final File codeFile = new File(pkg.codePath); 9535 9536 final boolean has64BitLibs; 9537 final boolean has32BitLibs; 9538 if (isApkFile(codeFile)) { 9539 // Monolithic install 9540 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 9541 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 9542 } else { 9543 // Cluster install 9544 final File rootDir = new File(codeFile, LIB_DIR_NAME); 9545 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 9546 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 9547 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 9548 has64BitLibs = (new File(rootDir, isa)).exists(); 9549 } else { 9550 has64BitLibs = false; 9551 } 9552 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 9553 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 9554 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 9555 has32BitLibs = (new File(rootDir, isa)).exists(); 9556 } else { 9557 has32BitLibs = false; 9558 } 9559 } 9560 9561 if (has64BitLibs && !has32BitLibs) { 9562 // The package has 64 bit libs, but not 32 bit libs. Its primary 9563 // ABI should be 64 bit. We can safely assume here that the bundled 9564 // native libraries correspond to the most preferred ABI in the list. 9565 9566 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9567 pkg.applicationInfo.secondaryCpuAbi = null; 9568 } else if (has32BitLibs && !has64BitLibs) { 9569 // The package has 32 bit libs but not 64 bit libs. Its primary 9570 // ABI should be 32 bit. 9571 9572 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9573 pkg.applicationInfo.secondaryCpuAbi = null; 9574 } else if (has32BitLibs && has64BitLibs) { 9575 // The application has both 64 and 32 bit bundled libraries. We check 9576 // here that the app declares multiArch support, and warn if it doesn't. 9577 // 9578 // We will be lenient here and record both ABIs. The primary will be the 9579 // ABI that's higher on the list, i.e, a device that's configured to prefer 9580 // 64 bit apps will see a 64 bit primary ABI, 9581 9582 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 9583 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 9584 } 9585 9586 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 9587 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9588 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9589 } else { 9590 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9591 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9592 } 9593 } else { 9594 pkg.applicationInfo.primaryCpuAbi = null; 9595 pkg.applicationInfo.secondaryCpuAbi = null; 9596 } 9597 } 9598 9599 private void killApplication(String pkgName, int appId, String reason) { 9600 killApplication(pkgName, appId, UserHandle.USER_ALL, reason); 9601 } 9602 9603 private void killApplication(String pkgName, int appId, int userId, String reason) { 9604 // Request the ActivityManager to kill the process(only for existing packages) 9605 // so that we do not end up in a confused state while the user is still using the older 9606 // version of the application while the new one gets installed. 9607 final long token = Binder.clearCallingIdentity(); 9608 try { 9609 IActivityManager am = ActivityManagerNative.getDefault(); 9610 if (am != null) { 9611 try { 9612 am.killApplication(pkgName, appId, userId, reason); 9613 } catch (RemoteException e) { 9614 } 9615 } 9616 } finally { 9617 Binder.restoreCallingIdentity(token); 9618 } 9619 } 9620 9621 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 9622 // Remove the parent package setting 9623 PackageSetting ps = (PackageSetting) pkg.mExtras; 9624 if (ps != null) { 9625 removePackageLI(ps, chatty); 9626 } 9627 // Remove the child package setting 9628 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9629 for (int i = 0; i < childCount; i++) { 9630 PackageParser.Package childPkg = pkg.childPackages.get(i); 9631 ps = (PackageSetting) childPkg.mExtras; 9632 if (ps != null) { 9633 removePackageLI(ps, chatty); 9634 } 9635 } 9636 } 9637 9638 void removePackageLI(PackageSetting ps, boolean chatty) { 9639 if (DEBUG_INSTALL) { 9640 if (chatty) 9641 Log.d(TAG, "Removing package " + ps.name); 9642 } 9643 9644 // writer 9645 synchronized (mPackages) { 9646 mPackages.remove(ps.name); 9647 final PackageParser.Package pkg = ps.pkg; 9648 if (pkg != null) { 9649 cleanPackageDataStructuresLILPw(pkg, chatty); 9650 } 9651 } 9652 } 9653 9654 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 9655 if (DEBUG_INSTALL) { 9656 if (chatty) 9657 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 9658 } 9659 9660 // writer 9661 synchronized (mPackages) { 9662 // Remove the parent package 9663 mPackages.remove(pkg.applicationInfo.packageName); 9664 cleanPackageDataStructuresLILPw(pkg, chatty); 9665 9666 // Remove the child packages 9667 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9668 for (int i = 0; i < childCount; i++) { 9669 PackageParser.Package childPkg = pkg.childPackages.get(i); 9670 mPackages.remove(childPkg.applicationInfo.packageName); 9671 cleanPackageDataStructuresLILPw(childPkg, chatty); 9672 } 9673 } 9674 } 9675 9676 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 9677 int N = pkg.providers.size(); 9678 StringBuilder r = null; 9679 int i; 9680 for (i=0; i<N; i++) { 9681 PackageParser.Provider p = pkg.providers.get(i); 9682 mProviders.removeProvider(p); 9683 if (p.info.authority == null) { 9684 9685 /* There was another ContentProvider with this authority when 9686 * this app was installed so this authority is null, 9687 * Ignore it as we don't have to unregister the provider. 9688 */ 9689 continue; 9690 } 9691 String names[] = p.info.authority.split(";"); 9692 for (int j = 0; j < names.length; j++) { 9693 if (mProvidersByAuthority.get(names[j]) == p) { 9694 mProvidersByAuthority.remove(names[j]); 9695 if (DEBUG_REMOVE) { 9696 if (chatty) 9697 Log.d(TAG, "Unregistered content provider: " + names[j] 9698 + ", className = " + p.info.name + ", isSyncable = " 9699 + p.info.isSyncable); 9700 } 9701 } 9702 } 9703 if (DEBUG_REMOVE && chatty) { 9704 if (r == null) { 9705 r = new StringBuilder(256); 9706 } else { 9707 r.append(' '); 9708 } 9709 r.append(p.info.name); 9710 } 9711 } 9712 if (r != null) { 9713 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 9714 } 9715 9716 N = pkg.services.size(); 9717 r = null; 9718 for (i=0; i<N; i++) { 9719 PackageParser.Service s = pkg.services.get(i); 9720 mServices.removeService(s); 9721 if (chatty) { 9722 if (r == null) { 9723 r = new StringBuilder(256); 9724 } else { 9725 r.append(' '); 9726 } 9727 r.append(s.info.name); 9728 } 9729 } 9730 if (r != null) { 9731 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 9732 } 9733 9734 N = pkg.receivers.size(); 9735 r = null; 9736 for (i=0; i<N; i++) { 9737 PackageParser.Activity a = pkg.receivers.get(i); 9738 mReceivers.removeActivity(a, "receiver"); 9739 if (DEBUG_REMOVE && chatty) { 9740 if (r == null) { 9741 r = new StringBuilder(256); 9742 } else { 9743 r.append(' '); 9744 } 9745 r.append(a.info.name); 9746 } 9747 } 9748 if (r != null) { 9749 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 9750 } 9751 9752 N = pkg.activities.size(); 9753 r = null; 9754 for (i=0; i<N; i++) { 9755 PackageParser.Activity a = pkg.activities.get(i); 9756 mActivities.removeActivity(a, "activity"); 9757 if (DEBUG_REMOVE && chatty) { 9758 if (r == null) { 9759 r = new StringBuilder(256); 9760 } else { 9761 r.append(' '); 9762 } 9763 r.append(a.info.name); 9764 } 9765 } 9766 if (r != null) { 9767 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 9768 } 9769 9770 N = pkg.permissions.size(); 9771 r = null; 9772 for (i=0; i<N; i++) { 9773 PackageParser.Permission p = pkg.permissions.get(i); 9774 BasePermission bp = mSettings.mPermissions.get(p.info.name); 9775 if (bp == null) { 9776 bp = mSettings.mPermissionTrees.get(p.info.name); 9777 } 9778 if (bp != null && bp.perm == p) { 9779 bp.perm = null; 9780 if (DEBUG_REMOVE && chatty) { 9781 if (r == null) { 9782 r = new StringBuilder(256); 9783 } else { 9784 r.append(' '); 9785 } 9786 r.append(p.info.name); 9787 } 9788 } 9789 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9790 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 9791 if (appOpPkgs != null) { 9792 appOpPkgs.remove(pkg.packageName); 9793 } 9794 } 9795 } 9796 if (r != null) { 9797 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9798 } 9799 9800 N = pkg.requestedPermissions.size(); 9801 r = null; 9802 for (i=0; i<N; i++) { 9803 String perm = pkg.requestedPermissions.get(i); 9804 BasePermission bp = mSettings.mPermissions.get(perm); 9805 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9806 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 9807 if (appOpPkgs != null) { 9808 appOpPkgs.remove(pkg.packageName); 9809 if (appOpPkgs.isEmpty()) { 9810 mAppOpPermissionPackages.remove(perm); 9811 } 9812 } 9813 } 9814 } 9815 if (r != null) { 9816 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9817 } 9818 9819 N = pkg.instrumentation.size(); 9820 r = null; 9821 for (i=0; i<N; i++) { 9822 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9823 mInstrumentation.remove(a.getComponentName()); 9824 if (DEBUG_REMOVE && chatty) { 9825 if (r == null) { 9826 r = new StringBuilder(256); 9827 } else { 9828 r.append(' '); 9829 } 9830 r.append(a.info.name); 9831 } 9832 } 9833 if (r != null) { 9834 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9835 } 9836 9837 r = null; 9838 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9839 // Only system apps can hold shared libraries. 9840 if (pkg.libraryNames != null) { 9841 for (i=0; i<pkg.libraryNames.size(); i++) { 9842 String name = pkg.libraryNames.get(i); 9843 SharedLibraryEntry cur = mSharedLibraries.get(name); 9844 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9845 mSharedLibraries.remove(name); 9846 if (DEBUG_REMOVE && chatty) { 9847 if (r == null) { 9848 r = new StringBuilder(256); 9849 } else { 9850 r.append(' '); 9851 } 9852 r.append(name); 9853 } 9854 } 9855 } 9856 } 9857 } 9858 if (r != null) { 9859 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9860 } 9861 } 9862 9863 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9864 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9865 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9866 return true; 9867 } 9868 } 9869 return false; 9870 } 9871 9872 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9873 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9874 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9875 9876 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9877 // Update the parent permissions 9878 updatePermissionsLPw(pkg.packageName, pkg, flags); 9879 // Update the child permissions 9880 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9881 for (int i = 0; i < childCount; i++) { 9882 PackageParser.Package childPkg = pkg.childPackages.get(i); 9883 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9884 } 9885 } 9886 9887 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9888 int flags) { 9889 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9890 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9891 } 9892 9893 private void updatePermissionsLPw(String changingPkg, 9894 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9895 // Make sure there are no dangling permission trees. 9896 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9897 while (it.hasNext()) { 9898 final BasePermission bp = it.next(); 9899 if (bp.packageSetting == null) { 9900 // We may not yet have parsed the package, so just see if 9901 // we still know about its settings. 9902 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9903 } 9904 if (bp.packageSetting == null) { 9905 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9906 + " from package " + bp.sourcePackage); 9907 it.remove(); 9908 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9909 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9910 Slog.i(TAG, "Removing old permission tree: " + bp.name 9911 + " from package " + bp.sourcePackage); 9912 flags |= UPDATE_PERMISSIONS_ALL; 9913 it.remove(); 9914 } 9915 } 9916 } 9917 9918 // Make sure all dynamic permissions have been assigned to a package, 9919 // and make sure there are no dangling permissions. 9920 it = mSettings.mPermissions.values().iterator(); 9921 while (it.hasNext()) { 9922 final BasePermission bp = it.next(); 9923 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9924 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9925 + bp.name + " pkg=" + bp.sourcePackage 9926 + " info=" + bp.pendingInfo); 9927 if (bp.packageSetting == null && bp.pendingInfo != null) { 9928 final BasePermission tree = findPermissionTreeLP(bp.name); 9929 if (tree != null && tree.perm != null) { 9930 bp.packageSetting = tree.packageSetting; 9931 bp.perm = new PackageParser.Permission(tree.perm.owner, 9932 new PermissionInfo(bp.pendingInfo)); 9933 bp.perm.info.packageName = tree.perm.info.packageName; 9934 bp.perm.info.name = bp.name; 9935 bp.uid = tree.uid; 9936 } 9937 } 9938 } 9939 if (bp.packageSetting == null) { 9940 // We may not yet have parsed the package, so just see if 9941 // we still know about its settings. 9942 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9943 } 9944 if (bp.packageSetting == null) { 9945 Slog.w(TAG, "Removing dangling permission: " + bp.name 9946 + " from package " + bp.sourcePackage); 9947 it.remove(); 9948 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9949 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9950 Slog.i(TAG, "Removing old permission: " + bp.name 9951 + " from package " + bp.sourcePackage); 9952 flags |= UPDATE_PERMISSIONS_ALL; 9953 it.remove(); 9954 } 9955 } 9956 } 9957 9958 // Now update the permissions for all packages, in particular 9959 // replace the granted permissions of the system packages. 9960 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9961 for (PackageParser.Package pkg : mPackages.values()) { 9962 if (pkg != pkgInfo) { 9963 // Only replace for packages on requested volume 9964 final String volumeUuid = getVolumeUuidForPackage(pkg); 9965 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9966 && Objects.equals(replaceVolumeUuid, volumeUuid); 9967 grantPermissionsLPw(pkg, replace, changingPkg); 9968 } 9969 } 9970 } 9971 9972 if (pkgInfo != null) { 9973 // Only replace for packages on requested volume 9974 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9975 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9976 && Objects.equals(replaceVolumeUuid, volumeUuid); 9977 grantPermissionsLPw(pkgInfo, replace, changingPkg); 9978 } 9979 } 9980 9981 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 9982 String packageOfInterest) { 9983 // IMPORTANT: There are two types of permissions: install and runtime. 9984 // Install time permissions are granted when the app is installed to 9985 // all device users and users added in the future. Runtime permissions 9986 // are granted at runtime explicitly to specific users. Normal and signature 9987 // protected permissions are install time permissions. Dangerous permissions 9988 // are install permissions if the app's target SDK is Lollipop MR1 or older, 9989 // otherwise they are runtime permissions. This function does not manage 9990 // runtime permissions except for the case an app targeting Lollipop MR1 9991 // being upgraded to target a newer SDK, in which case dangerous permissions 9992 // are transformed from install time to runtime ones. 9993 9994 final PackageSetting ps = (PackageSetting) pkg.mExtras; 9995 if (ps == null) { 9996 return; 9997 } 9998 9999 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 10000 10001 PermissionsState permissionsState = ps.getPermissionsState(); 10002 PermissionsState origPermissions = permissionsState; 10003 10004 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 10005 10006 boolean runtimePermissionsRevoked = false; 10007 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 10008 10009 boolean changedInstallPermission = false; 10010 10011 if (replace) { 10012 ps.installPermissionsFixed = false; 10013 if (!ps.isSharedUser()) { 10014 origPermissions = new PermissionsState(permissionsState); 10015 permissionsState.reset(); 10016 } else { 10017 // We need to know only about runtime permission changes since the 10018 // calling code always writes the install permissions state but 10019 // the runtime ones are written only if changed. The only cases of 10020 // changed runtime permissions here are promotion of an install to 10021 // runtime and revocation of a runtime from a shared user. 10022 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 10023 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 10024 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 10025 runtimePermissionsRevoked = true; 10026 } 10027 } 10028 } 10029 10030 permissionsState.setGlobalGids(mGlobalGids); 10031 10032 final int N = pkg.requestedPermissions.size(); 10033 for (int i=0; i<N; i++) { 10034 final String name = pkg.requestedPermissions.get(i); 10035 final BasePermission bp = mSettings.mPermissions.get(name); 10036 10037 if (DEBUG_INSTALL) { 10038 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 10039 } 10040 10041 if (bp == null || bp.packageSetting == null) { 10042 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 10043 Slog.w(TAG, "Unknown permission " + name 10044 + " in package " + pkg.packageName); 10045 } 10046 continue; 10047 } 10048 10049 final String perm = bp.name; 10050 boolean allowedSig = false; 10051 int grant = GRANT_DENIED; 10052 10053 // Keep track of app op permissions. 10054 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 10055 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 10056 if (pkgs == null) { 10057 pkgs = new ArraySet<>(); 10058 mAppOpPermissionPackages.put(bp.name, pkgs); 10059 } 10060 pkgs.add(pkg.packageName); 10061 } 10062 10063 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 10064 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 10065 >= Build.VERSION_CODES.M; 10066 switch (level) { 10067 case PermissionInfo.PROTECTION_NORMAL: { 10068 // For all apps normal permissions are install time ones. 10069 grant = GRANT_INSTALL; 10070 } break; 10071 10072 case PermissionInfo.PROTECTION_DANGEROUS: { 10073 // If a permission review is required for legacy apps we represent 10074 // their permissions as always granted runtime ones since we need 10075 // to keep the review required permission flag per user while an 10076 // install permission's state is shared across all users. 10077 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 10078 // For legacy apps dangerous permissions are install time ones. 10079 grant = GRANT_INSTALL; 10080 } else if (origPermissions.hasInstallPermission(bp.name)) { 10081 // For legacy apps that became modern, install becomes runtime. 10082 grant = GRANT_UPGRADE; 10083 } else if (mPromoteSystemApps 10084 && isSystemApp(ps) 10085 && mExistingSystemPackages.contains(ps.name)) { 10086 // For legacy system apps, install becomes runtime. 10087 // We cannot check hasInstallPermission() for system apps since those 10088 // permissions were granted implicitly and not persisted pre-M. 10089 grant = GRANT_UPGRADE; 10090 } else { 10091 // For modern apps keep runtime permissions unchanged. 10092 grant = GRANT_RUNTIME; 10093 } 10094 } break; 10095 10096 case PermissionInfo.PROTECTION_SIGNATURE: { 10097 // For all apps signature permissions are install time ones. 10098 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 10099 if (allowedSig) { 10100 grant = GRANT_INSTALL; 10101 } 10102 } break; 10103 } 10104 10105 if (DEBUG_INSTALL) { 10106 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 10107 } 10108 10109 if (grant != GRANT_DENIED) { 10110 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 10111 // If this is an existing, non-system package, then 10112 // we can't add any new permissions to it. 10113 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 10114 // Except... if this is a permission that was added 10115 // to the platform (note: need to only do this when 10116 // updating the platform). 10117 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 10118 grant = GRANT_DENIED; 10119 } 10120 } 10121 } 10122 10123 switch (grant) { 10124 case GRANT_INSTALL: { 10125 // Revoke this as runtime permission to handle the case of 10126 // a runtime permission being downgraded to an install one. 10127 // Also in permission review mode we keep dangerous permissions 10128 // for legacy apps 10129 for (int userId : UserManagerService.getInstance().getUserIds()) { 10130 if (origPermissions.getRuntimePermissionState( 10131 bp.name, userId) != null) { 10132 // Revoke the runtime permission and clear the flags. 10133 origPermissions.revokeRuntimePermission(bp, userId); 10134 origPermissions.updatePermissionFlags(bp, userId, 10135 PackageManager.MASK_PERMISSION_FLAGS, 0); 10136 // If we revoked a permission permission, we have to write. 10137 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10138 changedRuntimePermissionUserIds, userId); 10139 } 10140 } 10141 // Grant an install permission. 10142 if (permissionsState.grantInstallPermission(bp) != 10143 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10144 changedInstallPermission = true; 10145 } 10146 } break; 10147 10148 case GRANT_RUNTIME: { 10149 // Grant previously granted runtime permissions. 10150 for (int userId : UserManagerService.getInstance().getUserIds()) { 10151 PermissionState permissionState = origPermissions 10152 .getRuntimePermissionState(bp.name, userId); 10153 int flags = permissionState != null 10154 ? permissionState.getFlags() : 0; 10155 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 10156 if (permissionsState.grantRuntimePermission(bp, userId) == 10157 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10158 // If we cannot put the permission as it was, we have to write. 10159 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10160 changedRuntimePermissionUserIds, userId); 10161 } 10162 // If the app supports runtime permissions no need for a review. 10163 if (Build.PERMISSIONS_REVIEW_REQUIRED 10164 && appSupportsRuntimePermissions 10165 && (flags & PackageManager 10166 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 10167 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 10168 // Since we changed the flags, we have to write. 10169 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10170 changedRuntimePermissionUserIds, userId); 10171 } 10172 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 10173 && !appSupportsRuntimePermissions) { 10174 // For legacy apps that need a permission review, every new 10175 // runtime permission is granted but it is pending a review. 10176 // We also need to review only platform defined runtime 10177 // permissions as these are the only ones the platform knows 10178 // how to disable the API to simulate revocation as legacy 10179 // apps don't expect to run with revoked permissions. 10180 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 10181 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 10182 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 10183 // We changed the flags, hence have to write. 10184 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10185 changedRuntimePermissionUserIds, userId); 10186 } 10187 } 10188 if (permissionsState.grantRuntimePermission(bp, userId) 10189 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10190 // We changed the permission, hence have to write. 10191 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10192 changedRuntimePermissionUserIds, userId); 10193 } 10194 } 10195 // Propagate the permission flags. 10196 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 10197 } 10198 } break; 10199 10200 case GRANT_UPGRADE: { 10201 // Grant runtime permissions for a previously held install permission. 10202 PermissionState permissionState = origPermissions 10203 .getInstallPermissionState(bp.name); 10204 final int flags = permissionState != null ? permissionState.getFlags() : 0; 10205 10206 if (origPermissions.revokeInstallPermission(bp) 10207 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10208 // We will be transferring the permission flags, so clear them. 10209 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 10210 PackageManager.MASK_PERMISSION_FLAGS, 0); 10211 changedInstallPermission = true; 10212 } 10213 10214 // If the permission is not to be promoted to runtime we ignore it and 10215 // also its other flags as they are not applicable to install permissions. 10216 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 10217 for (int userId : currentUserIds) { 10218 if (permissionsState.grantRuntimePermission(bp, userId) != 10219 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10220 // Transfer the permission flags. 10221 permissionsState.updatePermissionFlags(bp, userId, 10222 flags, flags); 10223 // If we granted the permission, we have to write. 10224 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10225 changedRuntimePermissionUserIds, userId); 10226 } 10227 } 10228 } 10229 } break; 10230 10231 default: { 10232 if (packageOfInterest == null 10233 || packageOfInterest.equals(pkg.packageName)) { 10234 Slog.w(TAG, "Not granting permission " + perm 10235 + " to package " + pkg.packageName 10236 + " because it was previously installed without"); 10237 } 10238 } break; 10239 } 10240 } else { 10241 if (permissionsState.revokeInstallPermission(bp) != 10242 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10243 // Also drop the permission flags. 10244 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 10245 PackageManager.MASK_PERMISSION_FLAGS, 0); 10246 changedInstallPermission = true; 10247 Slog.i(TAG, "Un-granting permission " + perm 10248 + " from package " + pkg.packageName 10249 + " (protectionLevel=" + bp.protectionLevel 10250 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10251 + ")"); 10252 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 10253 // Don't print warning for app op permissions, since it is fine for them 10254 // not to be granted, there is a UI for the user to decide. 10255 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 10256 Slog.w(TAG, "Not granting permission " + perm 10257 + " to package " + pkg.packageName 10258 + " (protectionLevel=" + bp.protectionLevel 10259 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10260 + ")"); 10261 } 10262 } 10263 } 10264 } 10265 10266 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 10267 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 10268 // This is the first that we have heard about this package, so the 10269 // permissions we have now selected are fixed until explicitly 10270 // changed. 10271 ps.installPermissionsFixed = true; 10272 } 10273 10274 // Persist the runtime permissions state for users with changes. If permissions 10275 // were revoked because no app in the shared user declares them we have to 10276 // write synchronously to avoid losing runtime permissions state. 10277 for (int userId : changedRuntimePermissionUserIds) { 10278 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 10279 } 10280 10281 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10282 } 10283 10284 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 10285 boolean allowed = false; 10286 final int NP = PackageParser.NEW_PERMISSIONS.length; 10287 for (int ip=0; ip<NP; ip++) { 10288 final PackageParser.NewPermissionInfo npi 10289 = PackageParser.NEW_PERMISSIONS[ip]; 10290 if (npi.name.equals(perm) 10291 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 10292 allowed = true; 10293 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 10294 + pkg.packageName); 10295 break; 10296 } 10297 } 10298 return allowed; 10299 } 10300 10301 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 10302 BasePermission bp, PermissionsState origPermissions) { 10303 boolean allowed; 10304 allowed = (compareSignatures( 10305 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 10306 == PackageManager.SIGNATURE_MATCH) 10307 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 10308 == PackageManager.SIGNATURE_MATCH); 10309 if (!allowed && (bp.protectionLevel 10310 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 10311 if (isSystemApp(pkg)) { 10312 // For updated system applications, a system permission 10313 // is granted only if it had been defined by the original application. 10314 if (pkg.isUpdatedSystemApp()) { 10315 final PackageSetting sysPs = mSettings 10316 .getDisabledSystemPkgLPr(pkg.packageName); 10317 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 10318 // If the original was granted this permission, we take 10319 // that grant decision as read and propagate it to the 10320 // update. 10321 if (sysPs.isPrivileged()) { 10322 allowed = true; 10323 } 10324 } else { 10325 // The system apk may have been updated with an older 10326 // version of the one on the data partition, but which 10327 // granted a new system permission that it didn't have 10328 // before. In this case we do want to allow the app to 10329 // now get the new permission if the ancestral apk is 10330 // privileged to get it. 10331 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 10332 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 10333 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 10334 allowed = true; 10335 break; 10336 } 10337 } 10338 } 10339 // Also if a privileged parent package on the system image or any of 10340 // its children requested a privileged permission, the updated child 10341 // packages can also get the permission. 10342 if (pkg.parentPackage != null) { 10343 final PackageSetting disabledSysParentPs = mSettings 10344 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 10345 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 10346 && disabledSysParentPs.isPrivileged()) { 10347 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 10348 allowed = true; 10349 } else if (disabledSysParentPs.pkg.childPackages != null) { 10350 final int count = disabledSysParentPs.pkg.childPackages.size(); 10351 for (int i = 0; i < count; i++) { 10352 PackageParser.Package disabledSysChildPkg = 10353 disabledSysParentPs.pkg.childPackages.get(i); 10354 if (isPackageRequestingPermission(disabledSysChildPkg, 10355 perm)) { 10356 allowed = true; 10357 break; 10358 } 10359 } 10360 } 10361 } 10362 } 10363 } 10364 } else { 10365 allowed = isPrivilegedApp(pkg); 10366 } 10367 } 10368 } 10369 if (!allowed) { 10370 if (!allowed && (bp.protectionLevel 10371 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 10372 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 10373 // If this was a previously normal/dangerous permission that got moved 10374 // to a system permission as part of the runtime permission redesign, then 10375 // we still want to blindly grant it to old apps. 10376 allowed = true; 10377 } 10378 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 10379 && pkg.packageName.equals(mRequiredInstallerPackage)) { 10380 // If this permission is to be granted to the system installer and 10381 // this app is an installer, then it gets the permission. 10382 allowed = true; 10383 } 10384 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 10385 && pkg.packageName.equals(mRequiredVerifierPackage)) { 10386 // If this permission is to be granted to the system verifier and 10387 // this app is a verifier, then it gets the permission. 10388 allowed = true; 10389 } 10390 if (!allowed && (bp.protectionLevel 10391 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 10392 && isSystemApp(pkg)) { 10393 // Any pre-installed system app is allowed to get this permission. 10394 allowed = true; 10395 } 10396 if (!allowed && (bp.protectionLevel 10397 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 10398 // For development permissions, a development permission 10399 // is granted only if it was already granted. 10400 allowed = origPermissions.hasInstallPermission(perm); 10401 } 10402 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 10403 && pkg.packageName.equals(mSetupWizardPackage)) { 10404 // If this permission is to be granted to the system setup wizard and 10405 // this app is a setup wizard, then it gets the permission. 10406 allowed = true; 10407 } 10408 } 10409 return allowed; 10410 } 10411 10412 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 10413 final int permCount = pkg.requestedPermissions.size(); 10414 for (int j = 0; j < permCount; j++) { 10415 String requestedPermission = pkg.requestedPermissions.get(j); 10416 if (permission.equals(requestedPermission)) { 10417 return true; 10418 } 10419 } 10420 return false; 10421 } 10422 10423 final class ActivityIntentResolver 10424 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 10425 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10426 boolean defaultOnly, int userId) { 10427 if (!sUserManager.exists(userId)) return null; 10428 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10429 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10430 } 10431 10432 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10433 int userId) { 10434 if (!sUserManager.exists(userId)) return null; 10435 mFlags = flags; 10436 return super.queryIntent(intent, resolvedType, 10437 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10438 } 10439 10440 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10441 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 10442 if (!sUserManager.exists(userId)) return null; 10443 if (packageActivities == null) { 10444 return null; 10445 } 10446 mFlags = flags; 10447 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10448 final int N = packageActivities.size(); 10449 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 10450 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 10451 10452 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 10453 for (int i = 0; i < N; ++i) { 10454 intentFilters = packageActivities.get(i).intents; 10455 if (intentFilters != null && intentFilters.size() > 0) { 10456 PackageParser.ActivityIntentInfo[] array = 10457 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 10458 intentFilters.toArray(array); 10459 listCut.add(array); 10460 } 10461 } 10462 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10463 } 10464 10465 /** 10466 * Finds a privileged activity that matches the specified activity names. 10467 */ 10468 private PackageParser.Activity findMatchingActivity( 10469 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 10470 for (PackageParser.Activity sysActivity : activityList) { 10471 if (sysActivity.info.name.equals(activityInfo.name)) { 10472 return sysActivity; 10473 } 10474 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 10475 return sysActivity; 10476 } 10477 if (sysActivity.info.targetActivity != null) { 10478 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 10479 return sysActivity; 10480 } 10481 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 10482 return sysActivity; 10483 } 10484 } 10485 } 10486 return null; 10487 } 10488 10489 public class IterGenerator<E> { 10490 public Iterator<E> generate(ActivityIntentInfo info) { 10491 return null; 10492 } 10493 } 10494 10495 public class ActionIterGenerator extends IterGenerator<String> { 10496 @Override 10497 public Iterator<String> generate(ActivityIntentInfo info) { 10498 return info.actionsIterator(); 10499 } 10500 } 10501 10502 public class CategoriesIterGenerator extends IterGenerator<String> { 10503 @Override 10504 public Iterator<String> generate(ActivityIntentInfo info) { 10505 return info.categoriesIterator(); 10506 } 10507 } 10508 10509 public class SchemesIterGenerator extends IterGenerator<String> { 10510 @Override 10511 public Iterator<String> generate(ActivityIntentInfo info) { 10512 return info.schemesIterator(); 10513 } 10514 } 10515 10516 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 10517 @Override 10518 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 10519 return info.authoritiesIterator(); 10520 } 10521 } 10522 10523 /** 10524 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 10525 * MODIFIED. Do not pass in a list that should not be changed. 10526 */ 10527 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 10528 IterGenerator<T> generator, Iterator<T> searchIterator) { 10529 // loop through the set of actions; every one must be found in the intent filter 10530 while (searchIterator.hasNext()) { 10531 // we must have at least one filter in the list to consider a match 10532 if (intentList.size() == 0) { 10533 break; 10534 } 10535 10536 final T searchAction = searchIterator.next(); 10537 10538 // loop through the set of intent filters 10539 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 10540 while (intentIter.hasNext()) { 10541 final ActivityIntentInfo intentInfo = intentIter.next(); 10542 boolean selectionFound = false; 10543 10544 // loop through the intent filter's selection criteria; at least one 10545 // of them must match the searched criteria 10546 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 10547 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 10548 final T intentSelection = intentSelectionIter.next(); 10549 if (intentSelection != null && intentSelection.equals(searchAction)) { 10550 selectionFound = true; 10551 break; 10552 } 10553 } 10554 10555 // the selection criteria wasn't found in this filter's set; this filter 10556 // is not a potential match 10557 if (!selectionFound) { 10558 intentIter.remove(); 10559 } 10560 } 10561 } 10562 } 10563 10564 private boolean isProtectedAction(ActivityIntentInfo filter) { 10565 final Iterator<String> actionsIter = filter.actionsIterator(); 10566 while (actionsIter != null && actionsIter.hasNext()) { 10567 final String filterAction = actionsIter.next(); 10568 if (PROTECTED_ACTIONS.contains(filterAction)) { 10569 return true; 10570 } 10571 } 10572 return false; 10573 } 10574 10575 /** 10576 * Adjusts the priority of the given intent filter according to policy. 10577 * <p> 10578 * <ul> 10579 * <li>The priority for non privileged applications is capped to '0'</li> 10580 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 10581 * <li>The priority for unbundled updates to privileged applications is capped to the 10582 * priority defined on the system partition</li> 10583 * </ul> 10584 * <p> 10585 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 10586 * allowed to obtain any priority on any action. 10587 */ 10588 private void adjustPriority( 10589 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 10590 // nothing to do; priority is fine as-is 10591 if (intent.getPriority() <= 0) { 10592 return; 10593 } 10594 10595 final ActivityInfo activityInfo = intent.activity.info; 10596 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 10597 10598 final boolean privilegedApp = 10599 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 10600 if (!privilegedApp) { 10601 // non-privileged applications can never define a priority >0 10602 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 10603 + " package: " + applicationInfo.packageName 10604 + " activity: " + intent.activity.className 10605 + " origPrio: " + intent.getPriority()); 10606 intent.setPriority(0); 10607 return; 10608 } 10609 10610 if (systemActivities == null) { 10611 // the system package is not disabled; we're parsing the system partition 10612 if (isProtectedAction(intent)) { 10613 if (mDeferProtectedFilters) { 10614 // We can't deal with these just yet. No component should ever obtain a 10615 // >0 priority for a protected actions, with ONE exception -- the setup 10616 // wizard. The setup wizard, however, cannot be known until we're able to 10617 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 10618 // until all intent filters have been processed. Chicken, meet egg. 10619 // Let the filter temporarily have a high priority and rectify the 10620 // priorities after all system packages have been scanned. 10621 mProtectedFilters.add(intent); 10622 if (DEBUG_FILTERS) { 10623 Slog.i(TAG, "Protected action; save for later;" 10624 + " package: " + applicationInfo.packageName 10625 + " activity: " + intent.activity.className 10626 + " origPrio: " + intent.getPriority()); 10627 } 10628 return; 10629 } else { 10630 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 10631 Slog.i(TAG, "No setup wizard;" 10632 + " All protected intents capped to priority 0"); 10633 } 10634 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 10635 if (DEBUG_FILTERS) { 10636 Slog.i(TAG, "Found setup wizard;" 10637 + " allow priority " + intent.getPriority() + ";" 10638 + " package: " + intent.activity.info.packageName 10639 + " activity: " + intent.activity.className 10640 + " priority: " + intent.getPriority()); 10641 } 10642 // setup wizard gets whatever it wants 10643 return; 10644 } 10645 Slog.w(TAG, "Protected action; cap priority to 0;" 10646 + " package: " + intent.activity.info.packageName 10647 + " activity: " + intent.activity.className 10648 + " origPrio: " + intent.getPriority()); 10649 intent.setPriority(0); 10650 return; 10651 } 10652 } 10653 // privileged apps on the system image get whatever priority they request 10654 return; 10655 } 10656 10657 // privileged app unbundled update ... try to find the same activity 10658 final PackageParser.Activity foundActivity = 10659 findMatchingActivity(systemActivities, activityInfo); 10660 if (foundActivity == null) { 10661 // this is a new activity; it cannot obtain >0 priority 10662 if (DEBUG_FILTERS) { 10663 Slog.i(TAG, "New activity; cap priority to 0;" 10664 + " package: " + applicationInfo.packageName 10665 + " activity: " + intent.activity.className 10666 + " origPrio: " + intent.getPriority()); 10667 } 10668 intent.setPriority(0); 10669 return; 10670 } 10671 10672 // found activity, now check for filter equivalence 10673 10674 // a shallow copy is enough; we modify the list, not its contents 10675 final List<ActivityIntentInfo> intentListCopy = 10676 new ArrayList<>(foundActivity.intents); 10677 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 10678 10679 // find matching action subsets 10680 final Iterator<String> actionsIterator = intent.actionsIterator(); 10681 if (actionsIterator != null) { 10682 getIntentListSubset( 10683 intentListCopy, new ActionIterGenerator(), actionsIterator); 10684 if (intentListCopy.size() == 0) { 10685 // no more intents to match; we're not equivalent 10686 if (DEBUG_FILTERS) { 10687 Slog.i(TAG, "Mismatched action; cap priority to 0;" 10688 + " package: " + applicationInfo.packageName 10689 + " activity: " + intent.activity.className 10690 + " origPrio: " + intent.getPriority()); 10691 } 10692 intent.setPriority(0); 10693 return; 10694 } 10695 } 10696 10697 // find matching category subsets 10698 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 10699 if (categoriesIterator != null) { 10700 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 10701 categoriesIterator); 10702 if (intentListCopy.size() == 0) { 10703 // no more intents to match; we're not equivalent 10704 if (DEBUG_FILTERS) { 10705 Slog.i(TAG, "Mismatched category; cap priority to 0;" 10706 + " package: " + applicationInfo.packageName 10707 + " activity: " + intent.activity.className 10708 + " origPrio: " + intent.getPriority()); 10709 } 10710 intent.setPriority(0); 10711 return; 10712 } 10713 } 10714 10715 // find matching schemes subsets 10716 final Iterator<String> schemesIterator = intent.schemesIterator(); 10717 if (schemesIterator != null) { 10718 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 10719 schemesIterator); 10720 if (intentListCopy.size() == 0) { 10721 // no more intents to match; we're not equivalent 10722 if (DEBUG_FILTERS) { 10723 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 10724 + " package: " + applicationInfo.packageName 10725 + " activity: " + intent.activity.className 10726 + " origPrio: " + intent.getPriority()); 10727 } 10728 intent.setPriority(0); 10729 return; 10730 } 10731 } 10732 10733 // find matching authorities subsets 10734 final Iterator<IntentFilter.AuthorityEntry> 10735 authoritiesIterator = intent.authoritiesIterator(); 10736 if (authoritiesIterator != null) { 10737 getIntentListSubset(intentListCopy, 10738 new AuthoritiesIterGenerator(), 10739 authoritiesIterator); 10740 if (intentListCopy.size() == 0) { 10741 // no more intents to match; we're not equivalent 10742 if (DEBUG_FILTERS) { 10743 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 10744 + " package: " + applicationInfo.packageName 10745 + " activity: " + intent.activity.className 10746 + " origPrio: " + intent.getPriority()); 10747 } 10748 intent.setPriority(0); 10749 return; 10750 } 10751 } 10752 10753 // we found matching filter(s); app gets the max priority of all intents 10754 int cappedPriority = 0; 10755 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 10756 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 10757 } 10758 if (intent.getPriority() > cappedPriority) { 10759 if (DEBUG_FILTERS) { 10760 Slog.i(TAG, "Found matching filter(s);" 10761 + " cap priority to " + cappedPriority + ";" 10762 + " package: " + applicationInfo.packageName 10763 + " activity: " + intent.activity.className 10764 + " origPrio: " + intent.getPriority()); 10765 } 10766 intent.setPriority(cappedPriority); 10767 return; 10768 } 10769 // all this for nothing; the requested priority was <= what was on the system 10770 } 10771 10772 public final void addActivity(PackageParser.Activity a, String type) { 10773 mActivities.put(a.getComponentName(), a); 10774 if (DEBUG_SHOW_INFO) 10775 Log.v( 10776 TAG, " " + type + " " + 10777 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 10778 if (DEBUG_SHOW_INFO) 10779 Log.v(TAG, " Class=" + a.info.name); 10780 final int NI = a.intents.size(); 10781 for (int j=0; j<NI; j++) { 10782 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10783 if ("activity".equals(type)) { 10784 final PackageSetting ps = 10785 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 10786 final List<PackageParser.Activity> systemActivities = 10787 ps != null && ps.pkg != null ? ps.pkg.activities : null; 10788 adjustPriority(systemActivities, intent); 10789 } 10790 if (DEBUG_SHOW_INFO) { 10791 Log.v(TAG, " IntentFilter:"); 10792 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10793 } 10794 if (!intent.debugCheck()) { 10795 Log.w(TAG, "==> For Activity " + a.info.name); 10796 } 10797 addFilter(intent); 10798 } 10799 } 10800 10801 public final void removeActivity(PackageParser.Activity a, String type) { 10802 mActivities.remove(a.getComponentName()); 10803 if (DEBUG_SHOW_INFO) { 10804 Log.v(TAG, " " + type + " " 10805 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 10806 : a.info.name) + ":"); 10807 Log.v(TAG, " Class=" + a.info.name); 10808 } 10809 final int NI = a.intents.size(); 10810 for (int j=0; j<NI; j++) { 10811 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10812 if (DEBUG_SHOW_INFO) { 10813 Log.v(TAG, " IntentFilter:"); 10814 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10815 } 10816 removeFilter(intent); 10817 } 10818 } 10819 10820 @Override 10821 protected boolean allowFilterResult( 10822 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 10823 ActivityInfo filterAi = filter.activity.info; 10824 for (int i=dest.size()-1; i>=0; i--) { 10825 ActivityInfo destAi = dest.get(i).activityInfo; 10826 if (destAi.name == filterAi.name 10827 && destAi.packageName == filterAi.packageName) { 10828 return false; 10829 } 10830 } 10831 return true; 10832 } 10833 10834 @Override 10835 protected ActivityIntentInfo[] newArray(int size) { 10836 return new ActivityIntentInfo[size]; 10837 } 10838 10839 @Override 10840 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 10841 if (!sUserManager.exists(userId)) return true; 10842 PackageParser.Package p = filter.activity.owner; 10843 if (p != null) { 10844 PackageSetting ps = (PackageSetting)p.mExtras; 10845 if (ps != null) { 10846 // System apps are never considered stopped for purposes of 10847 // filtering, because there may be no way for the user to 10848 // actually re-launch them. 10849 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 10850 && ps.getStopped(userId); 10851 } 10852 } 10853 return false; 10854 } 10855 10856 @Override 10857 protected boolean isPackageForFilter(String packageName, 10858 PackageParser.ActivityIntentInfo info) { 10859 return packageName.equals(info.activity.owner.packageName); 10860 } 10861 10862 @Override 10863 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 10864 int match, int userId) { 10865 if (!sUserManager.exists(userId)) return null; 10866 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 10867 return null; 10868 } 10869 final PackageParser.Activity activity = info.activity; 10870 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 10871 if (ps == null) { 10872 return null; 10873 } 10874 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 10875 ps.readUserState(userId), userId); 10876 if (ai == null) { 10877 return null; 10878 } 10879 final ResolveInfo res = new ResolveInfo(); 10880 res.activityInfo = ai; 10881 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10882 res.filter = info; 10883 } 10884 if (info != null) { 10885 res.handleAllWebDataURI = info.handleAllWebDataURI(); 10886 } 10887 res.priority = info.getPriority(); 10888 res.preferredOrder = activity.owner.mPreferredOrder; 10889 //System.out.println("Result: " + res.activityInfo.className + 10890 // " = " + res.priority); 10891 res.match = match; 10892 res.isDefault = info.hasDefault; 10893 res.labelRes = info.labelRes; 10894 res.nonLocalizedLabel = info.nonLocalizedLabel; 10895 if (userNeedsBadging(userId)) { 10896 res.noResourceId = true; 10897 } else { 10898 res.icon = info.icon; 10899 } 10900 res.iconResourceId = info.icon; 10901 res.system = res.activityInfo.applicationInfo.isSystemApp(); 10902 return res; 10903 } 10904 10905 @Override 10906 protected void sortResults(List<ResolveInfo> results) { 10907 Collections.sort(results, mResolvePrioritySorter); 10908 } 10909 10910 @Override 10911 protected void dumpFilter(PrintWriter out, String prefix, 10912 PackageParser.ActivityIntentInfo filter) { 10913 out.print(prefix); out.print( 10914 Integer.toHexString(System.identityHashCode(filter.activity))); 10915 out.print(' '); 10916 filter.activity.printComponentShortName(out); 10917 out.print(" filter "); 10918 out.println(Integer.toHexString(System.identityHashCode(filter))); 10919 } 10920 10921 @Override 10922 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 10923 return filter.activity; 10924 } 10925 10926 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10927 PackageParser.Activity activity = (PackageParser.Activity)label; 10928 out.print(prefix); out.print( 10929 Integer.toHexString(System.identityHashCode(activity))); 10930 out.print(' '); 10931 activity.printComponentShortName(out); 10932 if (count > 1) { 10933 out.print(" ("); out.print(count); out.print(" filters)"); 10934 } 10935 out.println(); 10936 } 10937 10938 // Keys are String (activity class name), values are Activity. 10939 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 10940 = new ArrayMap<ComponentName, PackageParser.Activity>(); 10941 private int mFlags; 10942 } 10943 10944 private final class ServiceIntentResolver 10945 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 10946 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10947 boolean defaultOnly, int userId) { 10948 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10949 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10950 } 10951 10952 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10953 int userId) { 10954 if (!sUserManager.exists(userId)) return null; 10955 mFlags = flags; 10956 return super.queryIntent(intent, resolvedType, 10957 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10958 } 10959 10960 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10961 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 10962 if (!sUserManager.exists(userId)) return null; 10963 if (packageServices == null) { 10964 return null; 10965 } 10966 mFlags = flags; 10967 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10968 final int N = packageServices.size(); 10969 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 10970 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 10971 10972 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 10973 for (int i = 0; i < N; ++i) { 10974 intentFilters = packageServices.get(i).intents; 10975 if (intentFilters != null && intentFilters.size() > 0) { 10976 PackageParser.ServiceIntentInfo[] array = 10977 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 10978 intentFilters.toArray(array); 10979 listCut.add(array); 10980 } 10981 } 10982 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10983 } 10984 10985 public final void addService(PackageParser.Service s) { 10986 mServices.put(s.getComponentName(), s); 10987 if (DEBUG_SHOW_INFO) { 10988 Log.v(TAG, " " 10989 + (s.info.nonLocalizedLabel != null 10990 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10991 Log.v(TAG, " Class=" + s.info.name); 10992 } 10993 final int NI = s.intents.size(); 10994 int j; 10995 for (j=0; j<NI; j++) { 10996 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10997 if (DEBUG_SHOW_INFO) { 10998 Log.v(TAG, " IntentFilter:"); 10999 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11000 } 11001 if (!intent.debugCheck()) { 11002 Log.w(TAG, "==> For Service " + s.info.name); 11003 } 11004 addFilter(intent); 11005 } 11006 } 11007 11008 public final void removeService(PackageParser.Service s) { 11009 mServices.remove(s.getComponentName()); 11010 if (DEBUG_SHOW_INFO) { 11011 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 11012 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 11013 Log.v(TAG, " Class=" + s.info.name); 11014 } 11015 final int NI = s.intents.size(); 11016 int j; 11017 for (j=0; j<NI; j++) { 11018 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 11019 if (DEBUG_SHOW_INFO) { 11020 Log.v(TAG, " IntentFilter:"); 11021 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11022 } 11023 removeFilter(intent); 11024 } 11025 } 11026 11027 @Override 11028 protected boolean allowFilterResult( 11029 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 11030 ServiceInfo filterSi = filter.service.info; 11031 for (int i=dest.size()-1; i>=0; i--) { 11032 ServiceInfo destAi = dest.get(i).serviceInfo; 11033 if (destAi.name == filterSi.name 11034 && destAi.packageName == filterSi.packageName) { 11035 return false; 11036 } 11037 } 11038 return true; 11039 } 11040 11041 @Override 11042 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 11043 return new PackageParser.ServiceIntentInfo[size]; 11044 } 11045 11046 @Override 11047 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 11048 if (!sUserManager.exists(userId)) return true; 11049 PackageParser.Package p = filter.service.owner; 11050 if (p != null) { 11051 PackageSetting ps = (PackageSetting)p.mExtras; 11052 if (ps != null) { 11053 // System apps are never considered stopped for purposes of 11054 // filtering, because there may be no way for the user to 11055 // actually re-launch them. 11056 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 11057 && ps.getStopped(userId); 11058 } 11059 } 11060 return false; 11061 } 11062 11063 @Override 11064 protected boolean isPackageForFilter(String packageName, 11065 PackageParser.ServiceIntentInfo info) { 11066 return packageName.equals(info.service.owner.packageName); 11067 } 11068 11069 @Override 11070 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 11071 int match, int userId) { 11072 if (!sUserManager.exists(userId)) return null; 11073 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 11074 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 11075 return null; 11076 } 11077 final PackageParser.Service service = info.service; 11078 PackageSetting ps = (PackageSetting) service.owner.mExtras; 11079 if (ps == null) { 11080 return null; 11081 } 11082 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 11083 ps.readUserState(userId), userId); 11084 if (si == null) { 11085 return null; 11086 } 11087 final ResolveInfo res = new ResolveInfo(); 11088 res.serviceInfo = si; 11089 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 11090 res.filter = filter; 11091 } 11092 res.priority = info.getPriority(); 11093 res.preferredOrder = service.owner.mPreferredOrder; 11094 res.match = match; 11095 res.isDefault = info.hasDefault; 11096 res.labelRes = info.labelRes; 11097 res.nonLocalizedLabel = info.nonLocalizedLabel; 11098 res.icon = info.icon; 11099 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 11100 return res; 11101 } 11102 11103 @Override 11104 protected void sortResults(List<ResolveInfo> results) { 11105 Collections.sort(results, mResolvePrioritySorter); 11106 } 11107 11108 @Override 11109 protected void dumpFilter(PrintWriter out, String prefix, 11110 PackageParser.ServiceIntentInfo filter) { 11111 out.print(prefix); out.print( 11112 Integer.toHexString(System.identityHashCode(filter.service))); 11113 out.print(' '); 11114 filter.service.printComponentShortName(out); 11115 out.print(" filter "); 11116 out.println(Integer.toHexString(System.identityHashCode(filter))); 11117 } 11118 11119 @Override 11120 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 11121 return filter.service; 11122 } 11123 11124 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11125 PackageParser.Service service = (PackageParser.Service)label; 11126 out.print(prefix); out.print( 11127 Integer.toHexString(System.identityHashCode(service))); 11128 out.print(' '); 11129 service.printComponentShortName(out); 11130 if (count > 1) { 11131 out.print(" ("); out.print(count); out.print(" filters)"); 11132 } 11133 out.println(); 11134 } 11135 11136// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 11137// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 11138// final List<ResolveInfo> retList = Lists.newArrayList(); 11139// while (i.hasNext()) { 11140// final ResolveInfo resolveInfo = (ResolveInfo) i; 11141// if (isEnabledLP(resolveInfo.serviceInfo)) { 11142// retList.add(resolveInfo); 11143// } 11144// } 11145// return retList; 11146// } 11147 11148 // Keys are String (activity class name), values are Activity. 11149 private final ArrayMap<ComponentName, PackageParser.Service> mServices 11150 = new ArrayMap<ComponentName, PackageParser.Service>(); 11151 private int mFlags; 11152 }; 11153 11154 private final class ProviderIntentResolver 11155 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 11156 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 11157 boolean defaultOnly, int userId) { 11158 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 11159 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 11160 } 11161 11162 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 11163 int userId) { 11164 if (!sUserManager.exists(userId)) 11165 return null; 11166 mFlags = flags; 11167 return super.queryIntent(intent, resolvedType, 11168 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 11169 } 11170 11171 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 11172 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 11173 if (!sUserManager.exists(userId)) 11174 return null; 11175 if (packageProviders == null) { 11176 return null; 11177 } 11178 mFlags = flags; 11179 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 11180 final int N = packageProviders.size(); 11181 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 11182 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 11183 11184 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 11185 for (int i = 0; i < N; ++i) { 11186 intentFilters = packageProviders.get(i).intents; 11187 if (intentFilters != null && intentFilters.size() > 0) { 11188 PackageParser.ProviderIntentInfo[] array = 11189 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 11190 intentFilters.toArray(array); 11191 listCut.add(array); 11192 } 11193 } 11194 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 11195 } 11196 11197 public final void addProvider(PackageParser.Provider p) { 11198 if (mProviders.containsKey(p.getComponentName())) { 11199 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 11200 return; 11201 } 11202 11203 mProviders.put(p.getComponentName(), p); 11204 if (DEBUG_SHOW_INFO) { 11205 Log.v(TAG, " " 11206 + (p.info.nonLocalizedLabel != null 11207 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11208 Log.v(TAG, " Class=" + p.info.name); 11209 } 11210 final int NI = p.intents.size(); 11211 int j; 11212 for (j = 0; j < NI; j++) { 11213 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11214 if (DEBUG_SHOW_INFO) { 11215 Log.v(TAG, " IntentFilter:"); 11216 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11217 } 11218 if (!intent.debugCheck()) { 11219 Log.w(TAG, "==> For Provider " + p.info.name); 11220 } 11221 addFilter(intent); 11222 } 11223 } 11224 11225 public final void removeProvider(PackageParser.Provider p) { 11226 mProviders.remove(p.getComponentName()); 11227 if (DEBUG_SHOW_INFO) { 11228 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 11229 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11230 Log.v(TAG, " Class=" + p.info.name); 11231 } 11232 final int NI = p.intents.size(); 11233 int j; 11234 for (j = 0; j < NI; j++) { 11235 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11236 if (DEBUG_SHOW_INFO) { 11237 Log.v(TAG, " IntentFilter:"); 11238 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11239 } 11240 removeFilter(intent); 11241 } 11242 } 11243 11244 @Override 11245 protected boolean allowFilterResult( 11246 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 11247 ProviderInfo filterPi = filter.provider.info; 11248 for (int i = dest.size() - 1; i >= 0; i--) { 11249 ProviderInfo destPi = dest.get(i).providerInfo; 11250 if (destPi.name == filterPi.name 11251 && destPi.packageName == filterPi.packageName) { 11252 return false; 11253 } 11254 } 11255 return true; 11256 } 11257 11258 @Override 11259 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 11260 return new PackageParser.ProviderIntentInfo[size]; 11261 } 11262 11263 @Override 11264 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 11265 if (!sUserManager.exists(userId)) 11266 return true; 11267 PackageParser.Package p = filter.provider.owner; 11268 if (p != null) { 11269 PackageSetting ps = (PackageSetting) p.mExtras; 11270 if (ps != null) { 11271 // System apps are never considered stopped for purposes of 11272 // filtering, because there may be no way for the user to 11273 // actually re-launch them. 11274 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 11275 && ps.getStopped(userId); 11276 } 11277 } 11278 return false; 11279 } 11280 11281 @Override 11282 protected boolean isPackageForFilter(String packageName, 11283 PackageParser.ProviderIntentInfo info) { 11284 return packageName.equals(info.provider.owner.packageName); 11285 } 11286 11287 @Override 11288 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 11289 int match, int userId) { 11290 if (!sUserManager.exists(userId)) 11291 return null; 11292 final PackageParser.ProviderIntentInfo info = filter; 11293 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 11294 return null; 11295 } 11296 final PackageParser.Provider provider = info.provider; 11297 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 11298 if (ps == null) { 11299 return null; 11300 } 11301 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 11302 ps.readUserState(userId), userId); 11303 if (pi == null) { 11304 return null; 11305 } 11306 final ResolveInfo res = new ResolveInfo(); 11307 res.providerInfo = pi; 11308 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 11309 res.filter = filter; 11310 } 11311 res.priority = info.getPriority(); 11312 res.preferredOrder = provider.owner.mPreferredOrder; 11313 res.match = match; 11314 res.isDefault = info.hasDefault; 11315 res.labelRes = info.labelRes; 11316 res.nonLocalizedLabel = info.nonLocalizedLabel; 11317 res.icon = info.icon; 11318 res.system = res.providerInfo.applicationInfo.isSystemApp(); 11319 return res; 11320 } 11321 11322 @Override 11323 protected void sortResults(List<ResolveInfo> results) { 11324 Collections.sort(results, mResolvePrioritySorter); 11325 } 11326 11327 @Override 11328 protected void dumpFilter(PrintWriter out, String prefix, 11329 PackageParser.ProviderIntentInfo filter) { 11330 out.print(prefix); 11331 out.print( 11332 Integer.toHexString(System.identityHashCode(filter.provider))); 11333 out.print(' '); 11334 filter.provider.printComponentShortName(out); 11335 out.print(" filter "); 11336 out.println(Integer.toHexString(System.identityHashCode(filter))); 11337 } 11338 11339 @Override 11340 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 11341 return filter.provider; 11342 } 11343 11344 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11345 PackageParser.Provider provider = (PackageParser.Provider)label; 11346 out.print(prefix); out.print( 11347 Integer.toHexString(System.identityHashCode(provider))); 11348 out.print(' '); 11349 provider.printComponentShortName(out); 11350 if (count > 1) { 11351 out.print(" ("); out.print(count); out.print(" filters)"); 11352 } 11353 out.println(); 11354 } 11355 11356 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 11357 = new ArrayMap<ComponentName, PackageParser.Provider>(); 11358 private int mFlags; 11359 } 11360 11361 private static final class EphemeralIntentResolver 11362 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 11363 @Override 11364 protected EphemeralResolveIntentInfo[] newArray(int size) { 11365 return new EphemeralResolveIntentInfo[size]; 11366 } 11367 11368 @Override 11369 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 11370 return true; 11371 } 11372 11373 @Override 11374 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 11375 int userId) { 11376 if (!sUserManager.exists(userId)) { 11377 return null; 11378 } 11379 return info.getEphemeralResolveInfo(); 11380 } 11381 } 11382 11383 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 11384 new Comparator<ResolveInfo>() { 11385 public int compare(ResolveInfo r1, ResolveInfo r2) { 11386 int v1 = r1.priority; 11387 int v2 = r2.priority; 11388 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 11389 if (v1 != v2) { 11390 return (v1 > v2) ? -1 : 1; 11391 } 11392 v1 = r1.preferredOrder; 11393 v2 = r2.preferredOrder; 11394 if (v1 != v2) { 11395 return (v1 > v2) ? -1 : 1; 11396 } 11397 if (r1.isDefault != r2.isDefault) { 11398 return r1.isDefault ? -1 : 1; 11399 } 11400 v1 = r1.match; 11401 v2 = r2.match; 11402 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 11403 if (v1 != v2) { 11404 return (v1 > v2) ? -1 : 1; 11405 } 11406 if (r1.system != r2.system) { 11407 return r1.system ? -1 : 1; 11408 } 11409 if (r1.activityInfo != null) { 11410 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 11411 } 11412 if (r1.serviceInfo != null) { 11413 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 11414 } 11415 if (r1.providerInfo != null) { 11416 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 11417 } 11418 return 0; 11419 } 11420 }; 11421 11422 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 11423 new Comparator<ProviderInfo>() { 11424 public int compare(ProviderInfo p1, ProviderInfo p2) { 11425 final int v1 = p1.initOrder; 11426 final int v2 = p2.initOrder; 11427 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 11428 } 11429 }; 11430 11431 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 11432 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 11433 final int[] userIds) { 11434 mHandler.post(new Runnable() { 11435 @Override 11436 public void run() { 11437 try { 11438 final IActivityManager am = ActivityManagerNative.getDefault(); 11439 if (am == null) return; 11440 final int[] resolvedUserIds; 11441 if (userIds == null) { 11442 resolvedUserIds = am.getRunningUserIds(); 11443 } else { 11444 resolvedUserIds = userIds; 11445 } 11446 for (int id : resolvedUserIds) { 11447 final Intent intent = new Intent(action, 11448 pkg != null ? Uri.fromParts("package", pkg, null) : null); 11449 if (extras != null) { 11450 intent.putExtras(extras); 11451 } 11452 if (targetPkg != null) { 11453 intent.setPackage(targetPkg); 11454 } 11455 // Modify the UID when posting to other users 11456 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 11457 if (uid > 0 && UserHandle.getUserId(uid) != id) { 11458 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 11459 intent.putExtra(Intent.EXTRA_UID, uid); 11460 } 11461 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 11462 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 11463 if (DEBUG_BROADCASTS) { 11464 RuntimeException here = new RuntimeException("here"); 11465 here.fillInStackTrace(); 11466 Slog.d(TAG, "Sending to user " + id + ": " 11467 + intent.toShortString(false, true, false, false) 11468 + " " + intent.getExtras(), here); 11469 } 11470 am.broadcastIntent(null, intent, null, finishedReceiver, 11471 0, null, null, null, android.app.AppOpsManager.OP_NONE, 11472 null, finishedReceiver != null, false, id); 11473 } 11474 } catch (RemoteException ex) { 11475 } 11476 } 11477 }); 11478 } 11479 11480 /** 11481 * Check if the external storage media is available. This is true if there 11482 * is a mounted external storage medium or if the external storage is 11483 * emulated. 11484 */ 11485 private boolean isExternalMediaAvailable() { 11486 return mMediaMounted || Environment.isExternalStorageEmulated(); 11487 } 11488 11489 @Override 11490 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 11491 // writer 11492 synchronized (mPackages) { 11493 if (!isExternalMediaAvailable()) { 11494 // If the external storage is no longer mounted at this point, 11495 // the caller may not have been able to delete all of this 11496 // packages files and can not delete any more. Bail. 11497 return null; 11498 } 11499 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 11500 if (lastPackage != null) { 11501 pkgs.remove(lastPackage); 11502 } 11503 if (pkgs.size() > 0) { 11504 return pkgs.get(0); 11505 } 11506 } 11507 return null; 11508 } 11509 11510 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 11511 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 11512 userId, andCode ? 1 : 0, packageName); 11513 if (mSystemReady) { 11514 msg.sendToTarget(); 11515 } else { 11516 if (mPostSystemReadyMessages == null) { 11517 mPostSystemReadyMessages = new ArrayList<>(); 11518 } 11519 mPostSystemReadyMessages.add(msg); 11520 } 11521 } 11522 11523 void startCleaningPackages() { 11524 // reader 11525 if (!isExternalMediaAvailable()) { 11526 return; 11527 } 11528 synchronized (mPackages) { 11529 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 11530 return; 11531 } 11532 } 11533 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 11534 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 11535 IActivityManager am = ActivityManagerNative.getDefault(); 11536 if (am != null) { 11537 try { 11538 am.startService(null, intent, null, mContext.getOpPackageName(), 11539 UserHandle.USER_SYSTEM); 11540 } catch (RemoteException e) { 11541 } 11542 } 11543 } 11544 11545 @Override 11546 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 11547 int installFlags, String installerPackageName, int userId) { 11548 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 11549 11550 final int callingUid = Binder.getCallingUid(); 11551 enforceCrossUserPermission(callingUid, userId, 11552 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 11553 11554 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11555 try { 11556 if (observer != null) { 11557 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 11558 } 11559 } catch (RemoteException re) { 11560 } 11561 return; 11562 } 11563 11564 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 11565 installFlags |= PackageManager.INSTALL_FROM_ADB; 11566 11567 } else { 11568 // Caller holds INSTALL_PACKAGES permission, so we're less strict 11569 // about installerPackageName. 11570 11571 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 11572 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 11573 } 11574 11575 UserHandle user; 11576 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 11577 user = UserHandle.ALL; 11578 } else { 11579 user = new UserHandle(userId); 11580 } 11581 11582 // Only system components can circumvent runtime permissions when installing. 11583 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 11584 && mContext.checkCallingOrSelfPermission(Manifest.permission 11585 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 11586 throw new SecurityException("You need the " 11587 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 11588 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 11589 } 11590 11591 final File originFile = new File(originPath); 11592 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 11593 11594 final Message msg = mHandler.obtainMessage(INIT_COPY); 11595 final VerificationInfo verificationInfo = new VerificationInfo( 11596 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 11597 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 11598 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 11599 null /*packageAbiOverride*/, null /*grantedPermissions*/, 11600 null /*certificates*/); 11601 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 11602 msg.obj = params; 11603 11604 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 11605 System.identityHashCode(msg.obj)); 11606 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11607 System.identityHashCode(msg.obj)); 11608 11609 mHandler.sendMessage(msg); 11610 } 11611 11612 void installStage(String packageName, File stagedDir, String stagedCid, 11613 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 11614 String installerPackageName, int installerUid, UserHandle user, 11615 Certificate[][] certificates) { 11616 if (DEBUG_EPHEMERAL) { 11617 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11618 Slog.d(TAG, "Ephemeral install of " + packageName); 11619 } 11620 } 11621 final VerificationInfo verificationInfo = new VerificationInfo( 11622 sessionParams.originatingUri, sessionParams.referrerUri, 11623 sessionParams.originatingUid, installerUid); 11624 11625 final OriginInfo origin; 11626 if (stagedDir != null) { 11627 origin = OriginInfo.fromStagedFile(stagedDir); 11628 } else { 11629 origin = OriginInfo.fromStagedContainer(stagedCid); 11630 } 11631 11632 final Message msg = mHandler.obtainMessage(INIT_COPY); 11633 final InstallParams params = new InstallParams(origin, null, observer, 11634 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 11635 verificationInfo, user, sessionParams.abiOverride, 11636 sessionParams.grantedRuntimePermissions, certificates); 11637 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 11638 msg.obj = params; 11639 11640 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 11641 System.identityHashCode(msg.obj)); 11642 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11643 System.identityHashCode(msg.obj)); 11644 11645 mHandler.sendMessage(msg); 11646 } 11647 11648 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 11649 int userId) { 11650 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 11651 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId); 11652 } 11653 11654 private void sendPackageAddedForUser(String packageName, boolean isSystem, 11655 int appId, int userId) { 11656 Bundle extras = new Bundle(1); 11657 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId)); 11658 11659 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 11660 packageName, extras, 0, null, null, new int[] {userId}); 11661 try { 11662 IActivityManager am = ActivityManagerNative.getDefault(); 11663 if (isSystem && am.isUserRunning(userId, 0)) { 11664 // The just-installed/enabled app is bundled on the system, so presumed 11665 // to be able to run automatically without needing an explicit launch. 11666 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 11667 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 11668 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 11669 .setPackage(packageName); 11670 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 11671 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 11672 } 11673 } catch (RemoteException e) { 11674 // shouldn't happen 11675 Slog.w(TAG, "Unable to bootstrap installed package", e); 11676 } 11677 } 11678 11679 @Override 11680 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 11681 int userId) { 11682 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11683 PackageSetting pkgSetting; 11684 final int uid = Binder.getCallingUid(); 11685 enforceCrossUserPermission(uid, userId, 11686 true /* requireFullPermission */, true /* checkShell */, 11687 "setApplicationHiddenSetting for user " + userId); 11688 11689 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 11690 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 11691 return false; 11692 } 11693 11694 long callingId = Binder.clearCallingIdentity(); 11695 try { 11696 boolean sendAdded = false; 11697 boolean sendRemoved = false; 11698 // writer 11699 synchronized (mPackages) { 11700 pkgSetting = mSettings.mPackages.get(packageName); 11701 if (pkgSetting == null) { 11702 return false; 11703 } 11704 // Only allow protected packages to hide themselves. 11705 if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId) 11706 && mProtectedPackages.isPackageStateProtected(userId, packageName)) { 11707 Slog.w(TAG, "Not hiding protected package: " + packageName); 11708 return false; 11709 } 11710 if (pkgSetting.getHidden(userId) != hidden) { 11711 pkgSetting.setHidden(hidden, userId); 11712 mSettings.writePackageRestrictionsLPr(userId); 11713 if (hidden) { 11714 sendRemoved = true; 11715 } else { 11716 sendAdded = true; 11717 } 11718 } 11719 } 11720 if (sendAdded) { 11721 sendPackageAddedForUser(packageName, pkgSetting, userId); 11722 return true; 11723 } 11724 if (sendRemoved) { 11725 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 11726 "hiding pkg"); 11727 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 11728 return true; 11729 } 11730 } finally { 11731 Binder.restoreCallingIdentity(callingId); 11732 } 11733 return false; 11734 } 11735 11736 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 11737 int userId) { 11738 final PackageRemovedInfo info = new PackageRemovedInfo(); 11739 info.removedPackage = packageName; 11740 info.removedUsers = new int[] {userId}; 11741 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 11742 info.sendPackageRemovedBroadcasts(true /*killApp*/); 11743 } 11744 11745 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 11746 if (pkgList.length > 0) { 11747 Bundle extras = new Bundle(1); 11748 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 11749 11750 sendPackageBroadcast( 11751 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 11752 : Intent.ACTION_PACKAGES_UNSUSPENDED, 11753 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 11754 new int[] {userId}); 11755 } 11756 } 11757 11758 /** 11759 * Returns true if application is not found or there was an error. Otherwise it returns 11760 * the hidden state of the package for the given user. 11761 */ 11762 @Override 11763 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 11764 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11765 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11766 true /* requireFullPermission */, false /* checkShell */, 11767 "getApplicationHidden for user " + userId); 11768 PackageSetting pkgSetting; 11769 long callingId = Binder.clearCallingIdentity(); 11770 try { 11771 // writer 11772 synchronized (mPackages) { 11773 pkgSetting = mSettings.mPackages.get(packageName); 11774 if (pkgSetting == null) { 11775 return true; 11776 } 11777 return pkgSetting.getHidden(userId); 11778 } 11779 } finally { 11780 Binder.restoreCallingIdentity(callingId); 11781 } 11782 } 11783 11784 /** 11785 * @hide 11786 */ 11787 @Override 11788 public int installExistingPackageAsUser(String packageName, int userId) { 11789 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 11790 null); 11791 PackageSetting pkgSetting; 11792 final int uid = Binder.getCallingUid(); 11793 enforceCrossUserPermission(uid, userId, 11794 true /* requireFullPermission */, true /* checkShell */, 11795 "installExistingPackage for user " + userId); 11796 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11797 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 11798 } 11799 11800 long callingId = Binder.clearCallingIdentity(); 11801 try { 11802 boolean installed = false; 11803 11804 // writer 11805 synchronized (mPackages) { 11806 pkgSetting = mSettings.mPackages.get(packageName); 11807 if (pkgSetting == null) { 11808 return PackageManager.INSTALL_FAILED_INVALID_URI; 11809 } 11810 if (!pkgSetting.getInstalled(userId)) { 11811 pkgSetting.setInstalled(true, userId); 11812 pkgSetting.setHidden(false, userId); 11813 mSettings.writePackageRestrictionsLPr(userId); 11814 installed = true; 11815 } 11816 } 11817 11818 if (installed) { 11819 if (pkgSetting.pkg != null) { 11820 synchronized (mInstallLock) { 11821 // We don't need to freeze for a brand new install 11822 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 11823 } 11824 } 11825 sendPackageAddedForUser(packageName, pkgSetting, userId); 11826 } 11827 } finally { 11828 Binder.restoreCallingIdentity(callingId); 11829 } 11830 11831 return PackageManager.INSTALL_SUCCEEDED; 11832 } 11833 11834 boolean isUserRestricted(int userId, String restrictionKey) { 11835 Bundle restrictions = sUserManager.getUserRestrictions(userId); 11836 if (restrictions.getBoolean(restrictionKey, false)) { 11837 Log.w(TAG, "User is restricted: " + restrictionKey); 11838 return true; 11839 } 11840 return false; 11841 } 11842 11843 @Override 11844 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 11845 int userId) { 11846 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11847 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11848 true /* requireFullPermission */, true /* checkShell */, 11849 "setPackagesSuspended for user " + userId); 11850 11851 if (ArrayUtils.isEmpty(packageNames)) { 11852 return packageNames; 11853 } 11854 11855 // List of package names for whom the suspended state has changed. 11856 List<String> changedPackages = new ArrayList<>(packageNames.length); 11857 // List of package names for whom the suspended state is not set as requested in this 11858 // method. 11859 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 11860 long callingId = Binder.clearCallingIdentity(); 11861 try { 11862 for (int i = 0; i < packageNames.length; i++) { 11863 String packageName = packageNames[i]; 11864 boolean changed = false; 11865 final int appId; 11866 synchronized (mPackages) { 11867 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11868 if (pkgSetting == null) { 11869 Slog.w(TAG, "Could not find package setting for package \"" + packageName 11870 + "\". Skipping suspending/un-suspending."); 11871 unactionedPackages.add(packageName); 11872 continue; 11873 } 11874 appId = pkgSetting.appId; 11875 if (pkgSetting.getSuspended(userId) != suspended) { 11876 if (!canSuspendPackageForUserLocked(packageName, userId)) { 11877 unactionedPackages.add(packageName); 11878 continue; 11879 } 11880 pkgSetting.setSuspended(suspended, userId); 11881 mSettings.writePackageRestrictionsLPr(userId); 11882 changed = true; 11883 changedPackages.add(packageName); 11884 } 11885 } 11886 11887 if (changed && suspended) { 11888 killApplication(packageName, UserHandle.getUid(userId, appId), 11889 "suspending package"); 11890 } 11891 } 11892 } finally { 11893 Binder.restoreCallingIdentity(callingId); 11894 } 11895 11896 if (!changedPackages.isEmpty()) { 11897 sendPackagesSuspendedForUser(changedPackages.toArray( 11898 new String[changedPackages.size()]), userId, suspended); 11899 } 11900 11901 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 11902 } 11903 11904 @Override 11905 public boolean isPackageSuspendedForUser(String packageName, int userId) { 11906 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11907 true /* requireFullPermission */, false /* checkShell */, 11908 "isPackageSuspendedForUser for user " + userId); 11909 synchronized (mPackages) { 11910 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11911 if (pkgSetting == null) { 11912 throw new IllegalArgumentException("Unknown target package: " + packageName); 11913 } 11914 return pkgSetting.getSuspended(userId); 11915 } 11916 } 11917 11918 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 11919 if (isPackageDeviceAdmin(packageName, userId)) { 11920 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11921 + "\": has an active device admin"); 11922 return false; 11923 } 11924 11925 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 11926 if (packageName.equals(activeLauncherPackageName)) { 11927 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11928 + "\": contains the active launcher"); 11929 return false; 11930 } 11931 11932 if (packageName.equals(mRequiredInstallerPackage)) { 11933 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11934 + "\": required for package installation"); 11935 return false; 11936 } 11937 11938 if (packageName.equals(mRequiredVerifierPackage)) { 11939 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11940 + "\": required for package verification"); 11941 return false; 11942 } 11943 11944 if (packageName.equals(getDefaultDialerPackageName(userId))) { 11945 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11946 + "\": is the default dialer"); 11947 return false; 11948 } 11949 11950 return true; 11951 } 11952 11953 private String getActiveLauncherPackageName(int userId) { 11954 Intent intent = new Intent(Intent.ACTION_MAIN); 11955 intent.addCategory(Intent.CATEGORY_HOME); 11956 ResolveInfo resolveInfo = resolveIntent( 11957 intent, 11958 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 11959 PackageManager.MATCH_DEFAULT_ONLY, 11960 userId); 11961 11962 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 11963 } 11964 11965 private String getDefaultDialerPackageName(int userId) { 11966 synchronized (mPackages) { 11967 return mSettings.getDefaultDialerPackageNameLPw(userId); 11968 } 11969 } 11970 11971 @Override 11972 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 11973 mContext.enforceCallingOrSelfPermission( 11974 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11975 "Only package verification agents can verify applications"); 11976 11977 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11978 final PackageVerificationResponse response = new PackageVerificationResponse( 11979 verificationCode, Binder.getCallingUid()); 11980 msg.arg1 = id; 11981 msg.obj = response; 11982 mHandler.sendMessage(msg); 11983 } 11984 11985 @Override 11986 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 11987 long millisecondsToDelay) { 11988 mContext.enforceCallingOrSelfPermission( 11989 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11990 "Only package verification agents can extend verification timeouts"); 11991 11992 final PackageVerificationState state = mPendingVerification.get(id); 11993 final PackageVerificationResponse response = new PackageVerificationResponse( 11994 verificationCodeAtTimeout, Binder.getCallingUid()); 11995 11996 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 11997 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 11998 } 11999 if (millisecondsToDelay < 0) { 12000 millisecondsToDelay = 0; 12001 } 12002 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 12003 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 12004 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 12005 } 12006 12007 if ((state != null) && !state.timeoutExtended()) { 12008 state.extendTimeout(); 12009 12010 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 12011 msg.arg1 = id; 12012 msg.obj = response; 12013 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 12014 } 12015 } 12016 12017 private void broadcastPackageVerified(int verificationId, Uri packageUri, 12018 int verificationCode, UserHandle user) { 12019 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 12020 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 12021 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 12022 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 12023 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 12024 12025 mContext.sendBroadcastAsUser(intent, user, 12026 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 12027 } 12028 12029 private ComponentName matchComponentForVerifier(String packageName, 12030 List<ResolveInfo> receivers) { 12031 ActivityInfo targetReceiver = null; 12032 12033 final int NR = receivers.size(); 12034 for (int i = 0; i < NR; i++) { 12035 final ResolveInfo info = receivers.get(i); 12036 if (info.activityInfo == null) { 12037 continue; 12038 } 12039 12040 if (packageName.equals(info.activityInfo.packageName)) { 12041 targetReceiver = info.activityInfo; 12042 break; 12043 } 12044 } 12045 12046 if (targetReceiver == null) { 12047 return null; 12048 } 12049 12050 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 12051 } 12052 12053 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 12054 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 12055 if (pkgInfo.verifiers.length == 0) { 12056 return null; 12057 } 12058 12059 final int N = pkgInfo.verifiers.length; 12060 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 12061 for (int i = 0; i < N; i++) { 12062 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 12063 12064 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 12065 receivers); 12066 if (comp == null) { 12067 continue; 12068 } 12069 12070 final int verifierUid = getUidForVerifier(verifierInfo); 12071 if (verifierUid == -1) { 12072 continue; 12073 } 12074 12075 if (DEBUG_VERIFY) { 12076 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 12077 + " with the correct signature"); 12078 } 12079 sufficientVerifiers.add(comp); 12080 verificationState.addSufficientVerifier(verifierUid); 12081 } 12082 12083 return sufficientVerifiers; 12084 } 12085 12086 private int getUidForVerifier(VerifierInfo verifierInfo) { 12087 synchronized (mPackages) { 12088 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 12089 if (pkg == null) { 12090 return -1; 12091 } else if (pkg.mSignatures.length != 1) { 12092 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 12093 + " has more than one signature; ignoring"); 12094 return -1; 12095 } 12096 12097 /* 12098 * If the public key of the package's signature does not match 12099 * our expected public key, then this is a different package and 12100 * we should skip. 12101 */ 12102 12103 final byte[] expectedPublicKey; 12104 try { 12105 final Signature verifierSig = pkg.mSignatures[0]; 12106 final PublicKey publicKey = verifierSig.getPublicKey(); 12107 expectedPublicKey = publicKey.getEncoded(); 12108 } catch (CertificateException e) { 12109 return -1; 12110 } 12111 12112 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 12113 12114 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 12115 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 12116 + " does not have the expected public key; ignoring"); 12117 return -1; 12118 } 12119 12120 return pkg.applicationInfo.uid; 12121 } 12122 } 12123 12124 @Override 12125 public void finishPackageInstall(int token, boolean didLaunch) { 12126 enforceSystemOrRoot("Only the system is allowed to finish installs"); 12127 12128 if (DEBUG_INSTALL) { 12129 Slog.v(TAG, "BM finishing package install for " + token); 12130 } 12131 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12132 12133 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 12134 mHandler.sendMessage(msg); 12135 } 12136 12137 /** 12138 * Get the verification agent timeout. 12139 * 12140 * @return verification timeout in milliseconds 12141 */ 12142 private long getVerificationTimeout() { 12143 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 12144 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 12145 DEFAULT_VERIFICATION_TIMEOUT); 12146 } 12147 12148 /** 12149 * Get the default verification agent response code. 12150 * 12151 * @return default verification response code 12152 */ 12153 private int getDefaultVerificationResponse() { 12154 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12155 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 12156 DEFAULT_VERIFICATION_RESPONSE); 12157 } 12158 12159 /** 12160 * Check whether or not package verification has been enabled. 12161 * 12162 * @return true if verification should be performed 12163 */ 12164 private boolean isVerificationEnabled(int userId, int installFlags) { 12165 if (!DEFAULT_VERIFY_ENABLE) { 12166 return false; 12167 } 12168 // Ephemeral apps don't get the full verification treatment 12169 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 12170 if (DEBUG_EPHEMERAL) { 12171 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 12172 } 12173 return false; 12174 } 12175 12176 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 12177 12178 // Check if installing from ADB 12179 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 12180 // Do not run verification in a test harness environment 12181 if (ActivityManager.isRunningInTestHarness()) { 12182 return false; 12183 } 12184 if (ensureVerifyAppsEnabled) { 12185 return true; 12186 } 12187 // Check if the developer does not want package verification for ADB installs 12188 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12189 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 12190 return false; 12191 } 12192 } 12193 12194 if (ensureVerifyAppsEnabled) { 12195 return true; 12196 } 12197 12198 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12199 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 12200 } 12201 12202 @Override 12203 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 12204 throws RemoteException { 12205 mContext.enforceCallingOrSelfPermission( 12206 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 12207 "Only intentfilter verification agents can verify applications"); 12208 12209 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 12210 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 12211 Binder.getCallingUid(), verificationCode, failedDomains); 12212 msg.arg1 = id; 12213 msg.obj = response; 12214 mHandler.sendMessage(msg); 12215 } 12216 12217 @Override 12218 public int getIntentVerificationStatus(String packageName, int userId) { 12219 synchronized (mPackages) { 12220 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 12221 } 12222 } 12223 12224 @Override 12225 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 12226 mContext.enforceCallingOrSelfPermission( 12227 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12228 12229 boolean result = false; 12230 synchronized (mPackages) { 12231 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 12232 } 12233 if (result) { 12234 scheduleWritePackageRestrictionsLocked(userId); 12235 } 12236 return result; 12237 } 12238 12239 @Override 12240 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 12241 String packageName) { 12242 synchronized (mPackages) { 12243 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 12244 } 12245 } 12246 12247 @Override 12248 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 12249 if (TextUtils.isEmpty(packageName)) { 12250 return ParceledListSlice.emptyList(); 12251 } 12252 synchronized (mPackages) { 12253 PackageParser.Package pkg = mPackages.get(packageName); 12254 if (pkg == null || pkg.activities == null) { 12255 return ParceledListSlice.emptyList(); 12256 } 12257 final int count = pkg.activities.size(); 12258 ArrayList<IntentFilter> result = new ArrayList<>(); 12259 for (int n=0; n<count; n++) { 12260 PackageParser.Activity activity = pkg.activities.get(n); 12261 if (activity.intents != null && activity.intents.size() > 0) { 12262 result.addAll(activity.intents); 12263 } 12264 } 12265 return new ParceledListSlice<>(result); 12266 } 12267 } 12268 12269 @Override 12270 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 12271 mContext.enforceCallingOrSelfPermission( 12272 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12273 12274 synchronized (mPackages) { 12275 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 12276 if (packageName != null) { 12277 result |= updateIntentVerificationStatus(packageName, 12278 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 12279 userId); 12280 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 12281 packageName, userId); 12282 } 12283 return result; 12284 } 12285 } 12286 12287 @Override 12288 public String getDefaultBrowserPackageName(int userId) { 12289 synchronized (mPackages) { 12290 return mSettings.getDefaultBrowserPackageNameLPw(userId); 12291 } 12292 } 12293 12294 /** 12295 * Get the "allow unknown sources" setting. 12296 * 12297 * @return the current "allow unknown sources" setting 12298 */ 12299 private int getUnknownSourcesSettings() { 12300 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 12301 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 12302 -1); 12303 } 12304 12305 @Override 12306 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 12307 final int uid = Binder.getCallingUid(); 12308 // writer 12309 synchronized (mPackages) { 12310 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 12311 if (targetPackageSetting == null) { 12312 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 12313 } 12314 12315 PackageSetting installerPackageSetting; 12316 if (installerPackageName != null) { 12317 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 12318 if (installerPackageSetting == null) { 12319 throw new IllegalArgumentException("Unknown installer package: " 12320 + installerPackageName); 12321 } 12322 } else { 12323 installerPackageSetting = null; 12324 } 12325 12326 Signature[] callerSignature; 12327 Object obj = mSettings.getUserIdLPr(uid); 12328 if (obj != null) { 12329 if (obj instanceof SharedUserSetting) { 12330 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 12331 } else if (obj instanceof PackageSetting) { 12332 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 12333 } else { 12334 throw new SecurityException("Bad object " + obj + " for uid " + uid); 12335 } 12336 } else { 12337 throw new SecurityException("Unknown calling UID: " + uid); 12338 } 12339 12340 // Verify: can't set installerPackageName to a package that is 12341 // not signed with the same cert as the caller. 12342 if (installerPackageSetting != null) { 12343 if (compareSignatures(callerSignature, 12344 installerPackageSetting.signatures.mSignatures) 12345 != PackageManager.SIGNATURE_MATCH) { 12346 throw new SecurityException( 12347 "Caller does not have same cert as new installer package " 12348 + installerPackageName); 12349 } 12350 } 12351 12352 // Verify: if target already has an installer package, it must 12353 // be signed with the same cert as the caller. 12354 if (targetPackageSetting.installerPackageName != null) { 12355 PackageSetting setting = mSettings.mPackages.get( 12356 targetPackageSetting.installerPackageName); 12357 // If the currently set package isn't valid, then it's always 12358 // okay to change it. 12359 if (setting != null) { 12360 if (compareSignatures(callerSignature, 12361 setting.signatures.mSignatures) 12362 != PackageManager.SIGNATURE_MATCH) { 12363 throw new SecurityException( 12364 "Caller does not have same cert as old installer package " 12365 + targetPackageSetting.installerPackageName); 12366 } 12367 } 12368 } 12369 12370 // Okay! 12371 targetPackageSetting.installerPackageName = installerPackageName; 12372 if (installerPackageName != null) { 12373 mSettings.mInstallerPackages.add(installerPackageName); 12374 } 12375 scheduleWriteSettingsLocked(); 12376 } 12377 } 12378 12379 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 12380 // Queue up an async operation since the package installation may take a little while. 12381 mHandler.post(new Runnable() { 12382 public void run() { 12383 mHandler.removeCallbacks(this); 12384 // Result object to be returned 12385 PackageInstalledInfo res = new PackageInstalledInfo(); 12386 res.setReturnCode(currentStatus); 12387 res.uid = -1; 12388 res.pkg = null; 12389 res.removedInfo = null; 12390 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12391 args.doPreInstall(res.returnCode); 12392 synchronized (mInstallLock) { 12393 installPackageTracedLI(args, res); 12394 } 12395 args.doPostInstall(res.returnCode, res.uid); 12396 } 12397 12398 // A restore should be performed at this point if (a) the install 12399 // succeeded, (b) the operation is not an update, and (c) the new 12400 // package has not opted out of backup participation. 12401 final boolean update = res.removedInfo != null 12402 && res.removedInfo.removedPackage != null; 12403 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 12404 boolean doRestore = !update 12405 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 12406 12407 // Set up the post-install work request bookkeeping. This will be used 12408 // and cleaned up by the post-install event handling regardless of whether 12409 // there's a restore pass performed. Token values are >= 1. 12410 int token; 12411 if (mNextInstallToken < 0) mNextInstallToken = 1; 12412 token = mNextInstallToken++; 12413 12414 PostInstallData data = new PostInstallData(args, res); 12415 mRunningInstalls.put(token, data); 12416 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 12417 12418 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 12419 // Pass responsibility to the Backup Manager. It will perform a 12420 // restore if appropriate, then pass responsibility back to the 12421 // Package Manager to run the post-install observer callbacks 12422 // and broadcasts. 12423 IBackupManager bm = IBackupManager.Stub.asInterface( 12424 ServiceManager.getService(Context.BACKUP_SERVICE)); 12425 if (bm != null) { 12426 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 12427 + " to BM for possible restore"); 12428 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12429 try { 12430 // TODO: http://b/22388012 12431 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 12432 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 12433 } else { 12434 doRestore = false; 12435 } 12436 } catch (RemoteException e) { 12437 // can't happen; the backup manager is local 12438 } catch (Exception e) { 12439 Slog.e(TAG, "Exception trying to enqueue restore", e); 12440 doRestore = false; 12441 } 12442 } else { 12443 Slog.e(TAG, "Backup Manager not found!"); 12444 doRestore = false; 12445 } 12446 } 12447 12448 if (!doRestore) { 12449 // No restore possible, or the Backup Manager was mysteriously not 12450 // available -- just fire the post-install work request directly. 12451 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 12452 12453 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 12454 12455 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 12456 mHandler.sendMessage(msg); 12457 } 12458 } 12459 }); 12460 } 12461 12462 /** 12463 * Callback from PackageSettings whenever an app is first transitioned out of the 12464 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 12465 * the app was "launched" for a restoreAtInstall operation. Therefore we check 12466 * here whether the app is the target of an ongoing install, and only send the 12467 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 12468 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 12469 * handling. 12470 */ 12471 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 12472 // Serialize this with the rest of the install-process message chain. In the 12473 // restore-at-install case, this Runnable will necessarily run before the 12474 // POST_INSTALL message is processed, so the contents of mRunningInstalls 12475 // are coherent. In the non-restore case, the app has already completed install 12476 // and been launched through some other means, so it is not in a problematic 12477 // state for observers to see the FIRST_LAUNCH signal. 12478 mHandler.post(new Runnable() { 12479 @Override 12480 public void run() { 12481 for (int i = 0; i < mRunningInstalls.size(); i++) { 12482 final PostInstallData data = mRunningInstalls.valueAt(i); 12483 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 12484 // right package; but is it for the right user? 12485 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 12486 if (userId == data.res.newUsers[uIndex]) { 12487 if (DEBUG_BACKUP) { 12488 Slog.i(TAG, "Package " + pkgName 12489 + " being restored so deferring FIRST_LAUNCH"); 12490 } 12491 return; 12492 } 12493 } 12494 } 12495 } 12496 // didn't find it, so not being restored 12497 if (DEBUG_BACKUP) { 12498 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 12499 } 12500 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 12501 } 12502 }); 12503 } 12504 12505 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 12506 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 12507 installerPkg, null, userIds); 12508 } 12509 12510 private abstract class HandlerParams { 12511 private static final int MAX_RETRIES = 4; 12512 12513 /** 12514 * Number of times startCopy() has been attempted and had a non-fatal 12515 * error. 12516 */ 12517 private int mRetries = 0; 12518 12519 /** User handle for the user requesting the information or installation. */ 12520 private final UserHandle mUser; 12521 String traceMethod; 12522 int traceCookie; 12523 12524 HandlerParams(UserHandle user) { 12525 mUser = user; 12526 } 12527 12528 UserHandle getUser() { 12529 return mUser; 12530 } 12531 12532 HandlerParams setTraceMethod(String traceMethod) { 12533 this.traceMethod = traceMethod; 12534 return this; 12535 } 12536 12537 HandlerParams setTraceCookie(int traceCookie) { 12538 this.traceCookie = traceCookie; 12539 return this; 12540 } 12541 12542 final boolean startCopy() { 12543 boolean res; 12544 try { 12545 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 12546 12547 if (++mRetries > MAX_RETRIES) { 12548 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 12549 mHandler.sendEmptyMessage(MCS_GIVE_UP); 12550 handleServiceError(); 12551 return false; 12552 } else { 12553 handleStartCopy(); 12554 res = true; 12555 } 12556 } catch (RemoteException e) { 12557 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 12558 mHandler.sendEmptyMessage(MCS_RECONNECT); 12559 res = false; 12560 } 12561 handleReturnCode(); 12562 return res; 12563 } 12564 12565 final void serviceError() { 12566 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 12567 handleServiceError(); 12568 handleReturnCode(); 12569 } 12570 12571 abstract void handleStartCopy() throws RemoteException; 12572 abstract void handleServiceError(); 12573 abstract void handleReturnCode(); 12574 } 12575 12576 class MeasureParams extends HandlerParams { 12577 private final PackageStats mStats; 12578 private boolean mSuccess; 12579 12580 private final IPackageStatsObserver mObserver; 12581 12582 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 12583 super(new UserHandle(stats.userHandle)); 12584 mObserver = observer; 12585 mStats = stats; 12586 } 12587 12588 @Override 12589 public String toString() { 12590 return "MeasureParams{" 12591 + Integer.toHexString(System.identityHashCode(this)) 12592 + " " + mStats.packageName + "}"; 12593 } 12594 12595 @Override 12596 void handleStartCopy() throws RemoteException { 12597 synchronized (mInstallLock) { 12598 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 12599 } 12600 12601 if (mSuccess) { 12602 boolean mounted = false; 12603 try { 12604 final String status = Environment.getExternalStorageState(); 12605 mounted = (Environment.MEDIA_MOUNTED.equals(status) 12606 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 12607 } catch (Exception e) { 12608 } 12609 12610 if (mounted) { 12611 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 12612 12613 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 12614 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 12615 12616 mStats.externalDataSize = calculateDirectorySize(mContainerService, 12617 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 12618 12619 // Always subtract cache size, since it's a subdirectory 12620 mStats.externalDataSize -= mStats.externalCacheSize; 12621 12622 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 12623 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 12624 12625 mStats.externalObbSize = calculateDirectorySize(mContainerService, 12626 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 12627 } 12628 } 12629 } 12630 12631 @Override 12632 void handleReturnCode() { 12633 if (mObserver != null) { 12634 try { 12635 mObserver.onGetStatsCompleted(mStats, mSuccess); 12636 } catch (RemoteException e) { 12637 Slog.i(TAG, "Observer no longer exists."); 12638 } 12639 } 12640 } 12641 12642 @Override 12643 void handleServiceError() { 12644 Slog.e(TAG, "Could not measure application " + mStats.packageName 12645 + " external storage"); 12646 } 12647 } 12648 12649 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 12650 throws RemoteException { 12651 long result = 0; 12652 for (File path : paths) { 12653 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 12654 } 12655 return result; 12656 } 12657 12658 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 12659 for (File path : paths) { 12660 try { 12661 mcs.clearDirectory(path.getAbsolutePath()); 12662 } catch (RemoteException e) { 12663 } 12664 } 12665 } 12666 12667 static class OriginInfo { 12668 /** 12669 * Location where install is coming from, before it has been 12670 * copied/renamed into place. This could be a single monolithic APK 12671 * file, or a cluster directory. This location may be untrusted. 12672 */ 12673 final File file; 12674 final String cid; 12675 12676 /** 12677 * Flag indicating that {@link #file} or {@link #cid} has already been 12678 * staged, meaning downstream users don't need to defensively copy the 12679 * contents. 12680 */ 12681 final boolean staged; 12682 12683 /** 12684 * Flag indicating that {@link #file} or {@link #cid} is an already 12685 * installed app that is being moved. 12686 */ 12687 final boolean existing; 12688 12689 final String resolvedPath; 12690 final File resolvedFile; 12691 12692 static OriginInfo fromNothing() { 12693 return new OriginInfo(null, null, false, false); 12694 } 12695 12696 static OriginInfo fromUntrustedFile(File file) { 12697 return new OriginInfo(file, null, false, false); 12698 } 12699 12700 static OriginInfo fromExistingFile(File file) { 12701 return new OriginInfo(file, null, false, true); 12702 } 12703 12704 static OriginInfo fromStagedFile(File file) { 12705 return new OriginInfo(file, null, true, false); 12706 } 12707 12708 static OriginInfo fromStagedContainer(String cid) { 12709 return new OriginInfo(null, cid, true, false); 12710 } 12711 12712 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 12713 this.file = file; 12714 this.cid = cid; 12715 this.staged = staged; 12716 this.existing = existing; 12717 12718 if (cid != null) { 12719 resolvedPath = PackageHelper.getSdDir(cid); 12720 resolvedFile = new File(resolvedPath); 12721 } else if (file != null) { 12722 resolvedPath = file.getAbsolutePath(); 12723 resolvedFile = file; 12724 } else { 12725 resolvedPath = null; 12726 resolvedFile = null; 12727 } 12728 } 12729 } 12730 12731 static class MoveInfo { 12732 final int moveId; 12733 final String fromUuid; 12734 final String toUuid; 12735 final String packageName; 12736 final String dataAppName; 12737 final int appId; 12738 final String seinfo; 12739 final int targetSdkVersion; 12740 12741 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 12742 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 12743 this.moveId = moveId; 12744 this.fromUuid = fromUuid; 12745 this.toUuid = toUuid; 12746 this.packageName = packageName; 12747 this.dataAppName = dataAppName; 12748 this.appId = appId; 12749 this.seinfo = seinfo; 12750 this.targetSdkVersion = targetSdkVersion; 12751 } 12752 } 12753 12754 static class VerificationInfo { 12755 /** A constant used to indicate that a uid value is not present. */ 12756 public static final int NO_UID = -1; 12757 12758 /** URI referencing where the package was downloaded from. */ 12759 final Uri originatingUri; 12760 12761 /** HTTP referrer URI associated with the originatingURI. */ 12762 final Uri referrer; 12763 12764 /** UID of the application that the install request originated from. */ 12765 final int originatingUid; 12766 12767 /** UID of application requesting the install */ 12768 final int installerUid; 12769 12770 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 12771 this.originatingUri = originatingUri; 12772 this.referrer = referrer; 12773 this.originatingUid = originatingUid; 12774 this.installerUid = installerUid; 12775 } 12776 } 12777 12778 class InstallParams extends HandlerParams { 12779 final OriginInfo origin; 12780 final MoveInfo move; 12781 final IPackageInstallObserver2 observer; 12782 int installFlags; 12783 final String installerPackageName; 12784 final String volumeUuid; 12785 private InstallArgs mArgs; 12786 private int mRet; 12787 final String packageAbiOverride; 12788 final String[] grantedRuntimePermissions; 12789 final VerificationInfo verificationInfo; 12790 final Certificate[][] certificates; 12791 12792 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12793 int installFlags, String installerPackageName, String volumeUuid, 12794 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 12795 String[] grantedPermissions, Certificate[][] certificates) { 12796 super(user); 12797 this.origin = origin; 12798 this.move = move; 12799 this.observer = observer; 12800 this.installFlags = installFlags; 12801 this.installerPackageName = installerPackageName; 12802 this.volumeUuid = volumeUuid; 12803 this.verificationInfo = verificationInfo; 12804 this.packageAbiOverride = packageAbiOverride; 12805 this.grantedRuntimePermissions = grantedPermissions; 12806 this.certificates = certificates; 12807 } 12808 12809 @Override 12810 public String toString() { 12811 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 12812 + " file=" + origin.file + " cid=" + origin.cid + "}"; 12813 } 12814 12815 private int installLocationPolicy(PackageInfoLite pkgLite) { 12816 String packageName = pkgLite.packageName; 12817 int installLocation = pkgLite.installLocation; 12818 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12819 // reader 12820 synchronized (mPackages) { 12821 // Currently installed package which the new package is attempting to replace or 12822 // null if no such package is installed. 12823 PackageParser.Package installedPkg = mPackages.get(packageName); 12824 // Package which currently owns the data which the new package will own if installed. 12825 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 12826 // will be null whereas dataOwnerPkg will contain information about the package 12827 // which was uninstalled while keeping its data. 12828 PackageParser.Package dataOwnerPkg = installedPkg; 12829 if (dataOwnerPkg == null) { 12830 PackageSetting ps = mSettings.mPackages.get(packageName); 12831 if (ps != null) { 12832 dataOwnerPkg = ps.pkg; 12833 } 12834 } 12835 12836 if (dataOwnerPkg != null) { 12837 // If installed, the package will get access to data left on the device by its 12838 // predecessor. As a security measure, this is permited only if this is not a 12839 // version downgrade or if the predecessor package is marked as debuggable and 12840 // a downgrade is explicitly requested. 12841 // 12842 // On debuggable platform builds, downgrades are permitted even for 12843 // non-debuggable packages to make testing easier. Debuggable platform builds do 12844 // not offer security guarantees and thus it's OK to disable some security 12845 // mechanisms to make debugging/testing easier on those builds. However, even on 12846 // debuggable builds downgrades of packages are permitted only if requested via 12847 // installFlags. This is because we aim to keep the behavior of debuggable 12848 // platform builds as close as possible to the behavior of non-debuggable 12849 // platform builds. 12850 final boolean downgradeRequested = 12851 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 12852 final boolean packageDebuggable = 12853 (dataOwnerPkg.applicationInfo.flags 12854 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 12855 final boolean downgradePermitted = 12856 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 12857 if (!downgradePermitted) { 12858 try { 12859 checkDowngrade(dataOwnerPkg, pkgLite); 12860 } catch (PackageManagerException e) { 12861 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 12862 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 12863 } 12864 } 12865 } 12866 12867 if (installedPkg != null) { 12868 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12869 // Check for updated system application. 12870 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 12871 if (onSd) { 12872 Slog.w(TAG, "Cannot install update to system app on sdcard"); 12873 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 12874 } 12875 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12876 } else { 12877 if (onSd) { 12878 // Install flag overrides everything. 12879 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12880 } 12881 // If current upgrade specifies particular preference 12882 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 12883 // Application explicitly specified internal. 12884 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12885 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 12886 // App explictly prefers external. Let policy decide 12887 } else { 12888 // Prefer previous location 12889 if (isExternal(installedPkg)) { 12890 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12891 } 12892 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12893 } 12894 } 12895 } else { 12896 // Invalid install. Return error code 12897 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 12898 } 12899 } 12900 } 12901 // All the special cases have been taken care of. 12902 // Return result based on recommended install location. 12903 if (onSd) { 12904 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12905 } 12906 return pkgLite.recommendedInstallLocation; 12907 } 12908 12909 /* 12910 * Invoke remote method to get package information and install 12911 * location values. Override install location based on default 12912 * policy if needed and then create install arguments based 12913 * on the install location. 12914 */ 12915 public void handleStartCopy() throws RemoteException { 12916 int ret = PackageManager.INSTALL_SUCCEEDED; 12917 12918 // If we're already staged, we've firmly committed to an install location 12919 if (origin.staged) { 12920 if (origin.file != null) { 12921 installFlags |= PackageManager.INSTALL_INTERNAL; 12922 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12923 } else if (origin.cid != null) { 12924 installFlags |= PackageManager.INSTALL_EXTERNAL; 12925 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12926 } else { 12927 throw new IllegalStateException("Invalid stage location"); 12928 } 12929 } 12930 12931 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12932 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 12933 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12934 PackageInfoLite pkgLite = null; 12935 12936 if (onInt && onSd) { 12937 // Check if both bits are set. 12938 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 12939 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12940 } else if (onSd && ephemeral) { 12941 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 12942 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12943 } else { 12944 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 12945 packageAbiOverride); 12946 12947 if (DEBUG_EPHEMERAL && ephemeral) { 12948 Slog.v(TAG, "pkgLite for install: " + pkgLite); 12949 } 12950 12951 /* 12952 * If we have too little free space, try to free cache 12953 * before giving up. 12954 */ 12955 if (!origin.staged && pkgLite.recommendedInstallLocation 12956 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12957 // TODO: focus freeing disk space on the target device 12958 final StorageManager storage = StorageManager.from(mContext); 12959 final long lowThreshold = storage.getStorageLowBytes( 12960 Environment.getDataDirectory()); 12961 12962 final long sizeBytes = mContainerService.calculateInstalledSize( 12963 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 12964 12965 try { 12966 mInstaller.freeCache(null, sizeBytes + lowThreshold); 12967 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 12968 installFlags, packageAbiOverride); 12969 } catch (InstallerException e) { 12970 Slog.w(TAG, "Failed to free cache", e); 12971 } 12972 12973 /* 12974 * The cache free must have deleted the file we 12975 * downloaded to install. 12976 * 12977 * TODO: fix the "freeCache" call to not delete 12978 * the file we care about. 12979 */ 12980 if (pkgLite.recommendedInstallLocation 12981 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12982 pkgLite.recommendedInstallLocation 12983 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 12984 } 12985 } 12986 } 12987 12988 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12989 int loc = pkgLite.recommendedInstallLocation; 12990 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 12991 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12992 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 12993 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 12994 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12995 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12996 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 12997 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 12998 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12999 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 13000 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 13001 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 13002 } else { 13003 // Override with defaults if needed. 13004 loc = installLocationPolicy(pkgLite); 13005 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 13006 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 13007 } else if (!onSd && !onInt) { 13008 // Override install location with flags 13009 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 13010 // Set the flag to install on external media. 13011 installFlags |= PackageManager.INSTALL_EXTERNAL; 13012 installFlags &= ~PackageManager.INSTALL_INTERNAL; 13013 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 13014 if (DEBUG_EPHEMERAL) { 13015 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 13016 } 13017 installFlags |= PackageManager.INSTALL_EPHEMERAL; 13018 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 13019 |PackageManager.INSTALL_INTERNAL); 13020 } else { 13021 // Make sure the flag for installing on external 13022 // media is unset 13023 installFlags |= PackageManager.INSTALL_INTERNAL; 13024 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 13025 } 13026 } 13027 } 13028 } 13029 13030 final InstallArgs args = createInstallArgs(this); 13031 mArgs = args; 13032 13033 if (ret == PackageManager.INSTALL_SUCCEEDED) { 13034 // TODO: http://b/22976637 13035 // Apps installed for "all" users use the device owner to verify the app 13036 UserHandle verifierUser = getUser(); 13037 if (verifierUser == UserHandle.ALL) { 13038 verifierUser = UserHandle.SYSTEM; 13039 } 13040 13041 /* 13042 * Determine if we have any installed package verifiers. If we 13043 * do, then we'll defer to them to verify the packages. 13044 */ 13045 final int requiredUid = mRequiredVerifierPackage == null ? -1 13046 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 13047 verifierUser.getIdentifier()); 13048 if (!origin.existing && requiredUid != -1 13049 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 13050 final Intent verification = new Intent( 13051 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 13052 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 13053 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 13054 PACKAGE_MIME_TYPE); 13055 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 13056 13057 // Query all live verifiers based on current user state 13058 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 13059 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 13060 13061 if (DEBUG_VERIFY) { 13062 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 13063 + verification.toString() + " with " + pkgLite.verifiers.length 13064 + " optional verifiers"); 13065 } 13066 13067 final int verificationId = mPendingVerificationToken++; 13068 13069 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 13070 13071 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 13072 installerPackageName); 13073 13074 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 13075 installFlags); 13076 13077 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 13078 pkgLite.packageName); 13079 13080 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 13081 pkgLite.versionCode); 13082 13083 if (verificationInfo != null) { 13084 if (verificationInfo.originatingUri != null) { 13085 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 13086 verificationInfo.originatingUri); 13087 } 13088 if (verificationInfo.referrer != null) { 13089 verification.putExtra(Intent.EXTRA_REFERRER, 13090 verificationInfo.referrer); 13091 } 13092 if (verificationInfo.originatingUid >= 0) { 13093 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 13094 verificationInfo.originatingUid); 13095 } 13096 if (verificationInfo.installerUid >= 0) { 13097 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 13098 verificationInfo.installerUid); 13099 } 13100 } 13101 13102 final PackageVerificationState verificationState = new PackageVerificationState( 13103 requiredUid, args); 13104 13105 mPendingVerification.append(verificationId, verificationState); 13106 13107 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 13108 receivers, verificationState); 13109 13110 /* 13111 * If any sufficient verifiers were listed in the package 13112 * manifest, attempt to ask them. 13113 */ 13114 if (sufficientVerifiers != null) { 13115 final int N = sufficientVerifiers.size(); 13116 if (N == 0) { 13117 Slog.i(TAG, "Additional verifiers required, but none installed."); 13118 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 13119 } else { 13120 for (int i = 0; i < N; i++) { 13121 final ComponentName verifierComponent = sufficientVerifiers.get(i); 13122 13123 final Intent sufficientIntent = new Intent(verification); 13124 sufficientIntent.setComponent(verifierComponent); 13125 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 13126 } 13127 } 13128 } 13129 13130 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 13131 mRequiredVerifierPackage, receivers); 13132 if (ret == PackageManager.INSTALL_SUCCEEDED 13133 && mRequiredVerifierPackage != null) { 13134 Trace.asyncTraceBegin( 13135 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 13136 /* 13137 * Send the intent to the required verification agent, 13138 * but only start the verification timeout after the 13139 * target BroadcastReceivers have run. 13140 */ 13141 verification.setComponent(requiredVerifierComponent); 13142 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 13143 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13144 new BroadcastReceiver() { 13145 @Override 13146 public void onReceive(Context context, Intent intent) { 13147 final Message msg = mHandler 13148 .obtainMessage(CHECK_PENDING_VERIFICATION); 13149 msg.arg1 = verificationId; 13150 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 13151 } 13152 }, null, 0, null, null); 13153 13154 /* 13155 * We don't want the copy to proceed until verification 13156 * succeeds, so null out this field. 13157 */ 13158 mArgs = null; 13159 } 13160 } else { 13161 /* 13162 * No package verification is enabled, so immediately start 13163 * the remote call to initiate copy using temporary file. 13164 */ 13165 ret = args.copyApk(mContainerService, true); 13166 } 13167 } 13168 13169 mRet = ret; 13170 } 13171 13172 @Override 13173 void handleReturnCode() { 13174 // If mArgs is null, then MCS couldn't be reached. When it 13175 // reconnects, it will try again to install. At that point, this 13176 // will succeed. 13177 if (mArgs != null) { 13178 processPendingInstall(mArgs, mRet); 13179 } 13180 } 13181 13182 @Override 13183 void handleServiceError() { 13184 mArgs = createInstallArgs(this); 13185 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13186 } 13187 13188 public boolean isForwardLocked() { 13189 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13190 } 13191 } 13192 13193 /** 13194 * Used during creation of InstallArgs 13195 * 13196 * @param installFlags package installation flags 13197 * @return true if should be installed on external storage 13198 */ 13199 private static boolean installOnExternalAsec(int installFlags) { 13200 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 13201 return false; 13202 } 13203 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 13204 return true; 13205 } 13206 return false; 13207 } 13208 13209 /** 13210 * Used during creation of InstallArgs 13211 * 13212 * @param installFlags package installation flags 13213 * @return true if should be installed as forward locked 13214 */ 13215 private static boolean installForwardLocked(int installFlags) { 13216 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13217 } 13218 13219 private InstallArgs createInstallArgs(InstallParams params) { 13220 if (params.move != null) { 13221 return new MoveInstallArgs(params); 13222 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 13223 return new AsecInstallArgs(params); 13224 } else { 13225 return new FileInstallArgs(params); 13226 } 13227 } 13228 13229 /** 13230 * Create args that describe an existing installed package. Typically used 13231 * when cleaning up old installs, or used as a move source. 13232 */ 13233 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 13234 String resourcePath, String[] instructionSets) { 13235 final boolean isInAsec; 13236 if (installOnExternalAsec(installFlags)) { 13237 /* Apps on SD card are always in ASEC containers. */ 13238 isInAsec = true; 13239 } else if (installForwardLocked(installFlags) 13240 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 13241 /* 13242 * Forward-locked apps are only in ASEC containers if they're the 13243 * new style 13244 */ 13245 isInAsec = true; 13246 } else { 13247 isInAsec = false; 13248 } 13249 13250 if (isInAsec) { 13251 return new AsecInstallArgs(codePath, instructionSets, 13252 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 13253 } else { 13254 return new FileInstallArgs(codePath, resourcePath, instructionSets); 13255 } 13256 } 13257 13258 static abstract class InstallArgs { 13259 /** @see InstallParams#origin */ 13260 final OriginInfo origin; 13261 /** @see InstallParams#move */ 13262 final MoveInfo move; 13263 13264 final IPackageInstallObserver2 observer; 13265 // Always refers to PackageManager flags only 13266 final int installFlags; 13267 final String installerPackageName; 13268 final String volumeUuid; 13269 final UserHandle user; 13270 final String abiOverride; 13271 final String[] installGrantPermissions; 13272 /** If non-null, drop an async trace when the install completes */ 13273 final String traceMethod; 13274 final int traceCookie; 13275 final Certificate[][] certificates; 13276 13277 // The list of instruction sets supported by this app. This is currently 13278 // only used during the rmdex() phase to clean up resources. We can get rid of this 13279 // if we move dex files under the common app path. 13280 /* nullable */ String[] instructionSets; 13281 13282 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 13283 int installFlags, String installerPackageName, String volumeUuid, 13284 UserHandle user, String[] instructionSets, 13285 String abiOverride, String[] installGrantPermissions, 13286 String traceMethod, int traceCookie, Certificate[][] certificates) { 13287 this.origin = origin; 13288 this.move = move; 13289 this.installFlags = installFlags; 13290 this.observer = observer; 13291 this.installerPackageName = installerPackageName; 13292 this.volumeUuid = volumeUuid; 13293 this.user = user; 13294 this.instructionSets = instructionSets; 13295 this.abiOverride = abiOverride; 13296 this.installGrantPermissions = installGrantPermissions; 13297 this.traceMethod = traceMethod; 13298 this.traceCookie = traceCookie; 13299 this.certificates = certificates; 13300 } 13301 13302 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 13303 abstract int doPreInstall(int status); 13304 13305 /** 13306 * Rename package into final resting place. All paths on the given 13307 * scanned package should be updated to reflect the rename. 13308 */ 13309 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 13310 abstract int doPostInstall(int status, int uid); 13311 13312 /** @see PackageSettingBase#codePathString */ 13313 abstract String getCodePath(); 13314 /** @see PackageSettingBase#resourcePathString */ 13315 abstract String getResourcePath(); 13316 13317 // Need installer lock especially for dex file removal. 13318 abstract void cleanUpResourcesLI(); 13319 abstract boolean doPostDeleteLI(boolean delete); 13320 13321 /** 13322 * Called before the source arguments are copied. This is used mostly 13323 * for MoveParams when it needs to read the source file to put it in the 13324 * destination. 13325 */ 13326 int doPreCopy() { 13327 return PackageManager.INSTALL_SUCCEEDED; 13328 } 13329 13330 /** 13331 * Called after the source arguments are copied. This is used mostly for 13332 * MoveParams when it needs to read the source file to put it in the 13333 * destination. 13334 */ 13335 int doPostCopy(int uid) { 13336 return PackageManager.INSTALL_SUCCEEDED; 13337 } 13338 13339 protected boolean isFwdLocked() { 13340 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13341 } 13342 13343 protected boolean isExternalAsec() { 13344 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 13345 } 13346 13347 protected boolean isEphemeral() { 13348 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13349 } 13350 13351 UserHandle getUser() { 13352 return user; 13353 } 13354 } 13355 13356 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 13357 if (!allCodePaths.isEmpty()) { 13358 if (instructionSets == null) { 13359 throw new IllegalStateException("instructionSet == null"); 13360 } 13361 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 13362 for (String codePath : allCodePaths) { 13363 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 13364 try { 13365 mInstaller.rmdex(codePath, dexCodeInstructionSet); 13366 } catch (InstallerException ignored) { 13367 } 13368 } 13369 } 13370 } 13371 } 13372 13373 /** 13374 * Logic to handle installation of non-ASEC applications, including copying 13375 * and renaming logic. 13376 */ 13377 class FileInstallArgs extends InstallArgs { 13378 private File codeFile; 13379 private File resourceFile; 13380 13381 // Example topology: 13382 // /data/app/com.example/base.apk 13383 // /data/app/com.example/split_foo.apk 13384 // /data/app/com.example/lib/arm/libfoo.so 13385 // /data/app/com.example/lib/arm64/libfoo.so 13386 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 13387 13388 /** New install */ 13389 FileInstallArgs(InstallParams params) { 13390 super(params.origin, params.move, params.observer, params.installFlags, 13391 params.installerPackageName, params.volumeUuid, 13392 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 13393 params.grantedRuntimePermissions, 13394 params.traceMethod, params.traceCookie, params.certificates); 13395 if (isFwdLocked()) { 13396 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 13397 } 13398 } 13399 13400 /** Existing install */ 13401 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 13402 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 13403 null, null, null, 0, null /*certificates*/); 13404 this.codeFile = (codePath != null) ? new File(codePath) : null; 13405 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 13406 } 13407 13408 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13409 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 13410 try { 13411 return doCopyApk(imcs, temp); 13412 } finally { 13413 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13414 } 13415 } 13416 13417 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13418 if (origin.staged) { 13419 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 13420 codeFile = origin.file; 13421 resourceFile = origin.file; 13422 return PackageManager.INSTALL_SUCCEEDED; 13423 } 13424 13425 try { 13426 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13427 final File tempDir = 13428 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 13429 codeFile = tempDir; 13430 resourceFile = tempDir; 13431 } catch (IOException e) { 13432 Slog.w(TAG, "Failed to create copy file: " + e); 13433 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 13434 } 13435 13436 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 13437 @Override 13438 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 13439 if (!FileUtils.isValidExtFilename(name)) { 13440 throw new IllegalArgumentException("Invalid filename: " + name); 13441 } 13442 try { 13443 final File file = new File(codeFile, name); 13444 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 13445 O_RDWR | O_CREAT, 0644); 13446 Os.chmod(file.getAbsolutePath(), 0644); 13447 return new ParcelFileDescriptor(fd); 13448 } catch (ErrnoException e) { 13449 throw new RemoteException("Failed to open: " + e.getMessage()); 13450 } 13451 } 13452 }; 13453 13454 int ret = PackageManager.INSTALL_SUCCEEDED; 13455 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 13456 if (ret != PackageManager.INSTALL_SUCCEEDED) { 13457 Slog.e(TAG, "Failed to copy package"); 13458 return ret; 13459 } 13460 13461 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 13462 NativeLibraryHelper.Handle handle = null; 13463 try { 13464 handle = NativeLibraryHelper.Handle.create(codeFile); 13465 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 13466 abiOverride); 13467 } catch (IOException e) { 13468 Slog.e(TAG, "Copying native libraries failed", e); 13469 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13470 } finally { 13471 IoUtils.closeQuietly(handle); 13472 } 13473 13474 return ret; 13475 } 13476 13477 int doPreInstall(int status) { 13478 if (status != PackageManager.INSTALL_SUCCEEDED) { 13479 cleanUp(); 13480 } 13481 return status; 13482 } 13483 13484 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13485 if (status != PackageManager.INSTALL_SUCCEEDED) { 13486 cleanUp(); 13487 return false; 13488 } 13489 13490 final File targetDir = codeFile.getParentFile(); 13491 final File beforeCodeFile = codeFile; 13492 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 13493 13494 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 13495 try { 13496 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 13497 } catch (ErrnoException e) { 13498 Slog.w(TAG, "Failed to rename", e); 13499 return false; 13500 } 13501 13502 if (!SELinux.restoreconRecursive(afterCodeFile)) { 13503 Slog.w(TAG, "Failed to restorecon"); 13504 return false; 13505 } 13506 13507 // Reflect the rename internally 13508 codeFile = afterCodeFile; 13509 resourceFile = afterCodeFile; 13510 13511 // Reflect the rename in scanned details 13512 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13513 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13514 afterCodeFile, pkg.baseCodePath)); 13515 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13516 afterCodeFile, pkg.splitCodePaths)); 13517 13518 // Reflect the rename in app info 13519 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13520 pkg.setApplicationInfoCodePath(pkg.codePath); 13521 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13522 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13523 pkg.setApplicationInfoResourcePath(pkg.codePath); 13524 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13525 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13526 13527 return true; 13528 } 13529 13530 int doPostInstall(int status, int uid) { 13531 if (status != PackageManager.INSTALL_SUCCEEDED) { 13532 cleanUp(); 13533 } 13534 return status; 13535 } 13536 13537 @Override 13538 String getCodePath() { 13539 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13540 } 13541 13542 @Override 13543 String getResourcePath() { 13544 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13545 } 13546 13547 private boolean cleanUp() { 13548 if (codeFile == null || !codeFile.exists()) { 13549 return false; 13550 } 13551 13552 removeCodePathLI(codeFile); 13553 13554 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 13555 resourceFile.delete(); 13556 } 13557 13558 return true; 13559 } 13560 13561 void cleanUpResourcesLI() { 13562 // Try enumerating all code paths before deleting 13563 List<String> allCodePaths = Collections.EMPTY_LIST; 13564 if (codeFile != null && codeFile.exists()) { 13565 try { 13566 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13567 allCodePaths = pkg.getAllCodePaths(); 13568 } catch (PackageParserException e) { 13569 // Ignored; we tried our best 13570 } 13571 } 13572 13573 cleanUp(); 13574 removeDexFiles(allCodePaths, instructionSets); 13575 } 13576 13577 boolean doPostDeleteLI(boolean delete) { 13578 // XXX err, shouldn't we respect the delete flag? 13579 cleanUpResourcesLI(); 13580 return true; 13581 } 13582 } 13583 13584 private boolean isAsecExternal(String cid) { 13585 final String asecPath = PackageHelper.getSdFilesystem(cid); 13586 return !asecPath.startsWith(mAsecInternalPath); 13587 } 13588 13589 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 13590 PackageManagerException { 13591 if (copyRet < 0) { 13592 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 13593 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 13594 throw new PackageManagerException(copyRet, message); 13595 } 13596 } 13597 } 13598 13599 /** 13600 * Extract the MountService "container ID" from the full code path of an 13601 * .apk. 13602 */ 13603 static String cidFromCodePath(String fullCodePath) { 13604 int eidx = fullCodePath.lastIndexOf("/"); 13605 String subStr1 = fullCodePath.substring(0, eidx); 13606 int sidx = subStr1.lastIndexOf("/"); 13607 return subStr1.substring(sidx+1, eidx); 13608 } 13609 13610 /** 13611 * Logic to handle installation of ASEC applications, including copying and 13612 * renaming logic. 13613 */ 13614 class AsecInstallArgs extends InstallArgs { 13615 static final String RES_FILE_NAME = "pkg.apk"; 13616 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 13617 13618 String cid; 13619 String packagePath; 13620 String resourcePath; 13621 13622 /** New install */ 13623 AsecInstallArgs(InstallParams params) { 13624 super(params.origin, params.move, params.observer, params.installFlags, 13625 params.installerPackageName, params.volumeUuid, 13626 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13627 params.grantedRuntimePermissions, 13628 params.traceMethod, params.traceCookie, params.certificates); 13629 } 13630 13631 /** Existing install */ 13632 AsecInstallArgs(String fullCodePath, String[] instructionSets, 13633 boolean isExternal, boolean isForwardLocked) { 13634 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 13635 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13636 instructionSets, null, null, null, 0, null /*certificates*/); 13637 // Hackily pretend we're still looking at a full code path 13638 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 13639 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 13640 } 13641 13642 // Extract cid from fullCodePath 13643 int eidx = fullCodePath.lastIndexOf("/"); 13644 String subStr1 = fullCodePath.substring(0, eidx); 13645 int sidx = subStr1.lastIndexOf("/"); 13646 cid = subStr1.substring(sidx+1, eidx); 13647 setMountPath(subStr1); 13648 } 13649 13650 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 13651 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 13652 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13653 instructionSets, null, null, null, 0, null /*certificates*/); 13654 this.cid = cid; 13655 setMountPath(PackageHelper.getSdDir(cid)); 13656 } 13657 13658 void createCopyFile() { 13659 cid = mInstallerService.allocateExternalStageCidLegacy(); 13660 } 13661 13662 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13663 if (origin.staged && origin.cid != null) { 13664 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 13665 cid = origin.cid; 13666 setMountPath(PackageHelper.getSdDir(cid)); 13667 return PackageManager.INSTALL_SUCCEEDED; 13668 } 13669 13670 if (temp) { 13671 createCopyFile(); 13672 } else { 13673 /* 13674 * Pre-emptively destroy the container since it's destroyed if 13675 * copying fails due to it existing anyway. 13676 */ 13677 PackageHelper.destroySdDir(cid); 13678 } 13679 13680 final String newMountPath = imcs.copyPackageToContainer( 13681 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 13682 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 13683 13684 if (newMountPath != null) { 13685 setMountPath(newMountPath); 13686 return PackageManager.INSTALL_SUCCEEDED; 13687 } else { 13688 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13689 } 13690 } 13691 13692 @Override 13693 String getCodePath() { 13694 return packagePath; 13695 } 13696 13697 @Override 13698 String getResourcePath() { 13699 return resourcePath; 13700 } 13701 13702 int doPreInstall(int status) { 13703 if (status != PackageManager.INSTALL_SUCCEEDED) { 13704 // Destroy container 13705 PackageHelper.destroySdDir(cid); 13706 } else { 13707 boolean mounted = PackageHelper.isContainerMounted(cid); 13708 if (!mounted) { 13709 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 13710 Process.SYSTEM_UID); 13711 if (newMountPath != null) { 13712 setMountPath(newMountPath); 13713 } else { 13714 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13715 } 13716 } 13717 } 13718 return status; 13719 } 13720 13721 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13722 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 13723 String newMountPath = null; 13724 if (PackageHelper.isContainerMounted(cid)) { 13725 // Unmount the container 13726 if (!PackageHelper.unMountSdDir(cid)) { 13727 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 13728 return false; 13729 } 13730 } 13731 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13732 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 13733 " which might be stale. Will try to clean up."); 13734 // Clean up the stale container and proceed to recreate. 13735 if (!PackageHelper.destroySdDir(newCacheId)) { 13736 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 13737 return false; 13738 } 13739 // Successfully cleaned up stale container. Try to rename again. 13740 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13741 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 13742 + " inspite of cleaning it up."); 13743 return false; 13744 } 13745 } 13746 if (!PackageHelper.isContainerMounted(newCacheId)) { 13747 Slog.w(TAG, "Mounting container " + newCacheId); 13748 newMountPath = PackageHelper.mountSdDir(newCacheId, 13749 getEncryptKey(), Process.SYSTEM_UID); 13750 } else { 13751 newMountPath = PackageHelper.getSdDir(newCacheId); 13752 } 13753 if (newMountPath == null) { 13754 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 13755 return false; 13756 } 13757 Log.i(TAG, "Succesfully renamed " + cid + 13758 " to " + newCacheId + 13759 " at new path: " + newMountPath); 13760 cid = newCacheId; 13761 13762 final File beforeCodeFile = new File(packagePath); 13763 setMountPath(newMountPath); 13764 final File afterCodeFile = new File(packagePath); 13765 13766 // Reflect the rename in scanned details 13767 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13768 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13769 afterCodeFile, pkg.baseCodePath)); 13770 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13771 afterCodeFile, pkg.splitCodePaths)); 13772 13773 // Reflect the rename in app info 13774 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13775 pkg.setApplicationInfoCodePath(pkg.codePath); 13776 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13777 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13778 pkg.setApplicationInfoResourcePath(pkg.codePath); 13779 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13780 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13781 13782 return true; 13783 } 13784 13785 private void setMountPath(String mountPath) { 13786 final File mountFile = new File(mountPath); 13787 13788 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 13789 if (monolithicFile.exists()) { 13790 packagePath = monolithicFile.getAbsolutePath(); 13791 if (isFwdLocked()) { 13792 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 13793 } else { 13794 resourcePath = packagePath; 13795 } 13796 } else { 13797 packagePath = mountFile.getAbsolutePath(); 13798 resourcePath = packagePath; 13799 } 13800 } 13801 13802 int doPostInstall(int status, int uid) { 13803 if (status != PackageManager.INSTALL_SUCCEEDED) { 13804 cleanUp(); 13805 } else { 13806 final int groupOwner; 13807 final String protectedFile; 13808 if (isFwdLocked()) { 13809 groupOwner = UserHandle.getSharedAppGid(uid); 13810 protectedFile = RES_FILE_NAME; 13811 } else { 13812 groupOwner = -1; 13813 protectedFile = null; 13814 } 13815 13816 if (uid < Process.FIRST_APPLICATION_UID 13817 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 13818 Slog.e(TAG, "Failed to finalize " + cid); 13819 PackageHelper.destroySdDir(cid); 13820 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13821 } 13822 13823 boolean mounted = PackageHelper.isContainerMounted(cid); 13824 if (!mounted) { 13825 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 13826 } 13827 } 13828 return status; 13829 } 13830 13831 private void cleanUp() { 13832 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 13833 13834 // Destroy secure container 13835 PackageHelper.destroySdDir(cid); 13836 } 13837 13838 private List<String> getAllCodePaths() { 13839 final File codeFile = new File(getCodePath()); 13840 if (codeFile != null && codeFile.exists()) { 13841 try { 13842 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13843 return pkg.getAllCodePaths(); 13844 } catch (PackageParserException e) { 13845 // Ignored; we tried our best 13846 } 13847 } 13848 return Collections.EMPTY_LIST; 13849 } 13850 13851 void cleanUpResourcesLI() { 13852 // Enumerate all code paths before deleting 13853 cleanUpResourcesLI(getAllCodePaths()); 13854 } 13855 13856 private void cleanUpResourcesLI(List<String> allCodePaths) { 13857 cleanUp(); 13858 removeDexFiles(allCodePaths, instructionSets); 13859 } 13860 13861 String getPackageName() { 13862 return getAsecPackageName(cid); 13863 } 13864 13865 boolean doPostDeleteLI(boolean delete) { 13866 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 13867 final List<String> allCodePaths = getAllCodePaths(); 13868 boolean mounted = PackageHelper.isContainerMounted(cid); 13869 if (mounted) { 13870 // Unmount first 13871 if (PackageHelper.unMountSdDir(cid)) { 13872 mounted = false; 13873 } 13874 } 13875 if (!mounted && delete) { 13876 cleanUpResourcesLI(allCodePaths); 13877 } 13878 return !mounted; 13879 } 13880 13881 @Override 13882 int doPreCopy() { 13883 if (isFwdLocked()) { 13884 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 13885 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 13886 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13887 } 13888 } 13889 13890 return PackageManager.INSTALL_SUCCEEDED; 13891 } 13892 13893 @Override 13894 int doPostCopy(int uid) { 13895 if (isFwdLocked()) { 13896 if (uid < Process.FIRST_APPLICATION_UID 13897 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 13898 RES_FILE_NAME)) { 13899 Slog.e(TAG, "Failed to finalize " + cid); 13900 PackageHelper.destroySdDir(cid); 13901 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13902 } 13903 } 13904 13905 return PackageManager.INSTALL_SUCCEEDED; 13906 } 13907 } 13908 13909 /** 13910 * Logic to handle movement of existing installed applications. 13911 */ 13912 class MoveInstallArgs extends InstallArgs { 13913 private File codeFile; 13914 private File resourceFile; 13915 13916 /** New install */ 13917 MoveInstallArgs(InstallParams params) { 13918 super(params.origin, params.move, params.observer, params.installFlags, 13919 params.installerPackageName, params.volumeUuid, 13920 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13921 params.grantedRuntimePermissions, 13922 params.traceMethod, params.traceCookie, params.certificates); 13923 } 13924 13925 int copyApk(IMediaContainerService imcs, boolean temp) { 13926 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 13927 + move.fromUuid + " to " + move.toUuid); 13928 synchronized (mInstaller) { 13929 try { 13930 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 13931 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 13932 } catch (InstallerException e) { 13933 Slog.w(TAG, "Failed to move app", e); 13934 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13935 } 13936 } 13937 13938 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 13939 resourceFile = codeFile; 13940 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 13941 13942 return PackageManager.INSTALL_SUCCEEDED; 13943 } 13944 13945 int doPreInstall(int status) { 13946 if (status != PackageManager.INSTALL_SUCCEEDED) { 13947 cleanUp(move.toUuid); 13948 } 13949 return status; 13950 } 13951 13952 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13953 if (status != PackageManager.INSTALL_SUCCEEDED) { 13954 cleanUp(move.toUuid); 13955 return false; 13956 } 13957 13958 // Reflect the move in app info 13959 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13960 pkg.setApplicationInfoCodePath(pkg.codePath); 13961 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13962 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13963 pkg.setApplicationInfoResourcePath(pkg.codePath); 13964 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13965 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13966 13967 return true; 13968 } 13969 13970 int doPostInstall(int status, int uid) { 13971 if (status == PackageManager.INSTALL_SUCCEEDED) { 13972 cleanUp(move.fromUuid); 13973 } else { 13974 cleanUp(move.toUuid); 13975 } 13976 return status; 13977 } 13978 13979 @Override 13980 String getCodePath() { 13981 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13982 } 13983 13984 @Override 13985 String getResourcePath() { 13986 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13987 } 13988 13989 private boolean cleanUp(String volumeUuid) { 13990 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 13991 move.dataAppName); 13992 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 13993 final int[] userIds = sUserManager.getUserIds(); 13994 synchronized (mInstallLock) { 13995 // Clean up both app data and code 13996 // All package moves are frozen until finished 13997 for (int userId : userIds) { 13998 try { 13999 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 14000 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 14001 } catch (InstallerException e) { 14002 Slog.w(TAG, String.valueOf(e)); 14003 } 14004 } 14005 removeCodePathLI(codeFile); 14006 } 14007 return true; 14008 } 14009 14010 void cleanUpResourcesLI() { 14011 throw new UnsupportedOperationException(); 14012 } 14013 14014 boolean doPostDeleteLI(boolean delete) { 14015 throw new UnsupportedOperationException(); 14016 } 14017 } 14018 14019 static String getAsecPackageName(String packageCid) { 14020 int idx = packageCid.lastIndexOf("-"); 14021 if (idx == -1) { 14022 return packageCid; 14023 } 14024 return packageCid.substring(0, idx); 14025 } 14026 14027 // Utility method used to create code paths based on package name and available index. 14028 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 14029 String idxStr = ""; 14030 int idx = 1; 14031 // Fall back to default value of idx=1 if prefix is not 14032 // part of oldCodePath 14033 if (oldCodePath != null) { 14034 String subStr = oldCodePath; 14035 // Drop the suffix right away 14036 if (suffix != null && subStr.endsWith(suffix)) { 14037 subStr = subStr.substring(0, subStr.length() - suffix.length()); 14038 } 14039 // If oldCodePath already contains prefix find out the 14040 // ending index to either increment or decrement. 14041 int sidx = subStr.lastIndexOf(prefix); 14042 if (sidx != -1) { 14043 subStr = subStr.substring(sidx + prefix.length()); 14044 if (subStr != null) { 14045 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 14046 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 14047 } 14048 try { 14049 idx = Integer.parseInt(subStr); 14050 if (idx <= 1) { 14051 idx++; 14052 } else { 14053 idx--; 14054 } 14055 } catch(NumberFormatException e) { 14056 } 14057 } 14058 } 14059 } 14060 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 14061 return prefix + idxStr; 14062 } 14063 14064 private File getNextCodePath(File targetDir, String packageName) { 14065 int suffix = 1; 14066 File result; 14067 do { 14068 result = new File(targetDir, packageName + "-" + suffix); 14069 suffix++; 14070 } while (result.exists()); 14071 return result; 14072 } 14073 14074 // Utility method that returns the relative package path with respect 14075 // to the installation directory. Like say for /data/data/com.test-1.apk 14076 // string com.test-1 is returned. 14077 static String deriveCodePathName(String codePath) { 14078 if (codePath == null) { 14079 return null; 14080 } 14081 final File codeFile = new File(codePath); 14082 final String name = codeFile.getName(); 14083 if (codeFile.isDirectory()) { 14084 return name; 14085 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 14086 final int lastDot = name.lastIndexOf('.'); 14087 return name.substring(0, lastDot); 14088 } else { 14089 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 14090 return null; 14091 } 14092 } 14093 14094 static class PackageInstalledInfo { 14095 String name; 14096 int uid; 14097 // The set of users that originally had this package installed. 14098 int[] origUsers; 14099 // The set of users that now have this package installed. 14100 int[] newUsers; 14101 PackageParser.Package pkg; 14102 int returnCode; 14103 String returnMsg; 14104 PackageRemovedInfo removedInfo; 14105 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 14106 14107 public void setError(int code, String msg) { 14108 setReturnCode(code); 14109 setReturnMessage(msg); 14110 Slog.w(TAG, msg); 14111 } 14112 14113 public void setError(String msg, PackageParserException e) { 14114 setReturnCode(e.error); 14115 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 14116 Slog.w(TAG, msg, e); 14117 } 14118 14119 public void setError(String msg, PackageManagerException e) { 14120 returnCode = e.error; 14121 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 14122 Slog.w(TAG, msg, e); 14123 } 14124 14125 public void setReturnCode(int returnCode) { 14126 this.returnCode = returnCode; 14127 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 14128 for (int i = 0; i < childCount; i++) { 14129 addedChildPackages.valueAt(i).returnCode = returnCode; 14130 } 14131 } 14132 14133 private void setReturnMessage(String returnMsg) { 14134 this.returnMsg = returnMsg; 14135 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 14136 for (int i = 0; i < childCount; i++) { 14137 addedChildPackages.valueAt(i).returnMsg = returnMsg; 14138 } 14139 } 14140 14141 // In some error cases we want to convey more info back to the observer 14142 String origPackage; 14143 String origPermission; 14144 } 14145 14146 /* 14147 * Install a non-existing package. 14148 */ 14149 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 14150 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 14151 PackageInstalledInfo res) { 14152 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 14153 14154 // Remember this for later, in case we need to rollback this install 14155 String pkgName = pkg.packageName; 14156 14157 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 14158 14159 synchronized(mPackages) { 14160 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 14161 // A package with the same name is already installed, though 14162 // it has been renamed to an older name. The package we 14163 // are trying to install should be installed as an update to 14164 // the existing one, but that has not been requested, so bail. 14165 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 14166 + " without first uninstalling package running as " 14167 + mSettings.mRenamedPackages.get(pkgName)); 14168 return; 14169 } 14170 if (mPackages.containsKey(pkgName)) { 14171 // Don't allow installation over an existing package with the same name. 14172 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 14173 + " without first uninstalling."); 14174 return; 14175 } 14176 } 14177 14178 try { 14179 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 14180 System.currentTimeMillis(), user); 14181 14182 updateSettingsLI(newPackage, installerPackageName, null, res, user); 14183 14184 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14185 prepareAppDataAfterInstallLIF(newPackage); 14186 14187 } else { 14188 // Remove package from internal structures, but keep around any 14189 // data that might have already existed 14190 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 14191 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 14192 } 14193 } catch (PackageManagerException e) { 14194 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14195 } 14196 14197 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14198 } 14199 14200 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 14201 // Can't rotate keys during boot or if sharedUser. 14202 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 14203 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 14204 return false; 14205 } 14206 // app is using upgradeKeySets; make sure all are valid 14207 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14208 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 14209 for (int i = 0; i < upgradeKeySets.length; i++) { 14210 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 14211 Slog.wtf(TAG, "Package " 14212 + (oldPs.name != null ? oldPs.name : "<null>") 14213 + " contains upgrade-key-set reference to unknown key-set: " 14214 + upgradeKeySets[i] 14215 + " reverting to signatures check."); 14216 return false; 14217 } 14218 } 14219 return true; 14220 } 14221 14222 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 14223 // Upgrade keysets are being used. Determine if new package has a superset of the 14224 // required keys. 14225 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 14226 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14227 for (int i = 0; i < upgradeKeySets.length; i++) { 14228 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 14229 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 14230 return true; 14231 } 14232 } 14233 return false; 14234 } 14235 14236 private static void updateDigest(MessageDigest digest, File file) throws IOException { 14237 try (DigestInputStream digestStream = 14238 new DigestInputStream(new FileInputStream(file), digest)) { 14239 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 14240 } 14241 } 14242 14243 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 14244 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 14245 final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 14246 14247 final PackageParser.Package oldPackage; 14248 final String pkgName = pkg.packageName; 14249 final int[] allUsers; 14250 final int[] installedUsers; 14251 14252 synchronized(mPackages) { 14253 oldPackage = mPackages.get(pkgName); 14254 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 14255 14256 // don't allow upgrade to target a release SDK from a pre-release SDK 14257 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 14258 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14259 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 14260 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14261 if (oldTargetsPreRelease 14262 && !newTargetsPreRelease 14263 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 14264 Slog.w(TAG, "Can't install package targeting released sdk"); 14265 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 14266 return; 14267 } 14268 14269 // don't allow an upgrade from full to ephemeral 14270 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 14271 if (isEphemeral && !oldIsEphemeral) { 14272 // can't downgrade from full to ephemeral 14273 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 14274 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14275 return; 14276 } 14277 14278 // verify signatures are valid 14279 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14280 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14281 if (!checkUpgradeKeySetLP(ps, pkg)) { 14282 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14283 "New package not signed by keys specified by upgrade-keysets: " 14284 + pkgName); 14285 return; 14286 } 14287 } else { 14288 // default to original signature matching 14289 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 14290 != PackageManager.SIGNATURE_MATCH) { 14291 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14292 "New package has a different signature: " + pkgName); 14293 return; 14294 } 14295 } 14296 14297 // don't allow a system upgrade unless the upgrade hash matches 14298 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 14299 byte[] digestBytes = null; 14300 try { 14301 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 14302 updateDigest(digest, new File(pkg.baseCodePath)); 14303 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 14304 for (String path : pkg.splitCodePaths) { 14305 updateDigest(digest, new File(path)); 14306 } 14307 } 14308 digestBytes = digest.digest(); 14309 } catch (NoSuchAlgorithmException | IOException e) { 14310 res.setError(INSTALL_FAILED_INVALID_APK, 14311 "Could not compute hash: " + pkgName); 14312 return; 14313 } 14314 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 14315 res.setError(INSTALL_FAILED_INVALID_APK, 14316 "New package fails restrict-update check: " + pkgName); 14317 return; 14318 } 14319 // retain upgrade restriction 14320 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 14321 } 14322 14323 // Check for shared user id changes 14324 String invalidPackageName = 14325 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 14326 if (invalidPackageName != null) { 14327 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 14328 "Package " + invalidPackageName + " tried to change user " 14329 + oldPackage.mSharedUserId); 14330 return; 14331 } 14332 14333 // In case of rollback, remember per-user/profile install state 14334 allUsers = sUserManager.getUserIds(); 14335 installedUsers = ps.queryInstalledUsers(allUsers, true); 14336 } 14337 14338 // Update what is removed 14339 res.removedInfo = new PackageRemovedInfo(); 14340 res.removedInfo.uid = oldPackage.applicationInfo.uid; 14341 res.removedInfo.removedPackage = oldPackage.packageName; 14342 res.removedInfo.isUpdate = true; 14343 res.removedInfo.origUsers = installedUsers; 14344 final int childCount = (oldPackage.childPackages != null) 14345 ? oldPackage.childPackages.size() : 0; 14346 for (int i = 0; i < childCount; i++) { 14347 boolean childPackageUpdated = false; 14348 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 14349 if (res.addedChildPackages != null) { 14350 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14351 if (childRes != null) { 14352 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 14353 childRes.removedInfo.removedPackage = childPkg.packageName; 14354 childRes.removedInfo.isUpdate = true; 14355 childPackageUpdated = true; 14356 } 14357 } 14358 if (!childPackageUpdated) { 14359 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 14360 childRemovedRes.removedPackage = childPkg.packageName; 14361 childRemovedRes.isUpdate = false; 14362 childRemovedRes.dataRemoved = true; 14363 synchronized (mPackages) { 14364 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14365 if (childPs != null) { 14366 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 14367 } 14368 } 14369 if (res.removedInfo.removedChildPackages == null) { 14370 res.removedInfo.removedChildPackages = new ArrayMap<>(); 14371 } 14372 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 14373 } 14374 } 14375 14376 boolean sysPkg = (isSystemApp(oldPackage)); 14377 if (sysPkg) { 14378 // Set the system/privileged flags as needed 14379 final boolean privileged = 14380 (oldPackage.applicationInfo.privateFlags 14381 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14382 final int systemPolicyFlags = policyFlags 14383 | PackageParser.PARSE_IS_SYSTEM 14384 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 14385 14386 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 14387 user, allUsers, installerPackageName, res); 14388 } else { 14389 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 14390 user, allUsers, installerPackageName, res); 14391 } 14392 } 14393 14394 public List<String> getPreviousCodePaths(String packageName) { 14395 final PackageSetting ps = mSettings.mPackages.get(packageName); 14396 final List<String> result = new ArrayList<String>(); 14397 if (ps != null && ps.oldCodePaths != null) { 14398 result.addAll(ps.oldCodePaths); 14399 } 14400 return result; 14401 } 14402 14403 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 14404 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14405 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14406 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 14407 + deletedPackage); 14408 14409 String pkgName = deletedPackage.packageName; 14410 boolean deletedPkg = true; 14411 boolean addedPkg = false; 14412 boolean updatedSettings = false; 14413 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 14414 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 14415 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 14416 14417 final long origUpdateTime = (pkg.mExtras != null) 14418 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 14419 14420 // First delete the existing package while retaining the data directory 14421 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14422 res.removedInfo, true, pkg)) { 14423 // If the existing package wasn't successfully deleted 14424 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 14425 deletedPkg = false; 14426 } else { 14427 // Successfully deleted the old package; proceed with replace. 14428 14429 // If deleted package lived in a container, give users a chance to 14430 // relinquish resources before killing. 14431 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 14432 if (DEBUG_INSTALL) { 14433 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 14434 } 14435 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 14436 final ArrayList<String> pkgList = new ArrayList<String>(1); 14437 pkgList.add(deletedPackage.applicationInfo.packageName); 14438 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 14439 } 14440 14441 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14442 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14443 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14444 14445 try { 14446 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 14447 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 14448 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14449 14450 // Update the in-memory copy of the previous code paths. 14451 PackageSetting ps = mSettings.mPackages.get(pkgName); 14452 if (!killApp) { 14453 if (ps.oldCodePaths == null) { 14454 ps.oldCodePaths = new ArraySet<>(); 14455 } 14456 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 14457 if (deletedPackage.splitCodePaths != null) { 14458 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 14459 } 14460 } else { 14461 ps.oldCodePaths = null; 14462 } 14463 if (ps.childPackageNames != null) { 14464 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 14465 final String childPkgName = ps.childPackageNames.get(i); 14466 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 14467 childPs.oldCodePaths = ps.oldCodePaths; 14468 } 14469 } 14470 prepareAppDataAfterInstallLIF(newPackage); 14471 addedPkg = true; 14472 } catch (PackageManagerException e) { 14473 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14474 } 14475 } 14476 14477 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14478 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 14479 14480 // Revert all internal state mutations and added folders for the failed install 14481 if (addedPkg) { 14482 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14483 res.removedInfo, true, null); 14484 } 14485 14486 // Restore the old package 14487 if (deletedPkg) { 14488 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 14489 File restoreFile = new File(deletedPackage.codePath); 14490 // Parse old package 14491 boolean oldExternal = isExternal(deletedPackage); 14492 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 14493 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 14494 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 14495 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 14496 try { 14497 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 14498 null); 14499 } catch (PackageManagerException e) { 14500 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 14501 + e.getMessage()); 14502 return; 14503 } 14504 14505 synchronized (mPackages) { 14506 // Ensure the installer package name up to date 14507 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14508 14509 // Update permissions for restored package 14510 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14511 14512 mSettings.writeLPr(); 14513 } 14514 14515 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 14516 } 14517 } else { 14518 synchronized (mPackages) { 14519 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 14520 if (ps != null) { 14521 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 14522 if (res.removedInfo.removedChildPackages != null) { 14523 final int childCount = res.removedInfo.removedChildPackages.size(); 14524 // Iterate in reverse as we may modify the collection 14525 for (int i = childCount - 1; i >= 0; i--) { 14526 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 14527 if (res.addedChildPackages.containsKey(childPackageName)) { 14528 res.removedInfo.removedChildPackages.removeAt(i); 14529 } else { 14530 PackageRemovedInfo childInfo = res.removedInfo 14531 .removedChildPackages.valueAt(i); 14532 childInfo.removedForAllUsers = mPackages.get( 14533 childInfo.removedPackage) == null; 14534 } 14535 } 14536 } 14537 } 14538 } 14539 } 14540 } 14541 14542 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 14543 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14544 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14545 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 14546 + ", old=" + deletedPackage); 14547 14548 final boolean disabledSystem; 14549 14550 // Remove existing system package 14551 removePackageLI(deletedPackage, true); 14552 14553 synchronized (mPackages) { 14554 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 14555 } 14556 if (!disabledSystem) { 14557 // We didn't need to disable the .apk as a current system package, 14558 // which means we are replacing another update that is already 14559 // installed. We need to make sure to delete the older one's .apk. 14560 res.removedInfo.args = createInstallArgsForExisting(0, 14561 deletedPackage.applicationInfo.getCodePath(), 14562 deletedPackage.applicationInfo.getResourcePath(), 14563 getAppDexInstructionSets(deletedPackage.applicationInfo)); 14564 } else { 14565 res.removedInfo.args = null; 14566 } 14567 14568 // Successfully disabled the old package. Now proceed with re-installation 14569 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14570 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14571 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14572 14573 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14574 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 14575 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 14576 14577 PackageParser.Package newPackage = null; 14578 try { 14579 // Add the package to the internal data structures 14580 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 14581 14582 // Set the update and install times 14583 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 14584 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 14585 System.currentTimeMillis()); 14586 14587 // Update the package dynamic state if succeeded 14588 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14589 // Now that the install succeeded make sure we remove data 14590 // directories for any child package the update removed. 14591 final int deletedChildCount = (deletedPackage.childPackages != null) 14592 ? deletedPackage.childPackages.size() : 0; 14593 final int newChildCount = (newPackage.childPackages != null) 14594 ? newPackage.childPackages.size() : 0; 14595 for (int i = 0; i < deletedChildCount; i++) { 14596 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 14597 boolean childPackageDeleted = true; 14598 for (int j = 0; j < newChildCount; j++) { 14599 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 14600 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 14601 childPackageDeleted = false; 14602 break; 14603 } 14604 } 14605 if (childPackageDeleted) { 14606 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 14607 deletedChildPkg.packageName); 14608 if (ps != null && res.removedInfo.removedChildPackages != null) { 14609 PackageRemovedInfo removedChildRes = res.removedInfo 14610 .removedChildPackages.get(deletedChildPkg.packageName); 14611 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 14612 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 14613 } 14614 } 14615 } 14616 14617 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14618 prepareAppDataAfterInstallLIF(newPackage); 14619 } 14620 } catch (PackageManagerException e) { 14621 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 14622 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14623 } 14624 14625 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14626 // Re installation failed. Restore old information 14627 // Remove new pkg information 14628 if (newPackage != null) { 14629 removeInstalledPackageLI(newPackage, true); 14630 } 14631 // Add back the old system package 14632 try { 14633 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 14634 } catch (PackageManagerException e) { 14635 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 14636 } 14637 14638 synchronized (mPackages) { 14639 if (disabledSystem) { 14640 enableSystemPackageLPw(deletedPackage); 14641 } 14642 14643 // Ensure the installer package name up to date 14644 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14645 14646 // Update permissions for restored package 14647 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14648 14649 mSettings.writeLPr(); 14650 } 14651 14652 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 14653 + " after failed upgrade"); 14654 } 14655 } 14656 14657 /** 14658 * Checks whether the parent or any of the child packages have a change shared 14659 * user. For a package to be a valid update the shred users of the parent and 14660 * the children should match. We may later support changing child shared users. 14661 * @param oldPkg The updated package. 14662 * @param newPkg The update package. 14663 * @return The shared user that change between the versions. 14664 */ 14665 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 14666 PackageParser.Package newPkg) { 14667 // Check parent shared user 14668 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 14669 return newPkg.packageName; 14670 } 14671 // Check child shared users 14672 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14673 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 14674 for (int i = 0; i < newChildCount; i++) { 14675 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 14676 // If this child was present, did it have the same shared user? 14677 for (int j = 0; j < oldChildCount; j++) { 14678 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 14679 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 14680 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 14681 return newChildPkg.packageName; 14682 } 14683 } 14684 } 14685 return null; 14686 } 14687 14688 private void removeNativeBinariesLI(PackageSetting ps) { 14689 // Remove the lib path for the parent package 14690 if (ps != null) { 14691 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 14692 // Remove the lib path for the child packages 14693 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 14694 for (int i = 0; i < childCount; i++) { 14695 PackageSetting childPs = null; 14696 synchronized (mPackages) { 14697 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 14698 } 14699 if (childPs != null) { 14700 NativeLibraryHelper.removeNativeBinariesLI(childPs 14701 .legacyNativeLibraryPathString); 14702 } 14703 } 14704 } 14705 } 14706 14707 private void enableSystemPackageLPw(PackageParser.Package pkg) { 14708 // Enable the parent package 14709 mSettings.enableSystemPackageLPw(pkg.packageName); 14710 // Enable the child packages 14711 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14712 for (int i = 0; i < childCount; i++) { 14713 PackageParser.Package childPkg = pkg.childPackages.get(i); 14714 mSettings.enableSystemPackageLPw(childPkg.packageName); 14715 } 14716 } 14717 14718 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 14719 PackageParser.Package newPkg) { 14720 // Disable the parent package (parent always replaced) 14721 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 14722 // Disable the child packages 14723 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14724 for (int i = 0; i < childCount; i++) { 14725 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 14726 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 14727 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 14728 } 14729 return disabled; 14730 } 14731 14732 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 14733 String installerPackageName) { 14734 // Enable the parent package 14735 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 14736 // Enable the child packages 14737 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14738 for (int i = 0; i < childCount; i++) { 14739 PackageParser.Package childPkg = pkg.childPackages.get(i); 14740 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 14741 } 14742 } 14743 14744 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 14745 // Collect all used permissions in the UID 14746 ArraySet<String> usedPermissions = new ArraySet<>(); 14747 final int packageCount = su.packages.size(); 14748 for (int i = 0; i < packageCount; i++) { 14749 PackageSetting ps = su.packages.valueAt(i); 14750 if (ps.pkg == null) { 14751 continue; 14752 } 14753 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 14754 for (int j = 0; j < requestedPermCount; j++) { 14755 String permission = ps.pkg.requestedPermissions.get(j); 14756 BasePermission bp = mSettings.mPermissions.get(permission); 14757 if (bp != null) { 14758 usedPermissions.add(permission); 14759 } 14760 } 14761 } 14762 14763 PermissionsState permissionsState = su.getPermissionsState(); 14764 // Prune install permissions 14765 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 14766 final int installPermCount = installPermStates.size(); 14767 for (int i = installPermCount - 1; i >= 0; i--) { 14768 PermissionState permissionState = installPermStates.get(i); 14769 if (!usedPermissions.contains(permissionState.getName())) { 14770 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14771 if (bp != null) { 14772 permissionsState.revokeInstallPermission(bp); 14773 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 14774 PackageManager.MASK_PERMISSION_FLAGS, 0); 14775 } 14776 } 14777 } 14778 14779 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 14780 14781 // Prune runtime permissions 14782 for (int userId : allUserIds) { 14783 List<PermissionState> runtimePermStates = permissionsState 14784 .getRuntimePermissionStates(userId); 14785 final int runtimePermCount = runtimePermStates.size(); 14786 for (int i = runtimePermCount - 1; i >= 0; i--) { 14787 PermissionState permissionState = runtimePermStates.get(i); 14788 if (!usedPermissions.contains(permissionState.getName())) { 14789 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14790 if (bp != null) { 14791 permissionsState.revokeRuntimePermission(bp, userId); 14792 permissionsState.updatePermissionFlags(bp, userId, 14793 PackageManager.MASK_PERMISSION_FLAGS, 0); 14794 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 14795 runtimePermissionChangedUserIds, userId); 14796 } 14797 } 14798 } 14799 } 14800 14801 return runtimePermissionChangedUserIds; 14802 } 14803 14804 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 14805 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 14806 // Update the parent package setting 14807 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 14808 res, user); 14809 // Update the child packages setting 14810 final int childCount = (newPackage.childPackages != null) 14811 ? newPackage.childPackages.size() : 0; 14812 for (int i = 0; i < childCount; i++) { 14813 PackageParser.Package childPackage = newPackage.childPackages.get(i); 14814 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 14815 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 14816 childRes.origUsers, childRes, user); 14817 } 14818 } 14819 14820 private void updateSettingsInternalLI(PackageParser.Package newPackage, 14821 String installerPackageName, int[] allUsers, int[] installedForUsers, 14822 PackageInstalledInfo res, UserHandle user) { 14823 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 14824 14825 String pkgName = newPackage.packageName; 14826 synchronized (mPackages) { 14827 //write settings. the installStatus will be incomplete at this stage. 14828 //note that the new package setting would have already been 14829 //added to mPackages. It hasn't been persisted yet. 14830 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 14831 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14832 mSettings.writeLPr(); 14833 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14834 } 14835 14836 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 14837 synchronized (mPackages) { 14838 updatePermissionsLPw(newPackage.packageName, newPackage, 14839 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 14840 ? UPDATE_PERMISSIONS_ALL : 0)); 14841 // For system-bundled packages, we assume that installing an upgraded version 14842 // of the package implies that the user actually wants to run that new code, 14843 // so we enable the package. 14844 PackageSetting ps = mSettings.mPackages.get(pkgName); 14845 final int userId = user.getIdentifier(); 14846 if (ps != null) { 14847 if (isSystemApp(newPackage)) { 14848 if (DEBUG_INSTALL) { 14849 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 14850 } 14851 // Enable system package for requested users 14852 if (res.origUsers != null) { 14853 for (int origUserId : res.origUsers) { 14854 if (userId == UserHandle.USER_ALL || userId == origUserId) { 14855 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 14856 origUserId, installerPackageName); 14857 } 14858 } 14859 } 14860 // Also convey the prior install/uninstall state 14861 if (allUsers != null && installedForUsers != null) { 14862 for (int currentUserId : allUsers) { 14863 final boolean installed = ArrayUtils.contains( 14864 installedForUsers, currentUserId); 14865 if (DEBUG_INSTALL) { 14866 Slog.d(TAG, " user " + currentUserId + " => " + installed); 14867 } 14868 ps.setInstalled(installed, currentUserId); 14869 } 14870 // these install state changes will be persisted in the 14871 // upcoming call to mSettings.writeLPr(). 14872 } 14873 } 14874 // It's implied that when a user requests installation, they want the app to be 14875 // installed and enabled. 14876 if (userId != UserHandle.USER_ALL) { 14877 ps.setInstalled(true, userId); 14878 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 14879 } 14880 } 14881 res.name = pkgName; 14882 res.uid = newPackage.applicationInfo.uid; 14883 res.pkg = newPackage; 14884 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 14885 mSettings.setInstallerPackageName(pkgName, installerPackageName); 14886 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14887 //to update install status 14888 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14889 mSettings.writeLPr(); 14890 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14891 } 14892 14893 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14894 } 14895 14896 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 14897 try { 14898 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 14899 installPackageLI(args, res); 14900 } finally { 14901 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14902 } 14903 } 14904 14905 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 14906 final int installFlags = args.installFlags; 14907 final String installerPackageName = args.installerPackageName; 14908 final String volumeUuid = args.volumeUuid; 14909 final File tmpPackageFile = new File(args.getCodePath()); 14910 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 14911 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 14912 || (args.volumeUuid != null)); 14913 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 14914 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 14915 boolean replace = false; 14916 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 14917 if (args.move != null) { 14918 // moving a complete application; perform an initial scan on the new install location 14919 scanFlags |= SCAN_INITIAL; 14920 } 14921 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 14922 scanFlags |= SCAN_DONT_KILL_APP; 14923 } 14924 14925 // Result object to be returned 14926 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14927 14928 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 14929 14930 // Sanity check 14931 if (ephemeral && (forwardLocked || onExternal)) { 14932 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 14933 + " external=" + onExternal); 14934 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14935 return; 14936 } 14937 14938 // Retrieve PackageSettings and parse package 14939 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 14940 | PackageParser.PARSE_ENFORCE_CODE 14941 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 14942 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 14943 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0) 14944 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 14945 PackageParser pp = new PackageParser(); 14946 pp.setSeparateProcesses(mSeparateProcesses); 14947 pp.setDisplayMetrics(mMetrics); 14948 14949 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 14950 final PackageParser.Package pkg; 14951 try { 14952 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 14953 } catch (PackageParserException e) { 14954 res.setError("Failed parse during installPackageLI", e); 14955 return; 14956 } finally { 14957 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14958 } 14959 14960 // If we are installing a clustered package add results for the children 14961 if (pkg.childPackages != null) { 14962 synchronized (mPackages) { 14963 final int childCount = pkg.childPackages.size(); 14964 for (int i = 0; i < childCount; i++) { 14965 PackageParser.Package childPkg = pkg.childPackages.get(i); 14966 PackageInstalledInfo childRes = new PackageInstalledInfo(); 14967 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14968 childRes.pkg = childPkg; 14969 childRes.name = childPkg.packageName; 14970 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14971 if (childPs != null) { 14972 childRes.origUsers = childPs.queryInstalledUsers( 14973 sUserManager.getUserIds(), true); 14974 } 14975 if ((mPackages.containsKey(childPkg.packageName))) { 14976 childRes.removedInfo = new PackageRemovedInfo(); 14977 childRes.removedInfo.removedPackage = childPkg.packageName; 14978 } 14979 if (res.addedChildPackages == null) { 14980 res.addedChildPackages = new ArrayMap<>(); 14981 } 14982 res.addedChildPackages.put(childPkg.packageName, childRes); 14983 } 14984 } 14985 } 14986 14987 // If package doesn't declare API override, mark that we have an install 14988 // time CPU ABI override. 14989 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 14990 pkg.cpuAbiOverride = args.abiOverride; 14991 } 14992 14993 String pkgName = res.name = pkg.packageName; 14994 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 14995 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 14996 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 14997 return; 14998 } 14999 } 15000 15001 try { 15002 // either use what we've been given or parse directly from the APK 15003 if (args.certificates != null) { 15004 try { 15005 PackageParser.populateCertificates(pkg, args.certificates); 15006 } catch (PackageParserException e) { 15007 // there was something wrong with the certificates we were given; 15008 // try to pull them from the APK 15009 PackageParser.collectCertificates(pkg, parseFlags); 15010 } 15011 } else { 15012 PackageParser.collectCertificates(pkg, parseFlags); 15013 } 15014 } catch (PackageParserException e) { 15015 res.setError("Failed collect during installPackageLI", e); 15016 return; 15017 } 15018 15019 // Get rid of all references to package scan path via parser. 15020 pp = null; 15021 String oldCodePath = null; 15022 boolean systemApp = false; 15023 synchronized (mPackages) { 15024 // Check if installing already existing package 15025 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 15026 String oldName = mSettings.mRenamedPackages.get(pkgName); 15027 if (pkg.mOriginalPackages != null 15028 && pkg.mOriginalPackages.contains(oldName) 15029 && mPackages.containsKey(oldName)) { 15030 // This package is derived from an original package, 15031 // and this device has been updating from that original 15032 // name. We must continue using the original name, so 15033 // rename the new package here. 15034 pkg.setPackageName(oldName); 15035 pkgName = pkg.packageName; 15036 replace = true; 15037 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 15038 + oldName + " pkgName=" + pkgName); 15039 } else if (mPackages.containsKey(pkgName)) { 15040 // This package, under its official name, already exists 15041 // on the device; we should replace it. 15042 replace = true; 15043 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 15044 } 15045 15046 // Child packages are installed through the parent package 15047 if (pkg.parentPackage != null) { 15048 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 15049 "Package " + pkg.packageName + " is child of package " 15050 + pkg.parentPackage.parentPackage + ". Child packages " 15051 + "can be updated only through the parent package."); 15052 return; 15053 } 15054 15055 if (replace) { 15056 // Prevent apps opting out from runtime permissions 15057 PackageParser.Package oldPackage = mPackages.get(pkgName); 15058 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 15059 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 15060 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 15061 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 15062 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 15063 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 15064 + " doesn't support runtime permissions but the old" 15065 + " target SDK " + oldTargetSdk + " does."); 15066 return; 15067 } 15068 15069 // Prevent installing of child packages 15070 if (oldPackage.parentPackage != null) { 15071 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 15072 "Package " + pkg.packageName + " is child of package " 15073 + oldPackage.parentPackage + ". Child packages " 15074 + "can be updated only through the parent package."); 15075 return; 15076 } 15077 } 15078 } 15079 15080 PackageSetting ps = mSettings.mPackages.get(pkgName); 15081 if (ps != null) { 15082 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 15083 15084 // Quick sanity check that we're signed correctly if updating; 15085 // we'll check this again later when scanning, but we want to 15086 // bail early here before tripping over redefined permissions. 15087 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 15088 if (!checkUpgradeKeySetLP(ps, pkg)) { 15089 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 15090 + pkg.packageName + " upgrade keys do not match the " 15091 + "previously installed version"); 15092 return; 15093 } 15094 } else { 15095 try { 15096 verifySignaturesLP(ps, pkg); 15097 } catch (PackageManagerException e) { 15098 res.setError(e.error, e.getMessage()); 15099 return; 15100 } 15101 } 15102 15103 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 15104 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 15105 systemApp = (ps.pkg.applicationInfo.flags & 15106 ApplicationInfo.FLAG_SYSTEM) != 0; 15107 } 15108 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 15109 } 15110 15111 // Check whether the newly-scanned package wants to define an already-defined perm 15112 int N = pkg.permissions.size(); 15113 for (int i = N-1; i >= 0; i--) { 15114 PackageParser.Permission perm = pkg.permissions.get(i); 15115 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 15116 if (bp != null) { 15117 // If the defining package is signed with our cert, it's okay. This 15118 // also includes the "updating the same package" case, of course. 15119 // "updating same package" could also involve key-rotation. 15120 final boolean sigsOk; 15121 if (bp.sourcePackage.equals(pkg.packageName) 15122 && (bp.packageSetting instanceof PackageSetting) 15123 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 15124 scanFlags))) { 15125 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 15126 } else { 15127 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 15128 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 15129 } 15130 if (!sigsOk) { 15131 // If the owning package is the system itself, we log but allow 15132 // install to proceed; we fail the install on all other permission 15133 // redefinitions. 15134 if (!bp.sourcePackage.equals("android")) { 15135 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 15136 + pkg.packageName + " attempting to redeclare permission " 15137 + perm.info.name + " already owned by " + bp.sourcePackage); 15138 res.origPermission = perm.info.name; 15139 res.origPackage = bp.sourcePackage; 15140 return; 15141 } else { 15142 Slog.w(TAG, "Package " + pkg.packageName 15143 + " attempting to redeclare system permission " 15144 + perm.info.name + "; ignoring new declaration"); 15145 pkg.permissions.remove(i); 15146 } 15147 } 15148 } 15149 } 15150 } 15151 15152 if (systemApp) { 15153 if (onExternal) { 15154 // Abort update; system app can't be replaced with app on sdcard 15155 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 15156 "Cannot install updates to system apps on sdcard"); 15157 return; 15158 } else if (ephemeral) { 15159 // Abort update; system app can't be replaced with an ephemeral app 15160 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 15161 "Cannot update a system app with an ephemeral app"); 15162 return; 15163 } 15164 } 15165 15166 if (args.move != null) { 15167 // We did an in-place move, so dex is ready to roll 15168 scanFlags |= SCAN_NO_DEX; 15169 scanFlags |= SCAN_MOVE; 15170 15171 synchronized (mPackages) { 15172 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15173 if (ps == null) { 15174 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 15175 "Missing settings for moved package " + pkgName); 15176 } 15177 15178 // We moved the entire application as-is, so bring over the 15179 // previously derived ABI information. 15180 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 15181 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 15182 } 15183 15184 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 15185 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 15186 scanFlags |= SCAN_NO_DEX; 15187 15188 try { 15189 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 15190 args.abiOverride : pkg.cpuAbiOverride); 15191 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 15192 true /* extract libs */); 15193 } catch (PackageManagerException pme) { 15194 Slog.e(TAG, "Error deriving application ABI", pme); 15195 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 15196 return; 15197 } 15198 15199 // Shared libraries for the package need to be updated. 15200 synchronized (mPackages) { 15201 try { 15202 updateSharedLibrariesLPw(pkg, null); 15203 } catch (PackageManagerException e) { 15204 Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage()); 15205 } 15206 } 15207 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 15208 // Do not run PackageDexOptimizer through the local performDexOpt 15209 // method because `pkg` may not be in `mPackages` yet. 15210 // 15211 // Also, don't fail application installs if the dexopt step fails. 15212 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 15213 null /* instructionSets */, false /* checkProfiles */, 15214 getCompilerFilterForReason(REASON_INSTALL)); 15215 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15216 15217 // Notify BackgroundDexOptService that the package has been changed. 15218 // If this is an update of a package which used to fail to compile, 15219 // BDOS will remove it from its blacklist. 15220 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 15221 } 15222 15223 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 15224 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 15225 return; 15226 } 15227 15228 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 15229 15230 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 15231 "installPackageLI")) { 15232 if (replace) { 15233 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 15234 installerPackageName, res); 15235 } else { 15236 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 15237 args.user, installerPackageName, volumeUuid, res); 15238 } 15239 } 15240 synchronized (mPackages) { 15241 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15242 if (ps != null) { 15243 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 15244 } 15245 15246 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15247 for (int i = 0; i < childCount; i++) { 15248 PackageParser.Package childPkg = pkg.childPackages.get(i); 15249 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 15250 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 15251 if (childPs != null) { 15252 childRes.newUsers = childPs.queryInstalledUsers( 15253 sUserManager.getUserIds(), true); 15254 } 15255 } 15256 } 15257 } 15258 15259 private void startIntentFilterVerifications(int userId, boolean replacing, 15260 PackageParser.Package pkg) { 15261 if (mIntentFilterVerifierComponent == null) { 15262 Slog.w(TAG, "No IntentFilter verification will not be done as " 15263 + "there is no IntentFilterVerifier available!"); 15264 return; 15265 } 15266 15267 final int verifierUid = getPackageUid( 15268 mIntentFilterVerifierComponent.getPackageName(), 15269 MATCH_DEBUG_TRIAGED_MISSING, 15270 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 15271 15272 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15273 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 15274 mHandler.sendMessage(msg); 15275 15276 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15277 for (int i = 0; i < childCount; i++) { 15278 PackageParser.Package childPkg = pkg.childPackages.get(i); 15279 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15280 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 15281 mHandler.sendMessage(msg); 15282 } 15283 } 15284 15285 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 15286 PackageParser.Package pkg) { 15287 int size = pkg.activities.size(); 15288 if (size == 0) { 15289 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15290 "No activity, so no need to verify any IntentFilter!"); 15291 return; 15292 } 15293 15294 final boolean hasDomainURLs = hasDomainURLs(pkg); 15295 if (!hasDomainURLs) { 15296 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15297 "No domain URLs, so no need to verify any IntentFilter!"); 15298 return; 15299 } 15300 15301 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 15302 + " if any IntentFilter from the " + size 15303 + " Activities needs verification ..."); 15304 15305 int count = 0; 15306 final String packageName = pkg.packageName; 15307 15308 synchronized (mPackages) { 15309 // If this is a new install and we see that we've already run verification for this 15310 // package, we have nothing to do: it means the state was restored from backup. 15311 if (!replacing) { 15312 IntentFilterVerificationInfo ivi = 15313 mSettings.getIntentFilterVerificationLPr(packageName); 15314 if (ivi != null) { 15315 if (DEBUG_DOMAIN_VERIFICATION) { 15316 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 15317 + ivi.getStatusString()); 15318 } 15319 return; 15320 } 15321 } 15322 15323 // If any filters need to be verified, then all need to be. 15324 boolean needToVerify = false; 15325 for (PackageParser.Activity a : pkg.activities) { 15326 for (ActivityIntentInfo filter : a.intents) { 15327 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 15328 if (DEBUG_DOMAIN_VERIFICATION) { 15329 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 15330 } 15331 needToVerify = true; 15332 break; 15333 } 15334 } 15335 } 15336 15337 if (needToVerify) { 15338 final int verificationId = mIntentFilterVerificationToken++; 15339 for (PackageParser.Activity a : pkg.activities) { 15340 for (ActivityIntentInfo filter : a.intents) { 15341 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 15342 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15343 "Verification needed for IntentFilter:" + filter.toString()); 15344 mIntentFilterVerifier.addOneIntentFilterVerification( 15345 verifierUid, userId, verificationId, filter, packageName); 15346 count++; 15347 } 15348 } 15349 } 15350 } 15351 } 15352 15353 if (count > 0) { 15354 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 15355 + " IntentFilter verification" + (count > 1 ? "s" : "") 15356 + " for userId:" + userId); 15357 mIntentFilterVerifier.startVerifications(userId); 15358 } else { 15359 if (DEBUG_DOMAIN_VERIFICATION) { 15360 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 15361 } 15362 } 15363 } 15364 15365 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 15366 final ComponentName cn = filter.activity.getComponentName(); 15367 final String packageName = cn.getPackageName(); 15368 15369 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 15370 packageName); 15371 if (ivi == null) { 15372 return true; 15373 } 15374 int status = ivi.getStatus(); 15375 switch (status) { 15376 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 15377 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 15378 return true; 15379 15380 default: 15381 // Nothing to do 15382 return false; 15383 } 15384 } 15385 15386 private static boolean isMultiArch(ApplicationInfo info) { 15387 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 15388 } 15389 15390 private static boolean isExternal(PackageParser.Package pkg) { 15391 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15392 } 15393 15394 private static boolean isExternal(PackageSetting ps) { 15395 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15396 } 15397 15398 private static boolean isEphemeral(PackageParser.Package pkg) { 15399 return pkg.applicationInfo.isEphemeralApp(); 15400 } 15401 15402 private static boolean isEphemeral(PackageSetting ps) { 15403 return ps.pkg != null && isEphemeral(ps.pkg); 15404 } 15405 15406 private static boolean isSystemApp(PackageParser.Package pkg) { 15407 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 15408 } 15409 15410 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 15411 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 15412 } 15413 15414 private static boolean hasDomainURLs(PackageParser.Package pkg) { 15415 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 15416 } 15417 15418 private static boolean isSystemApp(PackageSetting ps) { 15419 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 15420 } 15421 15422 private static boolean isUpdatedSystemApp(PackageSetting ps) { 15423 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 15424 } 15425 15426 private int packageFlagsToInstallFlags(PackageSetting ps) { 15427 int installFlags = 0; 15428 if (isEphemeral(ps)) { 15429 installFlags |= PackageManager.INSTALL_EPHEMERAL; 15430 } 15431 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 15432 // This existing package was an external ASEC install when we have 15433 // the external flag without a UUID 15434 installFlags |= PackageManager.INSTALL_EXTERNAL; 15435 } 15436 if (ps.isForwardLocked()) { 15437 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 15438 } 15439 return installFlags; 15440 } 15441 15442 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 15443 if (isExternal(pkg)) { 15444 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15445 return StorageManager.UUID_PRIMARY_PHYSICAL; 15446 } else { 15447 return pkg.volumeUuid; 15448 } 15449 } else { 15450 return StorageManager.UUID_PRIVATE_INTERNAL; 15451 } 15452 } 15453 15454 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 15455 if (isExternal(pkg)) { 15456 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15457 return mSettings.getExternalVersion(); 15458 } else { 15459 return mSettings.findOrCreateVersion(pkg.volumeUuid); 15460 } 15461 } else { 15462 return mSettings.getInternalVersion(); 15463 } 15464 } 15465 15466 private void deleteTempPackageFiles() { 15467 final FilenameFilter filter = new FilenameFilter() { 15468 public boolean accept(File dir, String name) { 15469 return name.startsWith("vmdl") && name.endsWith(".tmp"); 15470 } 15471 }; 15472 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 15473 file.delete(); 15474 } 15475 } 15476 15477 @Override 15478 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 15479 int flags) { 15480 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 15481 flags); 15482 } 15483 15484 @Override 15485 public void deletePackage(final String packageName, 15486 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 15487 mContext.enforceCallingOrSelfPermission( 15488 android.Manifest.permission.DELETE_PACKAGES, null); 15489 Preconditions.checkNotNull(packageName); 15490 Preconditions.checkNotNull(observer); 15491 final int uid = Binder.getCallingUid(); 15492 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 15493 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 15494 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 15495 mContext.enforceCallingOrSelfPermission( 15496 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 15497 "deletePackage for user " + userId); 15498 } 15499 15500 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 15501 try { 15502 observer.onPackageDeleted(packageName, 15503 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 15504 } catch (RemoteException re) { 15505 } 15506 return; 15507 } 15508 15509 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 15510 try { 15511 observer.onPackageDeleted(packageName, 15512 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 15513 } catch (RemoteException re) { 15514 } 15515 return; 15516 } 15517 15518 if (DEBUG_REMOVE) { 15519 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 15520 + " deleteAllUsers: " + deleteAllUsers ); 15521 } 15522 // Queue up an async operation since the package deletion may take a little while. 15523 mHandler.post(new Runnable() { 15524 public void run() { 15525 mHandler.removeCallbacks(this); 15526 int returnCode; 15527 if (!deleteAllUsers) { 15528 returnCode = deletePackageX(packageName, userId, deleteFlags); 15529 } else { 15530 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 15531 // If nobody is blocking uninstall, proceed with delete for all users 15532 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 15533 returnCode = deletePackageX(packageName, userId, deleteFlags); 15534 } else { 15535 // Otherwise uninstall individually for users with blockUninstalls=false 15536 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 15537 for (int userId : users) { 15538 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 15539 returnCode = deletePackageX(packageName, userId, userFlags); 15540 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 15541 Slog.w(TAG, "Package delete failed for user " + userId 15542 + ", returnCode " + returnCode); 15543 } 15544 } 15545 } 15546 // The app has only been marked uninstalled for certain users. 15547 // We still need to report that delete was blocked 15548 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 15549 } 15550 } 15551 try { 15552 observer.onPackageDeleted(packageName, returnCode, null); 15553 } catch (RemoteException e) { 15554 Log.i(TAG, "Observer no longer exists."); 15555 } //end catch 15556 } //end run 15557 }); 15558 } 15559 15560 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 15561 int[] result = EMPTY_INT_ARRAY; 15562 for (int userId : userIds) { 15563 if (getBlockUninstallForUser(packageName, userId)) { 15564 result = ArrayUtils.appendInt(result, userId); 15565 } 15566 } 15567 return result; 15568 } 15569 15570 @Override 15571 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 15572 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 15573 } 15574 15575 private boolean isPackageDeviceAdmin(String packageName, int userId) { 15576 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 15577 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 15578 try { 15579 if (dpm != null) { 15580 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 15581 /* callingUserOnly =*/ false); 15582 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 15583 : deviceOwnerComponentName.getPackageName(); 15584 // Does the package contains the device owner? 15585 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 15586 // this check is probably not needed, since DO should be registered as a device 15587 // admin on some user too. (Original bug for this: b/17657954) 15588 if (packageName.equals(deviceOwnerPackageName)) { 15589 return true; 15590 } 15591 // Does it contain a device admin for any user? 15592 int[] users; 15593 if (userId == UserHandle.USER_ALL) { 15594 users = sUserManager.getUserIds(); 15595 } else { 15596 users = new int[]{userId}; 15597 } 15598 for (int i = 0; i < users.length; ++i) { 15599 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 15600 return true; 15601 } 15602 } 15603 } 15604 } catch (RemoteException e) { 15605 } 15606 return false; 15607 } 15608 15609 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 15610 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 15611 } 15612 15613 /** 15614 * This method is an internal method that could be get invoked either 15615 * to delete an installed package or to clean up a failed installation. 15616 * After deleting an installed package, a broadcast is sent to notify any 15617 * listeners that the package has been removed. For cleaning up a failed 15618 * installation, the broadcast is not necessary since the package's 15619 * installation wouldn't have sent the initial broadcast either 15620 * The key steps in deleting a package are 15621 * deleting the package information in internal structures like mPackages, 15622 * deleting the packages base directories through installd 15623 * updating mSettings to reflect current status 15624 * persisting settings for later use 15625 * sending a broadcast if necessary 15626 */ 15627 private int deletePackageX(String packageName, int userId, int deleteFlags) { 15628 final PackageRemovedInfo info = new PackageRemovedInfo(); 15629 final boolean res; 15630 15631 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 15632 ? UserHandle.USER_ALL : userId; 15633 15634 if (isPackageDeviceAdmin(packageName, removeUser)) { 15635 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 15636 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 15637 } 15638 15639 PackageSetting uninstalledPs = null; 15640 15641 // for the uninstall-updates case and restricted profiles, remember the per- 15642 // user handle installed state 15643 int[] allUsers; 15644 synchronized (mPackages) { 15645 uninstalledPs = mSettings.mPackages.get(packageName); 15646 if (uninstalledPs == null) { 15647 Slog.w(TAG, "Not removing non-existent package " + packageName); 15648 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15649 } 15650 allUsers = sUserManager.getUserIds(); 15651 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 15652 } 15653 15654 final int freezeUser; 15655 if (isUpdatedSystemApp(uninstalledPs) 15656 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) { 15657 // We're downgrading a system app, which will apply to all users, so 15658 // freeze them all during the downgrade 15659 freezeUser = UserHandle.USER_ALL; 15660 } else { 15661 freezeUser = removeUser; 15662 } 15663 15664 synchronized (mInstallLock) { 15665 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 15666 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser, 15667 deleteFlags, "deletePackageX")) { 15668 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers, 15669 deleteFlags | REMOVE_CHATTY, info, true, null); 15670 } 15671 synchronized (mPackages) { 15672 if (res) { 15673 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 15674 } 15675 } 15676 } 15677 15678 if (res) { 15679 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 15680 info.sendPackageRemovedBroadcasts(killApp); 15681 info.sendSystemPackageUpdatedBroadcasts(); 15682 info.sendSystemPackageAppearedBroadcasts(); 15683 } 15684 // Force a gc here. 15685 Runtime.getRuntime().gc(); 15686 // Delete the resources here after sending the broadcast to let 15687 // other processes clean up before deleting resources. 15688 if (info.args != null) { 15689 synchronized (mInstallLock) { 15690 info.args.doPostDeleteLI(true); 15691 } 15692 } 15693 15694 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15695 } 15696 15697 class PackageRemovedInfo { 15698 String removedPackage; 15699 int uid = -1; 15700 int removedAppId = -1; 15701 int[] origUsers; 15702 int[] removedUsers = null; 15703 boolean isRemovedPackageSystemUpdate = false; 15704 boolean isUpdate; 15705 boolean dataRemoved; 15706 boolean removedForAllUsers; 15707 // Clean up resources deleted packages. 15708 InstallArgs args = null; 15709 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 15710 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 15711 15712 void sendPackageRemovedBroadcasts(boolean killApp) { 15713 sendPackageRemovedBroadcastInternal(killApp); 15714 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 15715 for (int i = 0; i < childCount; i++) { 15716 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15717 childInfo.sendPackageRemovedBroadcastInternal(killApp); 15718 } 15719 } 15720 15721 void sendSystemPackageUpdatedBroadcasts() { 15722 if (isRemovedPackageSystemUpdate) { 15723 sendSystemPackageUpdatedBroadcastsInternal(); 15724 final int childCount = (removedChildPackages != null) 15725 ? removedChildPackages.size() : 0; 15726 for (int i = 0; i < childCount; i++) { 15727 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15728 if (childInfo.isRemovedPackageSystemUpdate) { 15729 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 15730 } 15731 } 15732 } 15733 } 15734 15735 void sendSystemPackageAppearedBroadcasts() { 15736 final int packageCount = (appearedChildPackages != null) 15737 ? appearedChildPackages.size() : 0; 15738 for (int i = 0; i < packageCount; i++) { 15739 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 15740 for (int userId : installedInfo.newUsers) { 15741 sendPackageAddedForUser(installedInfo.name, true, 15742 UserHandle.getAppId(installedInfo.uid), userId); 15743 } 15744 } 15745 } 15746 15747 private void sendSystemPackageUpdatedBroadcastsInternal() { 15748 Bundle extras = new Bundle(2); 15749 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15750 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15751 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 15752 extras, 0, null, null, null); 15753 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 15754 extras, 0, null, null, null); 15755 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 15756 null, 0, removedPackage, null, null); 15757 } 15758 15759 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 15760 Bundle extras = new Bundle(2); 15761 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15762 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 15763 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 15764 if (isUpdate || isRemovedPackageSystemUpdate) { 15765 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15766 } 15767 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 15768 if (removedPackage != null) { 15769 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 15770 extras, 0, null, null, removedUsers); 15771 if (dataRemoved && !isRemovedPackageSystemUpdate) { 15772 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 15773 removedPackage, extras, 0, null, null, removedUsers); 15774 } 15775 } 15776 if (removedAppId >= 0) { 15777 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 15778 removedUsers); 15779 } 15780 } 15781 } 15782 15783 /* 15784 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 15785 * flag is not set, the data directory is removed as well. 15786 * make sure this flag is set for partially installed apps. If not its meaningless to 15787 * delete a partially installed application. 15788 */ 15789 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 15790 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 15791 String packageName = ps.name; 15792 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 15793 // Retrieve object to delete permissions for shared user later on 15794 final PackageParser.Package deletedPkg; 15795 final PackageSetting deletedPs; 15796 // reader 15797 synchronized (mPackages) { 15798 deletedPkg = mPackages.get(packageName); 15799 deletedPs = mSettings.mPackages.get(packageName); 15800 if (outInfo != null) { 15801 outInfo.removedPackage = packageName; 15802 outInfo.removedUsers = deletedPs != null 15803 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 15804 : null; 15805 } 15806 } 15807 15808 removePackageLI(ps, (flags & REMOVE_CHATTY) != 0); 15809 15810 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 15811 final PackageParser.Package resolvedPkg; 15812 if (deletedPkg != null) { 15813 resolvedPkg = deletedPkg; 15814 } else { 15815 // We don't have a parsed package when it lives on an ejected 15816 // adopted storage device, so fake something together 15817 resolvedPkg = new PackageParser.Package(ps.name); 15818 resolvedPkg.setVolumeUuid(ps.volumeUuid); 15819 } 15820 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 15821 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15822 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 15823 if (outInfo != null) { 15824 outInfo.dataRemoved = true; 15825 } 15826 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 15827 } 15828 15829 // writer 15830 synchronized (mPackages) { 15831 if (deletedPs != null) { 15832 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 15833 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 15834 clearDefaultBrowserIfNeeded(packageName); 15835 if (outInfo != null) { 15836 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 15837 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 15838 } 15839 updatePermissionsLPw(deletedPs.name, null, 0); 15840 if (deletedPs.sharedUser != null) { 15841 // Remove permissions associated with package. Since runtime 15842 // permissions are per user we have to kill the removed package 15843 // or packages running under the shared user of the removed 15844 // package if revoking the permissions requested only by the removed 15845 // package is successful and this causes a change in gids. 15846 for (int userId : UserManagerService.getInstance().getUserIds()) { 15847 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 15848 userId); 15849 if (userIdToKill == UserHandle.USER_ALL 15850 || userIdToKill >= UserHandle.USER_SYSTEM) { 15851 // If gids changed for this user, kill all affected packages. 15852 mHandler.post(new Runnable() { 15853 @Override 15854 public void run() { 15855 // This has to happen with no lock held. 15856 killApplication(deletedPs.name, deletedPs.appId, 15857 KILL_APP_REASON_GIDS_CHANGED); 15858 } 15859 }); 15860 break; 15861 } 15862 } 15863 } 15864 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 15865 } 15866 // make sure to preserve per-user disabled state if this removal was just 15867 // a downgrade of a system app to the factory package 15868 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 15869 if (DEBUG_REMOVE) { 15870 Slog.d(TAG, "Propagating install state across downgrade"); 15871 } 15872 for (int userId : allUserHandles) { 15873 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15874 if (DEBUG_REMOVE) { 15875 Slog.d(TAG, " user " + userId + " => " + installed); 15876 } 15877 ps.setInstalled(installed, userId); 15878 } 15879 } 15880 } 15881 // can downgrade to reader 15882 if (writeSettings) { 15883 // Save settings now 15884 mSettings.writeLPr(); 15885 } 15886 } 15887 if (outInfo != null) { 15888 // A user ID was deleted here. Go through all users and remove it 15889 // from KeyStore. 15890 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 15891 } 15892 } 15893 15894 static boolean locationIsPrivileged(File path) { 15895 try { 15896 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 15897 .getCanonicalPath(); 15898 return path.getCanonicalPath().startsWith(privilegedAppDir); 15899 } catch (IOException e) { 15900 Slog.e(TAG, "Unable to access code path " + path); 15901 } 15902 return false; 15903 } 15904 15905 /* 15906 * Tries to delete system package. 15907 */ 15908 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 15909 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 15910 boolean writeSettings) { 15911 if (deletedPs.parentPackageName != null) { 15912 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 15913 return false; 15914 } 15915 15916 final boolean applyUserRestrictions 15917 = (allUserHandles != null) && (outInfo.origUsers != null); 15918 final PackageSetting disabledPs; 15919 // Confirm if the system package has been updated 15920 // An updated system app can be deleted. This will also have to restore 15921 // the system pkg from system partition 15922 // reader 15923 synchronized (mPackages) { 15924 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 15925 } 15926 15927 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 15928 + " disabledPs=" + disabledPs); 15929 15930 if (disabledPs == null) { 15931 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 15932 return false; 15933 } else if (DEBUG_REMOVE) { 15934 Slog.d(TAG, "Deleting system pkg from data partition"); 15935 } 15936 15937 if (DEBUG_REMOVE) { 15938 if (applyUserRestrictions) { 15939 Slog.d(TAG, "Remembering install states:"); 15940 for (int userId : allUserHandles) { 15941 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 15942 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 15943 } 15944 } 15945 } 15946 15947 // Delete the updated package 15948 outInfo.isRemovedPackageSystemUpdate = true; 15949 if (outInfo.removedChildPackages != null) { 15950 final int childCount = (deletedPs.childPackageNames != null) 15951 ? deletedPs.childPackageNames.size() : 0; 15952 for (int i = 0; i < childCount; i++) { 15953 String childPackageName = deletedPs.childPackageNames.get(i); 15954 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 15955 .contains(childPackageName)) { 15956 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15957 childPackageName); 15958 if (childInfo != null) { 15959 childInfo.isRemovedPackageSystemUpdate = true; 15960 } 15961 } 15962 } 15963 } 15964 15965 if (disabledPs.versionCode < deletedPs.versionCode) { 15966 // Delete data for downgrades 15967 flags &= ~PackageManager.DELETE_KEEP_DATA; 15968 } else { 15969 // Preserve data by setting flag 15970 flags |= PackageManager.DELETE_KEEP_DATA; 15971 } 15972 15973 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 15974 outInfo, writeSettings, disabledPs.pkg); 15975 if (!ret) { 15976 return false; 15977 } 15978 15979 // writer 15980 synchronized (mPackages) { 15981 // Reinstate the old system package 15982 enableSystemPackageLPw(disabledPs.pkg); 15983 // Remove any native libraries from the upgraded package. 15984 removeNativeBinariesLI(deletedPs); 15985 } 15986 15987 // Install the system package 15988 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 15989 int parseFlags = mDefParseFlags 15990 | PackageParser.PARSE_MUST_BE_APK 15991 | PackageParser.PARSE_IS_SYSTEM 15992 | PackageParser.PARSE_IS_SYSTEM_DIR; 15993 if (locationIsPrivileged(disabledPs.codePath)) { 15994 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 15995 } 15996 15997 final PackageParser.Package newPkg; 15998 try { 15999 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 16000 } catch (PackageManagerException e) { 16001 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 16002 + e.getMessage()); 16003 return false; 16004 } 16005 16006 prepareAppDataAfterInstallLIF(newPkg); 16007 16008 // writer 16009 synchronized (mPackages) { 16010 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 16011 16012 // Propagate the permissions state as we do not want to drop on the floor 16013 // runtime permissions. The update permissions method below will take 16014 // care of removing obsolete permissions and grant install permissions. 16015 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 16016 updatePermissionsLPw(newPkg.packageName, newPkg, 16017 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 16018 16019 if (applyUserRestrictions) { 16020 if (DEBUG_REMOVE) { 16021 Slog.d(TAG, "Propagating install state across reinstall"); 16022 } 16023 for (int userId : allUserHandles) { 16024 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 16025 if (DEBUG_REMOVE) { 16026 Slog.d(TAG, " user " + userId + " => " + installed); 16027 } 16028 ps.setInstalled(installed, userId); 16029 16030 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 16031 } 16032 // Regardless of writeSettings we need to ensure that this restriction 16033 // state propagation is persisted 16034 mSettings.writeAllUsersPackageRestrictionsLPr(); 16035 } 16036 // can downgrade to reader here 16037 if (writeSettings) { 16038 mSettings.writeLPr(); 16039 } 16040 } 16041 return true; 16042 } 16043 16044 private boolean deleteInstalledPackageLIF(PackageSetting ps, 16045 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 16046 PackageRemovedInfo outInfo, boolean writeSettings, 16047 PackageParser.Package replacingPackage) { 16048 synchronized (mPackages) { 16049 if (outInfo != null) { 16050 outInfo.uid = ps.appId; 16051 } 16052 16053 if (outInfo != null && outInfo.removedChildPackages != null) { 16054 final int childCount = (ps.childPackageNames != null) 16055 ? ps.childPackageNames.size() : 0; 16056 for (int i = 0; i < childCount; i++) { 16057 String childPackageName = ps.childPackageNames.get(i); 16058 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 16059 if (childPs == null) { 16060 return false; 16061 } 16062 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 16063 childPackageName); 16064 if (childInfo != null) { 16065 childInfo.uid = childPs.appId; 16066 } 16067 } 16068 } 16069 } 16070 16071 // Delete package data from internal structures and also remove data if flag is set 16072 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 16073 16074 // Delete the child packages data 16075 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 16076 for (int i = 0; i < childCount; i++) { 16077 PackageSetting childPs; 16078 synchronized (mPackages) { 16079 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 16080 } 16081 if (childPs != null) { 16082 PackageRemovedInfo childOutInfo = (outInfo != null 16083 && outInfo.removedChildPackages != null) 16084 ? outInfo.removedChildPackages.get(childPs.name) : null; 16085 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 16086 && (replacingPackage != null 16087 && !replacingPackage.hasChildPackage(childPs.name)) 16088 ? flags & ~DELETE_KEEP_DATA : flags; 16089 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 16090 deleteFlags, writeSettings); 16091 } 16092 } 16093 16094 // Delete application code and resources only for parent packages 16095 if (ps.parentPackageName == null) { 16096 if (deleteCodeAndResources && (outInfo != null)) { 16097 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 16098 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 16099 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 16100 } 16101 } 16102 16103 return true; 16104 } 16105 16106 @Override 16107 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 16108 int userId) { 16109 mContext.enforceCallingOrSelfPermission( 16110 android.Manifest.permission.DELETE_PACKAGES, null); 16111 synchronized (mPackages) { 16112 PackageSetting ps = mSettings.mPackages.get(packageName); 16113 if (ps == null) { 16114 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 16115 return false; 16116 } 16117 if (!ps.getInstalled(userId)) { 16118 // Can't block uninstall for an app that is not installed or enabled. 16119 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 16120 return false; 16121 } 16122 ps.setBlockUninstall(blockUninstall, userId); 16123 mSettings.writePackageRestrictionsLPr(userId); 16124 } 16125 return true; 16126 } 16127 16128 @Override 16129 public boolean getBlockUninstallForUser(String packageName, int userId) { 16130 synchronized (mPackages) { 16131 PackageSetting ps = mSettings.mPackages.get(packageName); 16132 if (ps == null) { 16133 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 16134 return false; 16135 } 16136 return ps.getBlockUninstall(userId); 16137 } 16138 } 16139 16140 @Override 16141 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 16142 int callingUid = Binder.getCallingUid(); 16143 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 16144 throw new SecurityException( 16145 "setRequiredForSystemUser can only be run by the system or root"); 16146 } 16147 synchronized (mPackages) { 16148 PackageSetting ps = mSettings.mPackages.get(packageName); 16149 if (ps == null) { 16150 Log.w(TAG, "Package doesn't exist: " + packageName); 16151 return false; 16152 } 16153 if (systemUserApp) { 16154 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 16155 } else { 16156 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 16157 } 16158 mSettings.writeLPr(); 16159 } 16160 return true; 16161 } 16162 16163 /* 16164 * This method handles package deletion in general 16165 */ 16166 private boolean deletePackageLIF(String packageName, UserHandle user, 16167 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 16168 PackageRemovedInfo outInfo, boolean writeSettings, 16169 PackageParser.Package replacingPackage) { 16170 if (packageName == null) { 16171 Slog.w(TAG, "Attempt to delete null packageName."); 16172 return false; 16173 } 16174 16175 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 16176 16177 PackageSetting ps; 16178 16179 synchronized (mPackages) { 16180 ps = mSettings.mPackages.get(packageName); 16181 if (ps == null) { 16182 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16183 return false; 16184 } 16185 16186 if (ps.parentPackageName != null && (!isSystemApp(ps) 16187 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 16188 if (DEBUG_REMOVE) { 16189 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 16190 + ((user == null) ? UserHandle.USER_ALL : user)); 16191 } 16192 final int removedUserId = (user != null) ? user.getIdentifier() 16193 : UserHandle.USER_ALL; 16194 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 16195 return false; 16196 } 16197 markPackageUninstalledForUserLPw(ps, user); 16198 scheduleWritePackageRestrictionsLocked(user); 16199 return true; 16200 } 16201 } 16202 16203 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 16204 && user.getIdentifier() != UserHandle.USER_ALL)) { 16205 // The caller is asking that the package only be deleted for a single 16206 // user. To do this, we just mark its uninstalled state and delete 16207 // its data. If this is a system app, we only allow this to happen if 16208 // they have set the special DELETE_SYSTEM_APP which requests different 16209 // semantics than normal for uninstalling system apps. 16210 markPackageUninstalledForUserLPw(ps, user); 16211 16212 if (!isSystemApp(ps)) { 16213 // Do not uninstall the APK if an app should be cached 16214 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 16215 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 16216 // Other user still have this package installed, so all 16217 // we need to do is clear this user's data and save that 16218 // it is uninstalled. 16219 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 16220 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16221 return false; 16222 } 16223 scheduleWritePackageRestrictionsLocked(user); 16224 return true; 16225 } else { 16226 // We need to set it back to 'installed' so the uninstall 16227 // broadcasts will be sent correctly. 16228 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 16229 ps.setInstalled(true, user.getIdentifier()); 16230 } 16231 } else { 16232 // This is a system app, so we assume that the 16233 // other users still have this package installed, so all 16234 // we need to do is clear this user's data and save that 16235 // it is uninstalled. 16236 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 16237 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16238 return false; 16239 } 16240 scheduleWritePackageRestrictionsLocked(user); 16241 return true; 16242 } 16243 } 16244 16245 // If we are deleting a composite package for all users, keep track 16246 // of result for each child. 16247 if (ps.childPackageNames != null && outInfo != null) { 16248 synchronized (mPackages) { 16249 final int childCount = ps.childPackageNames.size(); 16250 outInfo.removedChildPackages = new ArrayMap<>(childCount); 16251 for (int i = 0; i < childCount; i++) { 16252 String childPackageName = ps.childPackageNames.get(i); 16253 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 16254 childInfo.removedPackage = childPackageName; 16255 outInfo.removedChildPackages.put(childPackageName, childInfo); 16256 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 16257 if (childPs != null) { 16258 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 16259 } 16260 } 16261 } 16262 } 16263 16264 boolean ret = false; 16265 if (isSystemApp(ps)) { 16266 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 16267 // When an updated system application is deleted we delete the existing resources 16268 // as well and fall back to existing code in system partition 16269 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 16270 } else { 16271 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 16272 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 16273 outInfo, writeSettings, replacingPackage); 16274 } 16275 16276 // Take a note whether we deleted the package for all users 16277 if (outInfo != null) { 16278 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 16279 if (outInfo.removedChildPackages != null) { 16280 synchronized (mPackages) { 16281 final int childCount = outInfo.removedChildPackages.size(); 16282 for (int i = 0; i < childCount; i++) { 16283 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 16284 if (childInfo != null) { 16285 childInfo.removedForAllUsers = mPackages.get( 16286 childInfo.removedPackage) == null; 16287 } 16288 } 16289 } 16290 } 16291 // If we uninstalled an update to a system app there may be some 16292 // child packages that appeared as they are declared in the system 16293 // app but were not declared in the update. 16294 if (isSystemApp(ps)) { 16295 synchronized (mPackages) { 16296 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 16297 final int childCount = (updatedPs.childPackageNames != null) 16298 ? updatedPs.childPackageNames.size() : 0; 16299 for (int i = 0; i < childCount; i++) { 16300 String childPackageName = updatedPs.childPackageNames.get(i); 16301 if (outInfo.removedChildPackages == null 16302 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 16303 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 16304 if (childPs == null) { 16305 continue; 16306 } 16307 PackageInstalledInfo installRes = new PackageInstalledInfo(); 16308 installRes.name = childPackageName; 16309 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 16310 installRes.pkg = mPackages.get(childPackageName); 16311 installRes.uid = childPs.pkg.applicationInfo.uid; 16312 if (outInfo.appearedChildPackages == null) { 16313 outInfo.appearedChildPackages = new ArrayMap<>(); 16314 } 16315 outInfo.appearedChildPackages.put(childPackageName, installRes); 16316 } 16317 } 16318 } 16319 } 16320 } 16321 16322 return ret; 16323 } 16324 16325 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 16326 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 16327 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 16328 for (int nextUserId : userIds) { 16329 if (DEBUG_REMOVE) { 16330 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 16331 } 16332 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 16333 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 16334 false /*hidden*/, false /*suspended*/, null, null, null, 16335 false /*blockUninstall*/, 16336 ps.readUserState(nextUserId).domainVerificationStatus, 0); 16337 } 16338 } 16339 16340 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 16341 PackageRemovedInfo outInfo) { 16342 final PackageParser.Package pkg; 16343 synchronized (mPackages) { 16344 pkg = mPackages.get(ps.name); 16345 } 16346 16347 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 16348 : new int[] {userId}; 16349 for (int nextUserId : userIds) { 16350 if (DEBUG_REMOVE) { 16351 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 16352 + nextUserId); 16353 } 16354 16355 destroyAppDataLIF(pkg, userId, 16356 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16357 destroyAppProfilesLIF(pkg, userId); 16358 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 16359 schedulePackageCleaning(ps.name, nextUserId, false); 16360 synchronized (mPackages) { 16361 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 16362 scheduleWritePackageRestrictionsLocked(nextUserId); 16363 } 16364 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 16365 } 16366 } 16367 16368 if (outInfo != null) { 16369 outInfo.removedPackage = ps.name; 16370 outInfo.removedAppId = ps.appId; 16371 outInfo.removedUsers = userIds; 16372 } 16373 16374 return true; 16375 } 16376 16377 private final class ClearStorageConnection implements ServiceConnection { 16378 IMediaContainerService mContainerService; 16379 16380 @Override 16381 public void onServiceConnected(ComponentName name, IBinder service) { 16382 synchronized (this) { 16383 mContainerService = IMediaContainerService.Stub.asInterface(service); 16384 notifyAll(); 16385 } 16386 } 16387 16388 @Override 16389 public void onServiceDisconnected(ComponentName name) { 16390 } 16391 } 16392 16393 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 16394 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 16395 16396 final boolean mounted; 16397 if (Environment.isExternalStorageEmulated()) { 16398 mounted = true; 16399 } else { 16400 final String status = Environment.getExternalStorageState(); 16401 16402 mounted = status.equals(Environment.MEDIA_MOUNTED) 16403 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 16404 } 16405 16406 if (!mounted) { 16407 return; 16408 } 16409 16410 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 16411 int[] users; 16412 if (userId == UserHandle.USER_ALL) { 16413 users = sUserManager.getUserIds(); 16414 } else { 16415 users = new int[] { userId }; 16416 } 16417 final ClearStorageConnection conn = new ClearStorageConnection(); 16418 if (mContext.bindServiceAsUser( 16419 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 16420 try { 16421 for (int curUser : users) { 16422 long timeout = SystemClock.uptimeMillis() + 5000; 16423 synchronized (conn) { 16424 long now; 16425 while (conn.mContainerService == null && 16426 (now = SystemClock.uptimeMillis()) < timeout) { 16427 try { 16428 conn.wait(timeout - now); 16429 } catch (InterruptedException e) { 16430 } 16431 } 16432 } 16433 if (conn.mContainerService == null) { 16434 return; 16435 } 16436 16437 final UserEnvironment userEnv = new UserEnvironment(curUser); 16438 clearDirectory(conn.mContainerService, 16439 userEnv.buildExternalStorageAppCacheDirs(packageName)); 16440 if (allData) { 16441 clearDirectory(conn.mContainerService, 16442 userEnv.buildExternalStorageAppDataDirs(packageName)); 16443 clearDirectory(conn.mContainerService, 16444 userEnv.buildExternalStorageAppMediaDirs(packageName)); 16445 } 16446 } 16447 } finally { 16448 mContext.unbindService(conn); 16449 } 16450 } 16451 } 16452 16453 @Override 16454 public void clearApplicationProfileData(String packageName) { 16455 enforceSystemOrRoot("Only the system can clear all profile data"); 16456 16457 final PackageParser.Package pkg; 16458 synchronized (mPackages) { 16459 pkg = mPackages.get(packageName); 16460 } 16461 16462 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 16463 synchronized (mInstallLock) { 16464 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 16465 destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL, 16466 true /* removeBaseMarker */); 16467 } 16468 } 16469 } 16470 16471 @Override 16472 public void clearApplicationUserData(final String packageName, 16473 final IPackageDataObserver observer, final int userId) { 16474 mContext.enforceCallingOrSelfPermission( 16475 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 16476 16477 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16478 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 16479 16480 if (mProtectedPackages.isPackageDataProtected(userId, packageName)) { 16481 throw new SecurityException("Cannot clear data for a protected package: " 16482 + packageName); 16483 } 16484 // Queue up an async operation since the package deletion may take a little while. 16485 mHandler.post(new Runnable() { 16486 public void run() { 16487 mHandler.removeCallbacks(this); 16488 final boolean succeeded; 16489 try (PackageFreezer freezer = freezePackage(packageName, 16490 "clearApplicationUserData")) { 16491 synchronized (mInstallLock) { 16492 succeeded = clearApplicationUserDataLIF(packageName, userId); 16493 } 16494 clearExternalStorageDataSync(packageName, userId, true); 16495 } 16496 if (succeeded) { 16497 // invoke DeviceStorageMonitor's update method to clear any notifications 16498 DeviceStorageMonitorInternal dsm = LocalServices 16499 .getService(DeviceStorageMonitorInternal.class); 16500 if (dsm != null) { 16501 dsm.checkMemory(); 16502 } 16503 } 16504 if(observer != null) { 16505 try { 16506 observer.onRemoveCompleted(packageName, succeeded); 16507 } catch (RemoteException e) { 16508 Log.i(TAG, "Observer no longer exists."); 16509 } 16510 } //end if observer 16511 } //end run 16512 }); 16513 } 16514 16515 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 16516 if (packageName == null) { 16517 Slog.w(TAG, "Attempt to delete null packageName."); 16518 return false; 16519 } 16520 16521 // Try finding details about the requested package 16522 PackageParser.Package pkg; 16523 synchronized (mPackages) { 16524 pkg = mPackages.get(packageName); 16525 if (pkg == null) { 16526 final PackageSetting ps = mSettings.mPackages.get(packageName); 16527 if (ps != null) { 16528 pkg = ps.pkg; 16529 } 16530 } 16531 16532 if (pkg == null) { 16533 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16534 return false; 16535 } 16536 16537 PackageSetting ps = (PackageSetting) pkg.mExtras; 16538 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16539 } 16540 16541 clearAppDataLIF(pkg, userId, 16542 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16543 16544 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16545 removeKeystoreDataIfNeeded(userId, appId); 16546 16547 UserManagerInternal umInternal = getUserManagerInternal(); 16548 final int flags; 16549 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 16550 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 16551 } else if (umInternal.isUserRunning(userId)) { 16552 flags = StorageManager.FLAG_STORAGE_DE; 16553 } else { 16554 flags = 0; 16555 } 16556 prepareAppDataContentsLIF(pkg, userId, flags); 16557 16558 return true; 16559 } 16560 16561 /** 16562 * Reverts user permission state changes (permissions and flags) in 16563 * all packages for a given user. 16564 * 16565 * @param userId The device user for which to do a reset. 16566 */ 16567 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 16568 final int packageCount = mPackages.size(); 16569 for (int i = 0; i < packageCount; i++) { 16570 PackageParser.Package pkg = mPackages.valueAt(i); 16571 PackageSetting ps = (PackageSetting) pkg.mExtras; 16572 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16573 } 16574 } 16575 16576 private void resetNetworkPolicies(int userId) { 16577 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 16578 } 16579 16580 /** 16581 * Reverts user permission state changes (permissions and flags). 16582 * 16583 * @param ps The package for which to reset. 16584 * @param userId The device user for which to do a reset. 16585 */ 16586 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 16587 final PackageSetting ps, final int userId) { 16588 if (ps.pkg == null) { 16589 return; 16590 } 16591 16592 // These are flags that can change base on user actions. 16593 final int userSettableMask = FLAG_PERMISSION_USER_SET 16594 | FLAG_PERMISSION_USER_FIXED 16595 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 16596 | FLAG_PERMISSION_REVIEW_REQUIRED; 16597 16598 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 16599 | FLAG_PERMISSION_POLICY_FIXED; 16600 16601 boolean writeInstallPermissions = false; 16602 boolean writeRuntimePermissions = false; 16603 16604 final int permissionCount = ps.pkg.requestedPermissions.size(); 16605 for (int i = 0; i < permissionCount; i++) { 16606 String permission = ps.pkg.requestedPermissions.get(i); 16607 16608 BasePermission bp = mSettings.mPermissions.get(permission); 16609 if (bp == null) { 16610 continue; 16611 } 16612 16613 // If shared user we just reset the state to which only this app contributed. 16614 if (ps.sharedUser != null) { 16615 boolean used = false; 16616 final int packageCount = ps.sharedUser.packages.size(); 16617 for (int j = 0; j < packageCount; j++) { 16618 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 16619 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 16620 && pkg.pkg.requestedPermissions.contains(permission)) { 16621 used = true; 16622 break; 16623 } 16624 } 16625 if (used) { 16626 continue; 16627 } 16628 } 16629 16630 PermissionsState permissionsState = ps.getPermissionsState(); 16631 16632 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 16633 16634 // Always clear the user settable flags. 16635 final boolean hasInstallState = permissionsState.getInstallPermissionState( 16636 bp.name) != null; 16637 // If permission review is enabled and this is a legacy app, mark the 16638 // permission as requiring a review as this is the initial state. 16639 int flags = 0; 16640 if (Build.PERMISSIONS_REVIEW_REQUIRED 16641 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 16642 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 16643 } 16644 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 16645 if (hasInstallState) { 16646 writeInstallPermissions = true; 16647 } else { 16648 writeRuntimePermissions = true; 16649 } 16650 } 16651 16652 // Below is only runtime permission handling. 16653 if (!bp.isRuntime()) { 16654 continue; 16655 } 16656 16657 // Never clobber system or policy. 16658 if ((oldFlags & policyOrSystemFlags) != 0) { 16659 continue; 16660 } 16661 16662 // If this permission was granted by default, make sure it is. 16663 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 16664 if (permissionsState.grantRuntimePermission(bp, userId) 16665 != PERMISSION_OPERATION_FAILURE) { 16666 writeRuntimePermissions = true; 16667 } 16668 // If permission review is enabled the permissions for a legacy apps 16669 // are represented as constantly granted runtime ones, so don't revoke. 16670 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 16671 // Otherwise, reset the permission. 16672 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 16673 switch (revokeResult) { 16674 case PERMISSION_OPERATION_SUCCESS: 16675 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 16676 writeRuntimePermissions = true; 16677 final int appId = ps.appId; 16678 mHandler.post(new Runnable() { 16679 @Override 16680 public void run() { 16681 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 16682 } 16683 }); 16684 } break; 16685 } 16686 } 16687 } 16688 16689 // Synchronously write as we are taking permissions away. 16690 if (writeRuntimePermissions) { 16691 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 16692 } 16693 16694 // Synchronously write as we are taking permissions away. 16695 if (writeInstallPermissions) { 16696 mSettings.writeLPr(); 16697 } 16698 } 16699 16700 /** 16701 * Remove entries from the keystore daemon. Will only remove it if the 16702 * {@code appId} is valid. 16703 */ 16704 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 16705 if (appId < 0) { 16706 return; 16707 } 16708 16709 final KeyStore keyStore = KeyStore.getInstance(); 16710 if (keyStore != null) { 16711 if (userId == UserHandle.USER_ALL) { 16712 for (final int individual : sUserManager.getUserIds()) { 16713 keyStore.clearUid(UserHandle.getUid(individual, appId)); 16714 } 16715 } else { 16716 keyStore.clearUid(UserHandle.getUid(userId, appId)); 16717 } 16718 } else { 16719 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 16720 } 16721 } 16722 16723 @Override 16724 public void deleteApplicationCacheFiles(final String packageName, 16725 final IPackageDataObserver observer) { 16726 final int userId = UserHandle.getCallingUserId(); 16727 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 16728 } 16729 16730 @Override 16731 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 16732 final IPackageDataObserver observer) { 16733 mContext.enforceCallingOrSelfPermission( 16734 android.Manifest.permission.DELETE_CACHE_FILES, null); 16735 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16736 /* requireFullPermission= */ true, /* checkShell= */ false, 16737 "delete application cache files"); 16738 16739 final PackageParser.Package pkg; 16740 synchronized (mPackages) { 16741 pkg = mPackages.get(packageName); 16742 } 16743 16744 // Queue up an async operation since the package deletion may take a little while. 16745 mHandler.post(new Runnable() { 16746 public void run() { 16747 synchronized (mInstallLock) { 16748 final int flags = StorageManager.FLAG_STORAGE_DE 16749 | StorageManager.FLAG_STORAGE_CE; 16750 // We're only clearing cache files, so we don't care if the 16751 // app is unfrozen and still able to run 16752 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 16753 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16754 } 16755 clearExternalStorageDataSync(packageName, userId, false); 16756 if (observer != null) { 16757 try { 16758 observer.onRemoveCompleted(packageName, true); 16759 } catch (RemoteException e) { 16760 Log.i(TAG, "Observer no longer exists."); 16761 } 16762 } 16763 } 16764 }); 16765 } 16766 16767 @Override 16768 public void getPackageSizeInfo(final String packageName, int userHandle, 16769 final IPackageStatsObserver observer) { 16770 mContext.enforceCallingOrSelfPermission( 16771 android.Manifest.permission.GET_PACKAGE_SIZE, null); 16772 if (packageName == null) { 16773 throw new IllegalArgumentException("Attempt to get size of null packageName"); 16774 } 16775 16776 PackageStats stats = new PackageStats(packageName, userHandle); 16777 16778 /* 16779 * Queue up an async operation since the package measurement may take a 16780 * little while. 16781 */ 16782 Message msg = mHandler.obtainMessage(INIT_COPY); 16783 msg.obj = new MeasureParams(stats, observer); 16784 mHandler.sendMessage(msg); 16785 } 16786 16787 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 16788 final PackageSetting ps; 16789 synchronized (mPackages) { 16790 ps = mSettings.mPackages.get(packageName); 16791 if (ps == null) { 16792 Slog.w(TAG, "Failed to find settings for " + packageName); 16793 return false; 16794 } 16795 } 16796 try { 16797 mInstaller.getAppSize(ps.volumeUuid, packageName, userId, 16798 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 16799 ps.getCeDataInode(userId), ps.codePathString, stats); 16800 } catch (InstallerException e) { 16801 Slog.w(TAG, String.valueOf(e)); 16802 return false; 16803 } 16804 16805 // For now, ignore code size of packages on system partition 16806 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 16807 stats.codeSize = 0; 16808 } 16809 16810 return true; 16811 } 16812 16813 private int getUidTargetSdkVersionLockedLPr(int uid) { 16814 Object obj = mSettings.getUserIdLPr(uid); 16815 if (obj instanceof SharedUserSetting) { 16816 final SharedUserSetting sus = (SharedUserSetting) obj; 16817 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 16818 final Iterator<PackageSetting> it = sus.packages.iterator(); 16819 while (it.hasNext()) { 16820 final PackageSetting ps = it.next(); 16821 if (ps.pkg != null) { 16822 int v = ps.pkg.applicationInfo.targetSdkVersion; 16823 if (v < vers) vers = v; 16824 } 16825 } 16826 return vers; 16827 } else if (obj instanceof PackageSetting) { 16828 final PackageSetting ps = (PackageSetting) obj; 16829 if (ps.pkg != null) { 16830 return ps.pkg.applicationInfo.targetSdkVersion; 16831 } 16832 } 16833 return Build.VERSION_CODES.CUR_DEVELOPMENT; 16834 } 16835 16836 @Override 16837 public void addPreferredActivity(IntentFilter filter, int match, 16838 ComponentName[] set, ComponentName activity, int userId) { 16839 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16840 "Adding preferred"); 16841 } 16842 16843 private void addPreferredActivityInternal(IntentFilter filter, int match, 16844 ComponentName[] set, ComponentName activity, boolean always, int userId, 16845 String opname) { 16846 // writer 16847 int callingUid = Binder.getCallingUid(); 16848 enforceCrossUserPermission(callingUid, userId, 16849 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 16850 if (filter.countActions() == 0) { 16851 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16852 return; 16853 } 16854 synchronized (mPackages) { 16855 if (mContext.checkCallingOrSelfPermission( 16856 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16857 != PackageManager.PERMISSION_GRANTED) { 16858 if (getUidTargetSdkVersionLockedLPr(callingUid) 16859 < Build.VERSION_CODES.FROYO) { 16860 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 16861 + callingUid); 16862 return; 16863 } 16864 mContext.enforceCallingOrSelfPermission( 16865 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16866 } 16867 16868 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 16869 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 16870 + userId + ":"); 16871 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16872 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 16873 scheduleWritePackageRestrictionsLocked(userId); 16874 } 16875 } 16876 16877 @Override 16878 public void replacePreferredActivity(IntentFilter filter, int match, 16879 ComponentName[] set, ComponentName activity, int userId) { 16880 if (filter.countActions() != 1) { 16881 throw new IllegalArgumentException( 16882 "replacePreferredActivity expects filter to have only 1 action."); 16883 } 16884 if (filter.countDataAuthorities() != 0 16885 || filter.countDataPaths() != 0 16886 || filter.countDataSchemes() > 1 16887 || filter.countDataTypes() != 0) { 16888 throw new IllegalArgumentException( 16889 "replacePreferredActivity expects filter to have no data authorities, " + 16890 "paths, or types; and at most one scheme."); 16891 } 16892 16893 final int callingUid = Binder.getCallingUid(); 16894 enforceCrossUserPermission(callingUid, userId, 16895 true /* requireFullPermission */, false /* checkShell */, 16896 "replace preferred activity"); 16897 synchronized (mPackages) { 16898 if (mContext.checkCallingOrSelfPermission( 16899 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16900 != PackageManager.PERMISSION_GRANTED) { 16901 if (getUidTargetSdkVersionLockedLPr(callingUid) 16902 < Build.VERSION_CODES.FROYO) { 16903 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 16904 + Binder.getCallingUid()); 16905 return; 16906 } 16907 mContext.enforceCallingOrSelfPermission( 16908 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16909 } 16910 16911 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16912 if (pir != null) { 16913 // Get all of the existing entries that exactly match this filter. 16914 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 16915 if (existing != null && existing.size() == 1) { 16916 PreferredActivity cur = existing.get(0); 16917 if (DEBUG_PREFERRED) { 16918 Slog.i(TAG, "Checking replace of preferred:"); 16919 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16920 if (!cur.mPref.mAlways) { 16921 Slog.i(TAG, " -- CUR; not mAlways!"); 16922 } else { 16923 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 16924 Slog.i(TAG, " -- CUR: mSet=" 16925 + Arrays.toString(cur.mPref.mSetComponents)); 16926 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 16927 Slog.i(TAG, " -- NEW: mMatch=" 16928 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 16929 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 16930 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 16931 } 16932 } 16933 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 16934 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 16935 && cur.mPref.sameSet(set)) { 16936 // Setting the preferred activity to what it happens to be already 16937 if (DEBUG_PREFERRED) { 16938 Slog.i(TAG, "Replacing with same preferred activity " 16939 + cur.mPref.mShortComponent + " for user " 16940 + userId + ":"); 16941 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16942 } 16943 return; 16944 } 16945 } 16946 16947 if (existing != null) { 16948 if (DEBUG_PREFERRED) { 16949 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 16950 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16951 } 16952 for (int i = 0; i < existing.size(); i++) { 16953 PreferredActivity pa = existing.get(i); 16954 if (DEBUG_PREFERRED) { 16955 Slog.i(TAG, "Removing existing preferred activity " 16956 + pa.mPref.mComponent + ":"); 16957 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 16958 } 16959 pir.removeFilter(pa); 16960 } 16961 } 16962 } 16963 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16964 "Replacing preferred"); 16965 } 16966 } 16967 16968 @Override 16969 public void clearPackagePreferredActivities(String packageName) { 16970 final int uid = Binder.getCallingUid(); 16971 // writer 16972 synchronized (mPackages) { 16973 PackageParser.Package pkg = mPackages.get(packageName); 16974 if (pkg == null || pkg.applicationInfo.uid != uid) { 16975 if (mContext.checkCallingOrSelfPermission( 16976 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16977 != PackageManager.PERMISSION_GRANTED) { 16978 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 16979 < Build.VERSION_CODES.FROYO) { 16980 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 16981 + Binder.getCallingUid()); 16982 return; 16983 } 16984 mContext.enforceCallingOrSelfPermission( 16985 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16986 } 16987 } 16988 16989 int user = UserHandle.getCallingUserId(); 16990 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 16991 scheduleWritePackageRestrictionsLocked(user); 16992 } 16993 } 16994 } 16995 16996 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16997 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 16998 ArrayList<PreferredActivity> removed = null; 16999 boolean changed = false; 17000 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17001 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 17002 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17003 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 17004 continue; 17005 } 17006 Iterator<PreferredActivity> it = pir.filterIterator(); 17007 while (it.hasNext()) { 17008 PreferredActivity pa = it.next(); 17009 // Mark entry for removal only if it matches the package name 17010 // and the entry is of type "always". 17011 if (packageName == null || 17012 (pa.mPref.mComponent.getPackageName().equals(packageName) 17013 && pa.mPref.mAlways)) { 17014 if (removed == null) { 17015 removed = new ArrayList<PreferredActivity>(); 17016 } 17017 removed.add(pa); 17018 } 17019 } 17020 if (removed != null) { 17021 for (int j=0; j<removed.size(); j++) { 17022 PreferredActivity pa = removed.get(j); 17023 pir.removeFilter(pa); 17024 } 17025 changed = true; 17026 } 17027 } 17028 return changed; 17029 } 17030 17031 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 17032 private void clearIntentFilterVerificationsLPw(int userId) { 17033 final int packageCount = mPackages.size(); 17034 for (int i = 0; i < packageCount; i++) { 17035 PackageParser.Package pkg = mPackages.valueAt(i); 17036 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 17037 } 17038 } 17039 17040 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 17041 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 17042 if (userId == UserHandle.USER_ALL) { 17043 if (mSettings.removeIntentFilterVerificationLPw(packageName, 17044 sUserManager.getUserIds())) { 17045 for (int oneUserId : sUserManager.getUserIds()) { 17046 scheduleWritePackageRestrictionsLocked(oneUserId); 17047 } 17048 } 17049 } else { 17050 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 17051 scheduleWritePackageRestrictionsLocked(userId); 17052 } 17053 } 17054 } 17055 17056 void clearDefaultBrowserIfNeeded(String packageName) { 17057 for (int oneUserId : sUserManager.getUserIds()) { 17058 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 17059 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 17060 if (packageName.equals(defaultBrowserPackageName)) { 17061 setDefaultBrowserPackageName(null, oneUserId); 17062 } 17063 } 17064 } 17065 17066 @Override 17067 public void resetApplicationPreferences(int userId) { 17068 mContext.enforceCallingOrSelfPermission( 17069 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17070 final long identity = Binder.clearCallingIdentity(); 17071 // writer 17072 try { 17073 synchronized (mPackages) { 17074 clearPackagePreferredActivitiesLPw(null, userId); 17075 mSettings.applyDefaultPreferredAppsLPw(this, userId); 17076 // TODO: We have to reset the default SMS and Phone. This requires 17077 // significant refactoring to keep all default apps in the package 17078 // manager (cleaner but more work) or have the services provide 17079 // callbacks to the package manager to request a default app reset. 17080 applyFactoryDefaultBrowserLPw(userId); 17081 clearIntentFilterVerificationsLPw(userId); 17082 primeDomainVerificationsLPw(userId); 17083 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 17084 scheduleWritePackageRestrictionsLocked(userId); 17085 } 17086 resetNetworkPolicies(userId); 17087 } finally { 17088 Binder.restoreCallingIdentity(identity); 17089 } 17090 } 17091 17092 @Override 17093 public int getPreferredActivities(List<IntentFilter> outFilters, 17094 List<ComponentName> outActivities, String packageName) { 17095 17096 int num = 0; 17097 final int userId = UserHandle.getCallingUserId(); 17098 // reader 17099 synchronized (mPackages) { 17100 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 17101 if (pir != null) { 17102 final Iterator<PreferredActivity> it = pir.filterIterator(); 17103 while (it.hasNext()) { 17104 final PreferredActivity pa = it.next(); 17105 if (packageName == null 17106 || (pa.mPref.mComponent.getPackageName().equals(packageName) 17107 && pa.mPref.mAlways)) { 17108 if (outFilters != null) { 17109 outFilters.add(new IntentFilter(pa)); 17110 } 17111 if (outActivities != null) { 17112 outActivities.add(pa.mPref.mComponent); 17113 } 17114 } 17115 } 17116 } 17117 } 17118 17119 return num; 17120 } 17121 17122 @Override 17123 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 17124 int userId) { 17125 int callingUid = Binder.getCallingUid(); 17126 if (callingUid != Process.SYSTEM_UID) { 17127 throw new SecurityException( 17128 "addPersistentPreferredActivity can only be run by the system"); 17129 } 17130 if (filter.countActions() == 0) { 17131 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 17132 return; 17133 } 17134 synchronized (mPackages) { 17135 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 17136 ":"); 17137 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17138 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 17139 new PersistentPreferredActivity(filter, activity)); 17140 scheduleWritePackageRestrictionsLocked(userId); 17141 } 17142 } 17143 17144 @Override 17145 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 17146 int callingUid = Binder.getCallingUid(); 17147 if (callingUid != Process.SYSTEM_UID) { 17148 throw new SecurityException( 17149 "clearPackagePersistentPreferredActivities can only be run by the system"); 17150 } 17151 ArrayList<PersistentPreferredActivity> removed = null; 17152 boolean changed = false; 17153 synchronized (mPackages) { 17154 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 17155 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 17156 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 17157 .valueAt(i); 17158 if (userId != thisUserId) { 17159 continue; 17160 } 17161 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 17162 while (it.hasNext()) { 17163 PersistentPreferredActivity ppa = it.next(); 17164 // Mark entry for removal only if it matches the package name. 17165 if (ppa.mComponent.getPackageName().equals(packageName)) { 17166 if (removed == null) { 17167 removed = new ArrayList<PersistentPreferredActivity>(); 17168 } 17169 removed.add(ppa); 17170 } 17171 } 17172 if (removed != null) { 17173 for (int j=0; j<removed.size(); j++) { 17174 PersistentPreferredActivity ppa = removed.get(j); 17175 ppir.removeFilter(ppa); 17176 } 17177 changed = true; 17178 } 17179 } 17180 17181 if (changed) { 17182 scheduleWritePackageRestrictionsLocked(userId); 17183 } 17184 } 17185 } 17186 17187 /** 17188 * Common machinery for picking apart a restored XML blob and passing 17189 * it to a caller-supplied functor to be applied to the running system. 17190 */ 17191 private void restoreFromXml(XmlPullParser parser, int userId, 17192 String expectedStartTag, BlobXmlRestorer functor) 17193 throws IOException, XmlPullParserException { 17194 int type; 17195 while ((type = parser.next()) != XmlPullParser.START_TAG 17196 && type != XmlPullParser.END_DOCUMENT) { 17197 } 17198 if (type != XmlPullParser.START_TAG) { 17199 // oops didn't find a start tag?! 17200 if (DEBUG_BACKUP) { 17201 Slog.e(TAG, "Didn't find start tag during restore"); 17202 } 17203 return; 17204 } 17205Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 17206 // this is supposed to be TAG_PREFERRED_BACKUP 17207 if (!expectedStartTag.equals(parser.getName())) { 17208 if (DEBUG_BACKUP) { 17209 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 17210 } 17211 return; 17212 } 17213 17214 // skip interfering stuff, then we're aligned with the backing implementation 17215 while ((type = parser.next()) == XmlPullParser.TEXT) { } 17216Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 17217 functor.apply(parser, userId); 17218 } 17219 17220 private interface BlobXmlRestorer { 17221 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 17222 } 17223 17224 /** 17225 * Non-Binder method, support for the backup/restore mechanism: write the 17226 * full set of preferred activities in its canonical XML format. Returns the 17227 * XML output as a byte array, or null if there is none. 17228 */ 17229 @Override 17230 public byte[] getPreferredActivityBackup(int userId) { 17231 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17232 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 17233 } 17234 17235 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17236 try { 17237 final XmlSerializer serializer = new FastXmlSerializer(); 17238 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17239 serializer.startDocument(null, true); 17240 serializer.startTag(null, TAG_PREFERRED_BACKUP); 17241 17242 synchronized (mPackages) { 17243 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 17244 } 17245 17246 serializer.endTag(null, TAG_PREFERRED_BACKUP); 17247 serializer.endDocument(); 17248 serializer.flush(); 17249 } catch (Exception e) { 17250 if (DEBUG_BACKUP) { 17251 Slog.e(TAG, "Unable to write preferred activities for backup", e); 17252 } 17253 return null; 17254 } 17255 17256 return dataStream.toByteArray(); 17257 } 17258 17259 @Override 17260 public void restorePreferredActivities(byte[] backup, int userId) { 17261 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17262 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17263 } 17264 17265 try { 17266 final XmlPullParser parser = Xml.newPullParser(); 17267 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17268 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 17269 new BlobXmlRestorer() { 17270 @Override 17271 public void apply(XmlPullParser parser, int userId) 17272 throws XmlPullParserException, IOException { 17273 synchronized (mPackages) { 17274 mSettings.readPreferredActivitiesLPw(parser, userId); 17275 } 17276 } 17277 } ); 17278 } catch (Exception e) { 17279 if (DEBUG_BACKUP) { 17280 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17281 } 17282 } 17283 } 17284 17285 /** 17286 * Non-Binder method, support for the backup/restore mechanism: write the 17287 * default browser (etc) settings in its canonical XML format. Returns the default 17288 * browser XML representation as a byte array, or null if there is none. 17289 */ 17290 @Override 17291 public byte[] getDefaultAppsBackup(int userId) { 17292 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17293 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 17294 } 17295 17296 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17297 try { 17298 final XmlSerializer serializer = new FastXmlSerializer(); 17299 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17300 serializer.startDocument(null, true); 17301 serializer.startTag(null, TAG_DEFAULT_APPS); 17302 17303 synchronized (mPackages) { 17304 mSettings.writeDefaultAppsLPr(serializer, userId); 17305 } 17306 17307 serializer.endTag(null, TAG_DEFAULT_APPS); 17308 serializer.endDocument(); 17309 serializer.flush(); 17310 } catch (Exception e) { 17311 if (DEBUG_BACKUP) { 17312 Slog.e(TAG, "Unable to write default apps for backup", e); 17313 } 17314 return null; 17315 } 17316 17317 return dataStream.toByteArray(); 17318 } 17319 17320 @Override 17321 public void restoreDefaultApps(byte[] backup, int userId) { 17322 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17323 throw new SecurityException("Only the system may call restoreDefaultApps()"); 17324 } 17325 17326 try { 17327 final XmlPullParser parser = Xml.newPullParser(); 17328 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17329 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 17330 new BlobXmlRestorer() { 17331 @Override 17332 public void apply(XmlPullParser parser, int userId) 17333 throws XmlPullParserException, IOException { 17334 synchronized (mPackages) { 17335 mSettings.readDefaultAppsLPw(parser, userId); 17336 } 17337 } 17338 } ); 17339 } catch (Exception e) { 17340 if (DEBUG_BACKUP) { 17341 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 17342 } 17343 } 17344 } 17345 17346 @Override 17347 public byte[] getIntentFilterVerificationBackup(int userId) { 17348 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17349 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 17350 } 17351 17352 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17353 try { 17354 final XmlSerializer serializer = new FastXmlSerializer(); 17355 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17356 serializer.startDocument(null, true); 17357 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 17358 17359 synchronized (mPackages) { 17360 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 17361 } 17362 17363 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 17364 serializer.endDocument(); 17365 serializer.flush(); 17366 } catch (Exception e) { 17367 if (DEBUG_BACKUP) { 17368 Slog.e(TAG, "Unable to write default apps for backup", e); 17369 } 17370 return null; 17371 } 17372 17373 return dataStream.toByteArray(); 17374 } 17375 17376 @Override 17377 public void restoreIntentFilterVerification(byte[] backup, int userId) { 17378 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17379 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17380 } 17381 17382 try { 17383 final XmlPullParser parser = Xml.newPullParser(); 17384 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17385 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 17386 new BlobXmlRestorer() { 17387 @Override 17388 public void apply(XmlPullParser parser, int userId) 17389 throws XmlPullParserException, IOException { 17390 synchronized (mPackages) { 17391 mSettings.readAllDomainVerificationsLPr(parser, userId); 17392 mSettings.writeLPr(); 17393 } 17394 } 17395 } ); 17396 } catch (Exception e) { 17397 if (DEBUG_BACKUP) { 17398 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17399 } 17400 } 17401 } 17402 17403 @Override 17404 public byte[] getPermissionGrantBackup(int userId) { 17405 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17406 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 17407 } 17408 17409 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17410 try { 17411 final XmlSerializer serializer = new FastXmlSerializer(); 17412 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17413 serializer.startDocument(null, true); 17414 serializer.startTag(null, TAG_PERMISSION_BACKUP); 17415 17416 synchronized (mPackages) { 17417 serializeRuntimePermissionGrantsLPr(serializer, userId); 17418 } 17419 17420 serializer.endTag(null, TAG_PERMISSION_BACKUP); 17421 serializer.endDocument(); 17422 serializer.flush(); 17423 } catch (Exception e) { 17424 if (DEBUG_BACKUP) { 17425 Slog.e(TAG, "Unable to write default apps for backup", e); 17426 } 17427 return null; 17428 } 17429 17430 return dataStream.toByteArray(); 17431 } 17432 17433 @Override 17434 public void restorePermissionGrants(byte[] backup, int userId) { 17435 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17436 throw new SecurityException("Only the system may call restorePermissionGrants()"); 17437 } 17438 17439 try { 17440 final XmlPullParser parser = Xml.newPullParser(); 17441 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17442 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 17443 new BlobXmlRestorer() { 17444 @Override 17445 public void apply(XmlPullParser parser, int userId) 17446 throws XmlPullParserException, IOException { 17447 synchronized (mPackages) { 17448 processRestoredPermissionGrantsLPr(parser, userId); 17449 } 17450 } 17451 } ); 17452 } catch (Exception e) { 17453 if (DEBUG_BACKUP) { 17454 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17455 } 17456 } 17457 } 17458 17459 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 17460 throws IOException { 17461 serializer.startTag(null, TAG_ALL_GRANTS); 17462 17463 final int N = mSettings.mPackages.size(); 17464 for (int i = 0; i < N; i++) { 17465 final PackageSetting ps = mSettings.mPackages.valueAt(i); 17466 boolean pkgGrantsKnown = false; 17467 17468 PermissionsState packagePerms = ps.getPermissionsState(); 17469 17470 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 17471 final int grantFlags = state.getFlags(); 17472 // only look at grants that are not system/policy fixed 17473 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 17474 final boolean isGranted = state.isGranted(); 17475 // And only back up the user-twiddled state bits 17476 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 17477 final String packageName = mSettings.mPackages.keyAt(i); 17478 if (!pkgGrantsKnown) { 17479 serializer.startTag(null, TAG_GRANT); 17480 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 17481 pkgGrantsKnown = true; 17482 } 17483 17484 final boolean userSet = 17485 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 17486 final boolean userFixed = 17487 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 17488 final boolean revoke = 17489 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 17490 17491 serializer.startTag(null, TAG_PERMISSION); 17492 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 17493 if (isGranted) { 17494 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 17495 } 17496 if (userSet) { 17497 serializer.attribute(null, ATTR_USER_SET, "true"); 17498 } 17499 if (userFixed) { 17500 serializer.attribute(null, ATTR_USER_FIXED, "true"); 17501 } 17502 if (revoke) { 17503 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 17504 } 17505 serializer.endTag(null, TAG_PERMISSION); 17506 } 17507 } 17508 } 17509 17510 if (pkgGrantsKnown) { 17511 serializer.endTag(null, TAG_GRANT); 17512 } 17513 } 17514 17515 serializer.endTag(null, TAG_ALL_GRANTS); 17516 } 17517 17518 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 17519 throws XmlPullParserException, IOException { 17520 String pkgName = null; 17521 int outerDepth = parser.getDepth(); 17522 int type; 17523 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 17524 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 17525 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 17526 continue; 17527 } 17528 17529 final String tagName = parser.getName(); 17530 if (tagName.equals(TAG_GRANT)) { 17531 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 17532 if (DEBUG_BACKUP) { 17533 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 17534 } 17535 } else if (tagName.equals(TAG_PERMISSION)) { 17536 17537 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 17538 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 17539 17540 int newFlagSet = 0; 17541 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 17542 newFlagSet |= FLAG_PERMISSION_USER_SET; 17543 } 17544 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 17545 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 17546 } 17547 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 17548 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 17549 } 17550 if (DEBUG_BACKUP) { 17551 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 17552 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 17553 } 17554 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17555 if (ps != null) { 17556 // Already installed so we apply the grant immediately 17557 if (DEBUG_BACKUP) { 17558 Slog.v(TAG, " + already installed; applying"); 17559 } 17560 PermissionsState perms = ps.getPermissionsState(); 17561 BasePermission bp = mSettings.mPermissions.get(permName); 17562 if (bp != null) { 17563 if (isGranted) { 17564 perms.grantRuntimePermission(bp, userId); 17565 } 17566 if (newFlagSet != 0) { 17567 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 17568 } 17569 } 17570 } else { 17571 // Need to wait for post-restore install to apply the grant 17572 if (DEBUG_BACKUP) { 17573 Slog.v(TAG, " - not yet installed; saving for later"); 17574 } 17575 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 17576 isGranted, newFlagSet, userId); 17577 } 17578 } else { 17579 PackageManagerService.reportSettingsProblem(Log.WARN, 17580 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 17581 XmlUtils.skipCurrentTag(parser); 17582 } 17583 } 17584 17585 scheduleWriteSettingsLocked(); 17586 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 17587 } 17588 17589 @Override 17590 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 17591 int sourceUserId, int targetUserId, int flags) { 17592 mContext.enforceCallingOrSelfPermission( 17593 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17594 int callingUid = Binder.getCallingUid(); 17595 enforceOwnerRights(ownerPackage, callingUid); 17596 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17597 if (intentFilter.countActions() == 0) { 17598 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 17599 return; 17600 } 17601 synchronized (mPackages) { 17602 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 17603 ownerPackage, targetUserId, flags); 17604 CrossProfileIntentResolver resolver = 17605 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17606 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 17607 // We have all those whose filter is equal. Now checking if the rest is equal as well. 17608 if (existing != null) { 17609 int size = existing.size(); 17610 for (int i = 0; i < size; i++) { 17611 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 17612 return; 17613 } 17614 } 17615 } 17616 resolver.addFilter(newFilter); 17617 scheduleWritePackageRestrictionsLocked(sourceUserId); 17618 } 17619 } 17620 17621 @Override 17622 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 17623 mContext.enforceCallingOrSelfPermission( 17624 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17625 int callingUid = Binder.getCallingUid(); 17626 enforceOwnerRights(ownerPackage, callingUid); 17627 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17628 synchronized (mPackages) { 17629 CrossProfileIntentResolver resolver = 17630 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17631 ArraySet<CrossProfileIntentFilter> set = 17632 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 17633 for (CrossProfileIntentFilter filter : set) { 17634 if (filter.getOwnerPackage().equals(ownerPackage)) { 17635 resolver.removeFilter(filter); 17636 } 17637 } 17638 scheduleWritePackageRestrictionsLocked(sourceUserId); 17639 } 17640 } 17641 17642 // Enforcing that callingUid is owning pkg on userId 17643 private void enforceOwnerRights(String pkg, int callingUid) { 17644 // The system owns everything. 17645 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 17646 return; 17647 } 17648 int callingUserId = UserHandle.getUserId(callingUid); 17649 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 17650 if (pi == null) { 17651 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 17652 + callingUserId); 17653 } 17654 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 17655 throw new SecurityException("Calling uid " + callingUid 17656 + " does not own package " + pkg); 17657 } 17658 } 17659 17660 @Override 17661 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 17662 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 17663 } 17664 17665 private Intent getHomeIntent() { 17666 Intent intent = new Intent(Intent.ACTION_MAIN); 17667 intent.addCategory(Intent.CATEGORY_HOME); 17668 intent.addCategory(Intent.CATEGORY_DEFAULT); 17669 return intent; 17670 } 17671 17672 private IntentFilter getHomeFilter() { 17673 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 17674 filter.addCategory(Intent.CATEGORY_HOME); 17675 filter.addCategory(Intent.CATEGORY_DEFAULT); 17676 return filter; 17677 } 17678 17679 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 17680 int userId) { 17681 Intent intent = getHomeIntent(); 17682 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 17683 PackageManager.GET_META_DATA, userId); 17684 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 17685 true, false, false, userId); 17686 17687 allHomeCandidates.clear(); 17688 if (list != null) { 17689 for (ResolveInfo ri : list) { 17690 allHomeCandidates.add(ri); 17691 } 17692 } 17693 return (preferred == null || preferred.activityInfo == null) 17694 ? null 17695 : new ComponentName(preferred.activityInfo.packageName, 17696 preferred.activityInfo.name); 17697 } 17698 17699 @Override 17700 public void setHomeActivity(ComponentName comp, int userId) { 17701 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 17702 getHomeActivitiesAsUser(homeActivities, userId); 17703 17704 boolean found = false; 17705 17706 final int size = homeActivities.size(); 17707 final ComponentName[] set = new ComponentName[size]; 17708 for (int i = 0; i < size; i++) { 17709 final ResolveInfo candidate = homeActivities.get(i); 17710 final ActivityInfo info = candidate.activityInfo; 17711 final ComponentName activityName = new ComponentName(info.packageName, info.name); 17712 set[i] = activityName; 17713 if (!found && activityName.equals(comp)) { 17714 found = true; 17715 } 17716 } 17717 if (!found) { 17718 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 17719 + userId); 17720 } 17721 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 17722 set, comp, userId); 17723 } 17724 17725 private @Nullable String getSetupWizardPackageName() { 17726 final Intent intent = new Intent(Intent.ACTION_MAIN); 17727 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 17728 17729 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 17730 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 17731 | MATCH_DISABLED_COMPONENTS, 17732 UserHandle.myUserId()); 17733 if (matches.size() == 1) { 17734 return matches.get(0).getComponentInfo().packageName; 17735 } else { 17736 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 17737 + ": matches=" + matches); 17738 return null; 17739 } 17740 } 17741 17742 @Override 17743 public void setApplicationEnabledSetting(String appPackageName, 17744 int newState, int flags, int userId, String callingPackage) { 17745 if (!sUserManager.exists(userId)) return; 17746 if (callingPackage == null) { 17747 callingPackage = Integer.toString(Binder.getCallingUid()); 17748 } 17749 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 17750 } 17751 17752 @Override 17753 public void setComponentEnabledSetting(ComponentName componentName, 17754 int newState, int flags, int userId) { 17755 if (!sUserManager.exists(userId)) return; 17756 setEnabledSetting(componentName.getPackageName(), 17757 componentName.getClassName(), newState, flags, userId, null); 17758 } 17759 17760 private void setEnabledSetting(final String packageName, String className, int newState, 17761 final int flags, int userId, String callingPackage) { 17762 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 17763 || newState == COMPONENT_ENABLED_STATE_ENABLED 17764 || newState == COMPONENT_ENABLED_STATE_DISABLED 17765 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17766 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 17767 throw new IllegalArgumentException("Invalid new component state: " 17768 + newState); 17769 } 17770 PackageSetting pkgSetting; 17771 final int uid = Binder.getCallingUid(); 17772 final int permission; 17773 if (uid == Process.SYSTEM_UID) { 17774 permission = PackageManager.PERMISSION_GRANTED; 17775 } else { 17776 permission = mContext.checkCallingOrSelfPermission( 17777 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17778 } 17779 enforceCrossUserPermission(uid, userId, 17780 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 17781 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17782 boolean sendNow = false; 17783 boolean isApp = (className == null); 17784 String componentName = isApp ? packageName : className; 17785 int packageUid = -1; 17786 ArrayList<String> components; 17787 17788 // writer 17789 synchronized (mPackages) { 17790 pkgSetting = mSettings.mPackages.get(packageName); 17791 if (pkgSetting == null) { 17792 if (className == null) { 17793 throw new IllegalArgumentException("Unknown package: " + packageName); 17794 } 17795 throw new IllegalArgumentException( 17796 "Unknown component: " + packageName + "/" + className); 17797 } 17798 } 17799 17800 // Limit who can change which apps 17801 if (!UserHandle.isSameApp(uid, pkgSetting.appId)) { 17802 // Don't allow apps that don't have permission to modify other apps 17803 if (!allowedByPermission) { 17804 throw new SecurityException( 17805 "Permission Denial: attempt to change component state from pid=" 17806 + Binder.getCallingPid() 17807 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 17808 } 17809 // Don't allow changing protected packages. 17810 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 17811 throw new SecurityException("Cannot disable a protected package: " + packageName); 17812 } 17813 } 17814 17815 synchronized (mPackages) { 17816 if (uid == Process.SHELL_UID) { 17817 // Shell can only change whole packages between ENABLED and DISABLED_USER states 17818 int oldState = pkgSetting.getEnabled(userId); 17819 if (className == null 17820 && 17821 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 17822 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 17823 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 17824 && 17825 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17826 || newState == COMPONENT_ENABLED_STATE_DEFAULT 17827 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 17828 // ok 17829 } else { 17830 throw new SecurityException( 17831 "Shell cannot change component state for " + packageName + "/" 17832 + className + " to " + newState); 17833 } 17834 } 17835 if (className == null) { 17836 // We're dealing with an application/package level state change 17837 if (pkgSetting.getEnabled(userId) == newState) { 17838 // Nothing to do 17839 return; 17840 } 17841 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 17842 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 17843 // Don't care about who enables an app. 17844 callingPackage = null; 17845 } 17846 pkgSetting.setEnabled(newState, userId, callingPackage); 17847 // pkgSetting.pkg.mSetEnabled = newState; 17848 } else { 17849 // We're dealing with a component level state change 17850 // First, verify that this is a valid class name. 17851 PackageParser.Package pkg = pkgSetting.pkg; 17852 if (pkg == null || !pkg.hasComponentClassName(className)) { 17853 if (pkg != null && 17854 pkg.applicationInfo.targetSdkVersion >= 17855 Build.VERSION_CODES.JELLY_BEAN) { 17856 throw new IllegalArgumentException("Component class " + className 17857 + " does not exist in " + packageName); 17858 } else { 17859 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 17860 + className + " does not exist in " + packageName); 17861 } 17862 } 17863 switch (newState) { 17864 case COMPONENT_ENABLED_STATE_ENABLED: 17865 if (!pkgSetting.enableComponentLPw(className, userId)) { 17866 return; 17867 } 17868 break; 17869 case COMPONENT_ENABLED_STATE_DISABLED: 17870 if (!pkgSetting.disableComponentLPw(className, userId)) { 17871 return; 17872 } 17873 break; 17874 case COMPONENT_ENABLED_STATE_DEFAULT: 17875 if (!pkgSetting.restoreComponentLPw(className, userId)) { 17876 return; 17877 } 17878 break; 17879 default: 17880 Slog.e(TAG, "Invalid new component state: " + newState); 17881 return; 17882 } 17883 } 17884 scheduleWritePackageRestrictionsLocked(userId); 17885 components = mPendingBroadcasts.get(userId, packageName); 17886 final boolean newPackage = components == null; 17887 if (newPackage) { 17888 components = new ArrayList<String>(); 17889 } 17890 if (!components.contains(componentName)) { 17891 components.add(componentName); 17892 } 17893 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 17894 sendNow = true; 17895 // Purge entry from pending broadcast list if another one exists already 17896 // since we are sending one right away. 17897 mPendingBroadcasts.remove(userId, packageName); 17898 } else { 17899 if (newPackage) { 17900 mPendingBroadcasts.put(userId, packageName, components); 17901 } 17902 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 17903 // Schedule a message 17904 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 17905 } 17906 } 17907 } 17908 17909 long callingId = Binder.clearCallingIdentity(); 17910 try { 17911 if (sendNow) { 17912 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 17913 sendPackageChangedBroadcast(packageName, 17914 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 17915 } 17916 } finally { 17917 Binder.restoreCallingIdentity(callingId); 17918 } 17919 } 17920 17921 @Override 17922 public void flushPackageRestrictionsAsUser(int userId) { 17923 if (!sUserManager.exists(userId)) { 17924 return; 17925 } 17926 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 17927 false /* checkShell */, "flushPackageRestrictions"); 17928 synchronized (mPackages) { 17929 mSettings.writePackageRestrictionsLPr(userId); 17930 mDirtyUsers.remove(userId); 17931 if (mDirtyUsers.isEmpty()) { 17932 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 17933 } 17934 } 17935 } 17936 17937 private void sendPackageChangedBroadcast(String packageName, 17938 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 17939 if (DEBUG_INSTALL) 17940 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 17941 + componentNames); 17942 Bundle extras = new Bundle(4); 17943 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 17944 String nameList[] = new String[componentNames.size()]; 17945 componentNames.toArray(nameList); 17946 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 17947 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 17948 extras.putInt(Intent.EXTRA_UID, packageUid); 17949 // If this is not reporting a change of the overall package, then only send it 17950 // to registered receivers. We don't want to launch a swath of apps for every 17951 // little component state change. 17952 final int flags = !componentNames.contains(packageName) 17953 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 17954 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 17955 new int[] {UserHandle.getUserId(packageUid)}); 17956 } 17957 17958 @Override 17959 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 17960 if (!sUserManager.exists(userId)) return; 17961 final int uid = Binder.getCallingUid(); 17962 final int permission = mContext.checkCallingOrSelfPermission( 17963 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17964 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17965 enforceCrossUserPermission(uid, userId, 17966 true /* requireFullPermission */, true /* checkShell */, "stop package"); 17967 // writer 17968 synchronized (mPackages) { 17969 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 17970 allowedByPermission, uid, userId)) { 17971 scheduleWritePackageRestrictionsLocked(userId); 17972 } 17973 } 17974 } 17975 17976 @Override 17977 public String getInstallerPackageName(String packageName) { 17978 // reader 17979 synchronized (mPackages) { 17980 return mSettings.getInstallerPackageNameLPr(packageName); 17981 } 17982 } 17983 17984 public boolean isOrphaned(String packageName) { 17985 // reader 17986 synchronized (mPackages) { 17987 return mSettings.isOrphaned(packageName); 17988 } 17989 } 17990 17991 @Override 17992 public int getApplicationEnabledSetting(String packageName, int userId) { 17993 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17994 int uid = Binder.getCallingUid(); 17995 enforceCrossUserPermission(uid, userId, 17996 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 17997 // reader 17998 synchronized (mPackages) { 17999 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 18000 } 18001 } 18002 18003 @Override 18004 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 18005 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 18006 int uid = Binder.getCallingUid(); 18007 enforceCrossUserPermission(uid, userId, 18008 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 18009 // reader 18010 synchronized (mPackages) { 18011 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 18012 } 18013 } 18014 18015 @Override 18016 public void enterSafeMode() { 18017 enforceSystemOrRoot("Only the system can request entering safe mode"); 18018 18019 if (!mSystemReady) { 18020 mSafeMode = true; 18021 } 18022 } 18023 18024 @Override 18025 public void systemReady() { 18026 mSystemReady = true; 18027 18028 // Read the compatibilty setting when the system is ready. 18029 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 18030 mContext.getContentResolver(), 18031 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 18032 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 18033 if (DEBUG_SETTINGS) { 18034 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 18035 } 18036 18037 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 18038 18039 synchronized (mPackages) { 18040 // Verify that all of the preferred activity components actually 18041 // exist. It is possible for applications to be updated and at 18042 // that point remove a previously declared activity component that 18043 // had been set as a preferred activity. We try to clean this up 18044 // the next time we encounter that preferred activity, but it is 18045 // possible for the user flow to never be able to return to that 18046 // situation so here we do a sanity check to make sure we haven't 18047 // left any junk around. 18048 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 18049 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18050 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18051 removed.clear(); 18052 for (PreferredActivity pa : pir.filterSet()) { 18053 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 18054 removed.add(pa); 18055 } 18056 } 18057 if (removed.size() > 0) { 18058 for (int r=0; r<removed.size(); r++) { 18059 PreferredActivity pa = removed.get(r); 18060 Slog.w(TAG, "Removing dangling preferred activity: " 18061 + pa.mPref.mComponent); 18062 pir.removeFilter(pa); 18063 } 18064 mSettings.writePackageRestrictionsLPr( 18065 mSettings.mPreferredActivities.keyAt(i)); 18066 } 18067 } 18068 18069 for (int userId : UserManagerService.getInstance().getUserIds()) { 18070 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 18071 grantPermissionsUserIds = ArrayUtils.appendInt( 18072 grantPermissionsUserIds, userId); 18073 } 18074 } 18075 } 18076 sUserManager.systemReady(); 18077 18078 // If we upgraded grant all default permissions before kicking off. 18079 for (int userId : grantPermissionsUserIds) { 18080 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 18081 } 18082 18083 // Kick off any messages waiting for system ready 18084 if (mPostSystemReadyMessages != null) { 18085 for (Message msg : mPostSystemReadyMessages) { 18086 msg.sendToTarget(); 18087 } 18088 mPostSystemReadyMessages = null; 18089 } 18090 18091 // Watch for external volumes that come and go over time 18092 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18093 storage.registerListener(mStorageListener); 18094 18095 mInstallerService.systemReady(); 18096 mPackageDexOptimizer.systemReady(); 18097 18098 MountServiceInternal mountServiceInternal = LocalServices.getService( 18099 MountServiceInternal.class); 18100 mountServiceInternal.addExternalStoragePolicy( 18101 new MountServiceInternal.ExternalStorageMountPolicy() { 18102 @Override 18103 public int getMountMode(int uid, String packageName) { 18104 if (Process.isIsolated(uid)) { 18105 return Zygote.MOUNT_EXTERNAL_NONE; 18106 } 18107 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 18108 return Zygote.MOUNT_EXTERNAL_DEFAULT; 18109 } 18110 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 18111 return Zygote.MOUNT_EXTERNAL_DEFAULT; 18112 } 18113 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 18114 return Zygote.MOUNT_EXTERNAL_READ; 18115 } 18116 return Zygote.MOUNT_EXTERNAL_WRITE; 18117 } 18118 18119 @Override 18120 public boolean hasExternalStorage(int uid, String packageName) { 18121 return true; 18122 } 18123 }); 18124 18125 // Now that we're mostly running, clean up stale users and apps 18126 reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 18127 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 18128 } 18129 18130 @Override 18131 public boolean isSafeMode() { 18132 return mSafeMode; 18133 } 18134 18135 @Override 18136 public boolean hasSystemUidErrors() { 18137 return mHasSystemUidErrors; 18138 } 18139 18140 static String arrayToString(int[] array) { 18141 StringBuffer buf = new StringBuffer(128); 18142 buf.append('['); 18143 if (array != null) { 18144 for (int i=0; i<array.length; i++) { 18145 if (i > 0) buf.append(", "); 18146 buf.append(array[i]); 18147 } 18148 } 18149 buf.append(']'); 18150 return buf.toString(); 18151 } 18152 18153 static class DumpState { 18154 public static final int DUMP_LIBS = 1 << 0; 18155 public static final int DUMP_FEATURES = 1 << 1; 18156 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 18157 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 18158 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 18159 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 18160 public static final int DUMP_PERMISSIONS = 1 << 6; 18161 public static final int DUMP_PACKAGES = 1 << 7; 18162 public static final int DUMP_SHARED_USERS = 1 << 8; 18163 public static final int DUMP_MESSAGES = 1 << 9; 18164 public static final int DUMP_PROVIDERS = 1 << 10; 18165 public static final int DUMP_VERIFIERS = 1 << 11; 18166 public static final int DUMP_PREFERRED = 1 << 12; 18167 public static final int DUMP_PREFERRED_XML = 1 << 13; 18168 public static final int DUMP_KEYSETS = 1 << 14; 18169 public static final int DUMP_VERSION = 1 << 15; 18170 public static final int DUMP_INSTALLS = 1 << 16; 18171 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 18172 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 18173 public static final int DUMP_FROZEN = 1 << 19; 18174 public static final int DUMP_DEXOPT = 1 << 20; 18175 18176 public static final int OPTION_SHOW_FILTERS = 1 << 0; 18177 18178 private int mTypes; 18179 18180 private int mOptions; 18181 18182 private boolean mTitlePrinted; 18183 18184 private SharedUserSetting mSharedUser; 18185 18186 public boolean isDumping(int type) { 18187 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 18188 return true; 18189 } 18190 18191 return (mTypes & type) != 0; 18192 } 18193 18194 public void setDump(int type) { 18195 mTypes |= type; 18196 } 18197 18198 public boolean isOptionEnabled(int option) { 18199 return (mOptions & option) != 0; 18200 } 18201 18202 public void setOptionEnabled(int option) { 18203 mOptions |= option; 18204 } 18205 18206 public boolean onTitlePrinted() { 18207 final boolean printed = mTitlePrinted; 18208 mTitlePrinted = true; 18209 return printed; 18210 } 18211 18212 public boolean getTitlePrinted() { 18213 return mTitlePrinted; 18214 } 18215 18216 public void setTitlePrinted(boolean enabled) { 18217 mTitlePrinted = enabled; 18218 } 18219 18220 public SharedUserSetting getSharedUser() { 18221 return mSharedUser; 18222 } 18223 18224 public void setSharedUser(SharedUserSetting user) { 18225 mSharedUser = user; 18226 } 18227 } 18228 18229 @Override 18230 public void onShellCommand(FileDescriptor in, FileDescriptor out, 18231 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 18232 (new PackageManagerShellCommand(this)).exec( 18233 this, in, out, err, args, resultReceiver); 18234 } 18235 18236 @Override 18237 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 18238 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 18239 != PackageManager.PERMISSION_GRANTED) { 18240 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 18241 + Binder.getCallingPid() 18242 + ", uid=" + Binder.getCallingUid() 18243 + " without permission " 18244 + android.Manifest.permission.DUMP); 18245 return; 18246 } 18247 18248 DumpState dumpState = new DumpState(); 18249 boolean fullPreferred = false; 18250 boolean checkin = false; 18251 18252 String packageName = null; 18253 ArraySet<String> permissionNames = null; 18254 18255 int opti = 0; 18256 while (opti < args.length) { 18257 String opt = args[opti]; 18258 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 18259 break; 18260 } 18261 opti++; 18262 18263 if ("-a".equals(opt)) { 18264 // Right now we only know how to print all. 18265 } else if ("-h".equals(opt)) { 18266 pw.println("Package manager dump options:"); 18267 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 18268 pw.println(" --checkin: dump for a checkin"); 18269 pw.println(" -f: print details of intent filters"); 18270 pw.println(" -h: print this help"); 18271 pw.println(" cmd may be one of:"); 18272 pw.println(" l[ibraries]: list known shared libraries"); 18273 pw.println(" f[eatures]: list device features"); 18274 pw.println(" k[eysets]: print known keysets"); 18275 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 18276 pw.println(" perm[issions]: dump permissions"); 18277 pw.println(" permission [name ...]: dump declaration and use of given permission"); 18278 pw.println(" pref[erred]: print preferred package settings"); 18279 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 18280 pw.println(" prov[iders]: dump content providers"); 18281 pw.println(" p[ackages]: dump installed packages"); 18282 pw.println(" s[hared-users]: dump shared user IDs"); 18283 pw.println(" m[essages]: print collected runtime messages"); 18284 pw.println(" v[erifiers]: print package verifier info"); 18285 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 18286 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 18287 pw.println(" version: print database version info"); 18288 pw.println(" write: write current settings now"); 18289 pw.println(" installs: details about install sessions"); 18290 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 18291 pw.println(" dexopt: dump dexopt state"); 18292 pw.println(" <package.name>: info about given package"); 18293 return; 18294 } else if ("--checkin".equals(opt)) { 18295 checkin = true; 18296 } else if ("-f".equals(opt)) { 18297 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18298 } else { 18299 pw.println("Unknown argument: " + opt + "; use -h for help"); 18300 } 18301 } 18302 18303 // Is the caller requesting to dump a particular piece of data? 18304 if (opti < args.length) { 18305 String cmd = args[opti]; 18306 opti++; 18307 // Is this a package name? 18308 if ("android".equals(cmd) || cmd.contains(".")) { 18309 packageName = cmd; 18310 // When dumping a single package, we always dump all of its 18311 // filter information since the amount of data will be reasonable. 18312 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18313 } else if ("check-permission".equals(cmd)) { 18314 if (opti >= args.length) { 18315 pw.println("Error: check-permission missing permission argument"); 18316 return; 18317 } 18318 String perm = args[opti]; 18319 opti++; 18320 if (opti >= args.length) { 18321 pw.println("Error: check-permission missing package argument"); 18322 return; 18323 } 18324 String pkg = args[opti]; 18325 opti++; 18326 int user = UserHandle.getUserId(Binder.getCallingUid()); 18327 if (opti < args.length) { 18328 try { 18329 user = Integer.parseInt(args[opti]); 18330 } catch (NumberFormatException e) { 18331 pw.println("Error: check-permission user argument is not a number: " 18332 + args[opti]); 18333 return; 18334 } 18335 } 18336 pw.println(checkPermission(perm, pkg, user)); 18337 return; 18338 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 18339 dumpState.setDump(DumpState.DUMP_LIBS); 18340 } else if ("f".equals(cmd) || "features".equals(cmd)) { 18341 dumpState.setDump(DumpState.DUMP_FEATURES); 18342 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 18343 if (opti >= args.length) { 18344 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 18345 | DumpState.DUMP_SERVICE_RESOLVERS 18346 | DumpState.DUMP_RECEIVER_RESOLVERS 18347 | DumpState.DUMP_CONTENT_RESOLVERS); 18348 } else { 18349 while (opti < args.length) { 18350 String name = args[opti]; 18351 if ("a".equals(name) || "activity".equals(name)) { 18352 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 18353 } else if ("s".equals(name) || "service".equals(name)) { 18354 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 18355 } else if ("r".equals(name) || "receiver".equals(name)) { 18356 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 18357 } else if ("c".equals(name) || "content".equals(name)) { 18358 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 18359 } else { 18360 pw.println("Error: unknown resolver table type: " + name); 18361 return; 18362 } 18363 opti++; 18364 } 18365 } 18366 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 18367 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 18368 } else if ("permission".equals(cmd)) { 18369 if (opti >= args.length) { 18370 pw.println("Error: permission requires permission name"); 18371 return; 18372 } 18373 permissionNames = new ArraySet<>(); 18374 while (opti < args.length) { 18375 permissionNames.add(args[opti]); 18376 opti++; 18377 } 18378 dumpState.setDump(DumpState.DUMP_PERMISSIONS 18379 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 18380 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 18381 dumpState.setDump(DumpState.DUMP_PREFERRED); 18382 } else if ("preferred-xml".equals(cmd)) { 18383 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 18384 if (opti < args.length && "--full".equals(args[opti])) { 18385 fullPreferred = true; 18386 opti++; 18387 } 18388 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 18389 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 18390 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 18391 dumpState.setDump(DumpState.DUMP_PACKAGES); 18392 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 18393 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 18394 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 18395 dumpState.setDump(DumpState.DUMP_PROVIDERS); 18396 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 18397 dumpState.setDump(DumpState.DUMP_MESSAGES); 18398 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 18399 dumpState.setDump(DumpState.DUMP_VERIFIERS); 18400 } else if ("i".equals(cmd) || "ifv".equals(cmd) 18401 || "intent-filter-verifiers".equals(cmd)) { 18402 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 18403 } else if ("version".equals(cmd)) { 18404 dumpState.setDump(DumpState.DUMP_VERSION); 18405 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 18406 dumpState.setDump(DumpState.DUMP_KEYSETS); 18407 } else if ("installs".equals(cmd)) { 18408 dumpState.setDump(DumpState.DUMP_INSTALLS); 18409 } else if ("frozen".equals(cmd)) { 18410 dumpState.setDump(DumpState.DUMP_FROZEN); 18411 } else if ("dexopt".equals(cmd)) { 18412 dumpState.setDump(DumpState.DUMP_DEXOPT); 18413 } else if ("write".equals(cmd)) { 18414 synchronized (mPackages) { 18415 mSettings.writeLPr(); 18416 pw.println("Settings written."); 18417 return; 18418 } 18419 } 18420 } 18421 18422 if (checkin) { 18423 pw.println("vers,1"); 18424 } 18425 18426 // reader 18427 synchronized (mPackages) { 18428 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 18429 if (!checkin) { 18430 if (dumpState.onTitlePrinted()) 18431 pw.println(); 18432 pw.println("Database versions:"); 18433 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 18434 } 18435 } 18436 18437 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 18438 if (!checkin) { 18439 if (dumpState.onTitlePrinted()) 18440 pw.println(); 18441 pw.println("Verifiers:"); 18442 pw.print(" Required: "); 18443 pw.print(mRequiredVerifierPackage); 18444 pw.print(" (uid="); 18445 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18446 UserHandle.USER_SYSTEM)); 18447 pw.println(")"); 18448 } else if (mRequiredVerifierPackage != null) { 18449 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 18450 pw.print(","); 18451 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18452 UserHandle.USER_SYSTEM)); 18453 } 18454 } 18455 18456 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 18457 packageName == null) { 18458 if (mIntentFilterVerifierComponent != null) { 18459 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 18460 if (!checkin) { 18461 if (dumpState.onTitlePrinted()) 18462 pw.println(); 18463 pw.println("Intent Filter Verifier:"); 18464 pw.print(" Using: "); 18465 pw.print(verifierPackageName); 18466 pw.print(" (uid="); 18467 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18468 UserHandle.USER_SYSTEM)); 18469 pw.println(")"); 18470 } else if (verifierPackageName != null) { 18471 pw.print("ifv,"); pw.print(verifierPackageName); 18472 pw.print(","); 18473 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18474 UserHandle.USER_SYSTEM)); 18475 } 18476 } else { 18477 pw.println(); 18478 pw.println("No Intent Filter Verifier available!"); 18479 } 18480 } 18481 18482 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 18483 boolean printedHeader = false; 18484 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 18485 while (it.hasNext()) { 18486 String name = it.next(); 18487 SharedLibraryEntry ent = mSharedLibraries.get(name); 18488 if (!checkin) { 18489 if (!printedHeader) { 18490 if (dumpState.onTitlePrinted()) 18491 pw.println(); 18492 pw.println("Libraries:"); 18493 printedHeader = true; 18494 } 18495 pw.print(" "); 18496 } else { 18497 pw.print("lib,"); 18498 } 18499 pw.print(name); 18500 if (!checkin) { 18501 pw.print(" -> "); 18502 } 18503 if (ent.path != null) { 18504 if (!checkin) { 18505 pw.print("(jar) "); 18506 pw.print(ent.path); 18507 } else { 18508 pw.print(",jar,"); 18509 pw.print(ent.path); 18510 } 18511 } else { 18512 if (!checkin) { 18513 pw.print("(apk) "); 18514 pw.print(ent.apk); 18515 } else { 18516 pw.print(",apk,"); 18517 pw.print(ent.apk); 18518 } 18519 } 18520 pw.println(); 18521 } 18522 } 18523 18524 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 18525 if (dumpState.onTitlePrinted()) 18526 pw.println(); 18527 if (!checkin) { 18528 pw.println("Features:"); 18529 } 18530 18531 for (FeatureInfo feat : mAvailableFeatures.values()) { 18532 if (checkin) { 18533 pw.print("feat,"); 18534 pw.print(feat.name); 18535 pw.print(","); 18536 pw.println(feat.version); 18537 } else { 18538 pw.print(" "); 18539 pw.print(feat.name); 18540 if (feat.version > 0) { 18541 pw.print(" version="); 18542 pw.print(feat.version); 18543 } 18544 pw.println(); 18545 } 18546 } 18547 } 18548 18549 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 18550 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 18551 : "Activity Resolver Table:", " ", packageName, 18552 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18553 dumpState.setTitlePrinted(true); 18554 } 18555 } 18556 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 18557 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 18558 : "Receiver Resolver Table:", " ", packageName, 18559 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18560 dumpState.setTitlePrinted(true); 18561 } 18562 } 18563 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 18564 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 18565 : "Service Resolver Table:", " ", packageName, 18566 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18567 dumpState.setTitlePrinted(true); 18568 } 18569 } 18570 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 18571 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 18572 : "Provider Resolver Table:", " ", packageName, 18573 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18574 dumpState.setTitlePrinted(true); 18575 } 18576 } 18577 18578 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 18579 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18580 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18581 int user = mSettings.mPreferredActivities.keyAt(i); 18582 if (pir.dump(pw, 18583 dumpState.getTitlePrinted() 18584 ? "\nPreferred Activities User " + user + ":" 18585 : "Preferred Activities User " + user + ":", " ", 18586 packageName, true, false)) { 18587 dumpState.setTitlePrinted(true); 18588 } 18589 } 18590 } 18591 18592 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 18593 pw.flush(); 18594 FileOutputStream fout = new FileOutputStream(fd); 18595 BufferedOutputStream str = new BufferedOutputStream(fout); 18596 XmlSerializer serializer = new FastXmlSerializer(); 18597 try { 18598 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 18599 serializer.startDocument(null, true); 18600 serializer.setFeature( 18601 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 18602 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 18603 serializer.endDocument(); 18604 serializer.flush(); 18605 } catch (IllegalArgumentException e) { 18606 pw.println("Failed writing: " + e); 18607 } catch (IllegalStateException e) { 18608 pw.println("Failed writing: " + e); 18609 } catch (IOException e) { 18610 pw.println("Failed writing: " + e); 18611 } 18612 } 18613 18614 if (!checkin 18615 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 18616 && packageName == null) { 18617 pw.println(); 18618 int count = mSettings.mPackages.size(); 18619 if (count == 0) { 18620 pw.println("No applications!"); 18621 pw.println(); 18622 } else { 18623 final String prefix = " "; 18624 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 18625 if (allPackageSettings.size() == 0) { 18626 pw.println("No domain preferred apps!"); 18627 pw.println(); 18628 } else { 18629 pw.println("App verification status:"); 18630 pw.println(); 18631 count = 0; 18632 for (PackageSetting ps : allPackageSettings) { 18633 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 18634 if (ivi == null || ivi.getPackageName() == null) continue; 18635 pw.println(prefix + "Package: " + ivi.getPackageName()); 18636 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 18637 pw.println(prefix + "Status: " + ivi.getStatusString()); 18638 pw.println(); 18639 count++; 18640 } 18641 if (count == 0) { 18642 pw.println(prefix + "No app verification established."); 18643 pw.println(); 18644 } 18645 for (int userId : sUserManager.getUserIds()) { 18646 pw.println("App linkages for user " + userId + ":"); 18647 pw.println(); 18648 count = 0; 18649 for (PackageSetting ps : allPackageSettings) { 18650 final long status = ps.getDomainVerificationStatusForUser(userId); 18651 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 18652 continue; 18653 } 18654 pw.println(prefix + "Package: " + ps.name); 18655 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 18656 String statusStr = IntentFilterVerificationInfo. 18657 getStatusStringFromValue(status); 18658 pw.println(prefix + "Status: " + statusStr); 18659 pw.println(); 18660 count++; 18661 } 18662 if (count == 0) { 18663 pw.println(prefix + "No configured app linkages."); 18664 pw.println(); 18665 } 18666 } 18667 } 18668 } 18669 } 18670 18671 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 18672 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 18673 if (packageName == null && permissionNames == null) { 18674 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 18675 if (iperm == 0) { 18676 if (dumpState.onTitlePrinted()) 18677 pw.println(); 18678 pw.println("AppOp Permissions:"); 18679 } 18680 pw.print(" AppOp Permission "); 18681 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 18682 pw.println(":"); 18683 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 18684 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 18685 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 18686 } 18687 } 18688 } 18689 } 18690 18691 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 18692 boolean printedSomething = false; 18693 for (PackageParser.Provider p : mProviders.mProviders.values()) { 18694 if (packageName != null && !packageName.equals(p.info.packageName)) { 18695 continue; 18696 } 18697 if (!printedSomething) { 18698 if (dumpState.onTitlePrinted()) 18699 pw.println(); 18700 pw.println("Registered ContentProviders:"); 18701 printedSomething = true; 18702 } 18703 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 18704 pw.print(" "); pw.println(p.toString()); 18705 } 18706 printedSomething = false; 18707 for (Map.Entry<String, PackageParser.Provider> entry : 18708 mProvidersByAuthority.entrySet()) { 18709 PackageParser.Provider p = entry.getValue(); 18710 if (packageName != null && !packageName.equals(p.info.packageName)) { 18711 continue; 18712 } 18713 if (!printedSomething) { 18714 if (dumpState.onTitlePrinted()) 18715 pw.println(); 18716 pw.println("ContentProvider Authorities:"); 18717 printedSomething = true; 18718 } 18719 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 18720 pw.print(" "); pw.println(p.toString()); 18721 if (p.info != null && p.info.applicationInfo != null) { 18722 final String appInfo = p.info.applicationInfo.toString(); 18723 pw.print(" applicationInfo="); pw.println(appInfo); 18724 } 18725 } 18726 } 18727 18728 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 18729 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 18730 } 18731 18732 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 18733 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 18734 } 18735 18736 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 18737 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 18738 } 18739 18740 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 18741 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 18742 } 18743 18744 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 18745 // XXX should handle packageName != null by dumping only install data that 18746 // the given package is involved with. 18747 if (dumpState.onTitlePrinted()) pw.println(); 18748 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 18749 } 18750 18751 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 18752 // XXX should handle packageName != null by dumping only install data that 18753 // the given package is involved with. 18754 if (dumpState.onTitlePrinted()) pw.println(); 18755 18756 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18757 ipw.println(); 18758 ipw.println("Frozen packages:"); 18759 ipw.increaseIndent(); 18760 if (mFrozenPackages.size() == 0) { 18761 ipw.println("(none)"); 18762 } else { 18763 for (int i = 0; i < mFrozenPackages.size(); i++) { 18764 ipw.println(mFrozenPackages.valueAt(i)); 18765 } 18766 } 18767 ipw.decreaseIndent(); 18768 } 18769 18770 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 18771 if (dumpState.onTitlePrinted()) pw.println(); 18772 dumpDexoptStateLPr(pw, packageName); 18773 } 18774 18775 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 18776 if (dumpState.onTitlePrinted()) pw.println(); 18777 mSettings.dumpReadMessagesLPr(pw, dumpState); 18778 18779 pw.println(); 18780 pw.println("Package warning messages:"); 18781 BufferedReader in = null; 18782 String line = null; 18783 try { 18784 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18785 while ((line = in.readLine()) != null) { 18786 if (line.contains("ignored: updated version")) continue; 18787 pw.println(line); 18788 } 18789 } catch (IOException ignored) { 18790 } finally { 18791 IoUtils.closeQuietly(in); 18792 } 18793 } 18794 18795 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 18796 BufferedReader in = null; 18797 String line = null; 18798 try { 18799 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18800 while ((line = in.readLine()) != null) { 18801 if (line.contains("ignored: updated version")) continue; 18802 pw.print("msg,"); 18803 pw.println(line); 18804 } 18805 } catch (IOException ignored) { 18806 } finally { 18807 IoUtils.closeQuietly(in); 18808 } 18809 } 18810 } 18811 } 18812 18813 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 18814 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18815 ipw.println(); 18816 ipw.println("Dexopt state:"); 18817 ipw.increaseIndent(); 18818 Collection<PackageParser.Package> packages = null; 18819 if (packageName != null) { 18820 PackageParser.Package targetPackage = mPackages.get(packageName); 18821 if (targetPackage != null) { 18822 packages = Collections.singletonList(targetPackage); 18823 } else { 18824 ipw.println("Unable to find package: " + packageName); 18825 return; 18826 } 18827 } else { 18828 packages = mPackages.values(); 18829 } 18830 18831 for (PackageParser.Package pkg : packages) { 18832 ipw.println("[" + pkg.packageName + "]"); 18833 ipw.increaseIndent(); 18834 mPackageDexOptimizer.dumpDexoptState(ipw, pkg); 18835 ipw.decreaseIndent(); 18836 } 18837 } 18838 18839 private String dumpDomainString(String packageName) { 18840 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 18841 .getList(); 18842 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 18843 18844 ArraySet<String> result = new ArraySet<>(); 18845 if (iviList.size() > 0) { 18846 for (IntentFilterVerificationInfo ivi : iviList) { 18847 for (String host : ivi.getDomains()) { 18848 result.add(host); 18849 } 18850 } 18851 } 18852 if (filters != null && filters.size() > 0) { 18853 for (IntentFilter filter : filters) { 18854 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 18855 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 18856 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 18857 result.addAll(filter.getHostsList()); 18858 } 18859 } 18860 } 18861 18862 StringBuilder sb = new StringBuilder(result.size() * 16); 18863 for (String domain : result) { 18864 if (sb.length() > 0) sb.append(" "); 18865 sb.append(domain); 18866 } 18867 return sb.toString(); 18868 } 18869 18870 // ------- apps on sdcard specific code ------- 18871 static final boolean DEBUG_SD_INSTALL = false; 18872 18873 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 18874 18875 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 18876 18877 private boolean mMediaMounted = false; 18878 18879 static String getEncryptKey() { 18880 try { 18881 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 18882 SD_ENCRYPTION_KEYSTORE_NAME); 18883 if (sdEncKey == null) { 18884 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 18885 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 18886 if (sdEncKey == null) { 18887 Slog.e(TAG, "Failed to create encryption keys"); 18888 return null; 18889 } 18890 } 18891 return sdEncKey; 18892 } catch (NoSuchAlgorithmException nsae) { 18893 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 18894 return null; 18895 } catch (IOException ioe) { 18896 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 18897 return null; 18898 } 18899 } 18900 18901 /* 18902 * Update media status on PackageManager. 18903 */ 18904 @Override 18905 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 18906 int callingUid = Binder.getCallingUid(); 18907 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 18908 throw new SecurityException("Media status can only be updated by the system"); 18909 } 18910 // reader; this apparently protects mMediaMounted, but should probably 18911 // be a different lock in that case. 18912 synchronized (mPackages) { 18913 Log.i(TAG, "Updating external media status from " 18914 + (mMediaMounted ? "mounted" : "unmounted") + " to " 18915 + (mediaStatus ? "mounted" : "unmounted")); 18916 if (DEBUG_SD_INSTALL) 18917 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 18918 + ", mMediaMounted=" + mMediaMounted); 18919 if (mediaStatus == mMediaMounted) { 18920 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 18921 : 0, -1); 18922 mHandler.sendMessage(msg); 18923 return; 18924 } 18925 mMediaMounted = mediaStatus; 18926 } 18927 // Queue up an async operation since the package installation may take a 18928 // little while. 18929 mHandler.post(new Runnable() { 18930 public void run() { 18931 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 18932 } 18933 }); 18934 } 18935 18936 /** 18937 * Called by MountService when the initial ASECs to scan are available. 18938 * Should block until all the ASEC containers are finished being scanned. 18939 */ 18940 public void scanAvailableAsecs() { 18941 updateExternalMediaStatusInner(true, false, false); 18942 } 18943 18944 /* 18945 * Collect information of applications on external media, map them against 18946 * existing containers and update information based on current mount status. 18947 * Please note that we always have to report status if reportStatus has been 18948 * set to true especially when unloading packages. 18949 */ 18950 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 18951 boolean externalStorage) { 18952 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 18953 int[] uidArr = EmptyArray.INT; 18954 18955 final String[] list = PackageHelper.getSecureContainerList(); 18956 if (ArrayUtils.isEmpty(list)) { 18957 Log.i(TAG, "No secure containers found"); 18958 } else { 18959 // Process list of secure containers and categorize them 18960 // as active or stale based on their package internal state. 18961 18962 // reader 18963 synchronized (mPackages) { 18964 for (String cid : list) { 18965 // Leave stages untouched for now; installer service owns them 18966 if (PackageInstallerService.isStageName(cid)) continue; 18967 18968 if (DEBUG_SD_INSTALL) 18969 Log.i(TAG, "Processing container " + cid); 18970 String pkgName = getAsecPackageName(cid); 18971 if (pkgName == null) { 18972 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 18973 continue; 18974 } 18975 if (DEBUG_SD_INSTALL) 18976 Log.i(TAG, "Looking for pkg : " + pkgName); 18977 18978 final PackageSetting ps = mSettings.mPackages.get(pkgName); 18979 if (ps == null) { 18980 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 18981 continue; 18982 } 18983 18984 /* 18985 * Skip packages that are not external if we're unmounting 18986 * external storage. 18987 */ 18988 if (externalStorage && !isMounted && !isExternal(ps)) { 18989 continue; 18990 } 18991 18992 final AsecInstallArgs args = new AsecInstallArgs(cid, 18993 getAppDexInstructionSets(ps), ps.isForwardLocked()); 18994 // The package status is changed only if the code path 18995 // matches between settings and the container id. 18996 if (ps.codePathString != null 18997 && ps.codePathString.startsWith(args.getCodePath())) { 18998 if (DEBUG_SD_INSTALL) { 18999 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 19000 + " at code path: " + ps.codePathString); 19001 } 19002 19003 // We do have a valid package installed on sdcard 19004 processCids.put(args, ps.codePathString); 19005 final int uid = ps.appId; 19006 if (uid != -1) { 19007 uidArr = ArrayUtils.appendInt(uidArr, uid); 19008 } 19009 } else { 19010 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 19011 + ps.codePathString); 19012 } 19013 } 19014 } 19015 19016 Arrays.sort(uidArr); 19017 } 19018 19019 // Process packages with valid entries. 19020 if (isMounted) { 19021 if (DEBUG_SD_INSTALL) 19022 Log.i(TAG, "Loading packages"); 19023 loadMediaPackages(processCids, uidArr, externalStorage); 19024 startCleaningPackages(); 19025 mInstallerService.onSecureContainersAvailable(); 19026 } else { 19027 if (DEBUG_SD_INSTALL) 19028 Log.i(TAG, "Unloading packages"); 19029 unloadMediaPackages(processCids, uidArr, reportStatus); 19030 } 19031 } 19032 19033 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19034 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 19035 final int size = infos.size(); 19036 final String[] packageNames = new String[size]; 19037 final int[] packageUids = new int[size]; 19038 for (int i = 0; i < size; i++) { 19039 final ApplicationInfo info = infos.get(i); 19040 packageNames[i] = info.packageName; 19041 packageUids[i] = info.uid; 19042 } 19043 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 19044 finishedReceiver); 19045 } 19046 19047 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19048 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 19049 sendResourcesChangedBroadcast(mediaStatus, replacing, 19050 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 19051 } 19052 19053 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19054 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 19055 int size = pkgList.length; 19056 if (size > 0) { 19057 // Send broadcasts here 19058 Bundle extras = new Bundle(); 19059 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 19060 if (uidArr != null) { 19061 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 19062 } 19063 if (replacing) { 19064 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 19065 } 19066 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 19067 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 19068 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 19069 } 19070 } 19071 19072 /* 19073 * Look at potentially valid container ids from processCids If package 19074 * information doesn't match the one on record or package scanning fails, 19075 * the cid is added to list of removeCids. We currently don't delete stale 19076 * containers. 19077 */ 19078 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 19079 boolean externalStorage) { 19080 ArrayList<String> pkgList = new ArrayList<String>(); 19081 Set<AsecInstallArgs> keys = processCids.keySet(); 19082 19083 for (AsecInstallArgs args : keys) { 19084 String codePath = processCids.get(args); 19085 if (DEBUG_SD_INSTALL) 19086 Log.i(TAG, "Loading container : " + args.cid); 19087 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 19088 try { 19089 // Make sure there are no container errors first. 19090 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 19091 Slog.e(TAG, "Failed to mount cid : " + args.cid 19092 + " when installing from sdcard"); 19093 continue; 19094 } 19095 // Check code path here. 19096 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 19097 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 19098 + " does not match one in settings " + codePath); 19099 continue; 19100 } 19101 // Parse package 19102 int parseFlags = mDefParseFlags; 19103 if (args.isExternalAsec()) { 19104 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 19105 } 19106 if (args.isFwdLocked()) { 19107 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 19108 } 19109 19110 synchronized (mInstallLock) { 19111 PackageParser.Package pkg = null; 19112 try { 19113 // Sadly we don't know the package name yet to freeze it 19114 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 19115 SCAN_IGNORE_FROZEN, 0, null); 19116 } catch (PackageManagerException e) { 19117 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 19118 } 19119 // Scan the package 19120 if (pkg != null) { 19121 /* 19122 * TODO why is the lock being held? doPostInstall is 19123 * called in other places without the lock. This needs 19124 * to be straightened out. 19125 */ 19126 // writer 19127 synchronized (mPackages) { 19128 retCode = PackageManager.INSTALL_SUCCEEDED; 19129 pkgList.add(pkg.packageName); 19130 // Post process args 19131 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 19132 pkg.applicationInfo.uid); 19133 } 19134 } else { 19135 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 19136 } 19137 } 19138 19139 } finally { 19140 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 19141 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 19142 } 19143 } 19144 } 19145 // writer 19146 synchronized (mPackages) { 19147 // If the platform SDK has changed since the last time we booted, 19148 // we need to re-grant app permission to catch any new ones that 19149 // appear. This is really a hack, and means that apps can in some 19150 // cases get permissions that the user didn't initially explicitly 19151 // allow... it would be nice to have some better way to handle 19152 // this situation. 19153 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 19154 : mSettings.getInternalVersion(); 19155 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 19156 : StorageManager.UUID_PRIVATE_INTERNAL; 19157 19158 int updateFlags = UPDATE_PERMISSIONS_ALL; 19159 if (ver.sdkVersion != mSdkVersion) { 19160 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19161 + mSdkVersion + "; regranting permissions for external"); 19162 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19163 } 19164 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19165 19166 // Yay, everything is now upgraded 19167 ver.forceCurrent(); 19168 19169 // can downgrade to reader 19170 // Persist settings 19171 mSettings.writeLPr(); 19172 } 19173 // Send a broadcast to let everyone know we are done processing 19174 if (pkgList.size() > 0) { 19175 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 19176 } 19177 } 19178 19179 /* 19180 * Utility method to unload a list of specified containers 19181 */ 19182 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 19183 // Just unmount all valid containers. 19184 for (AsecInstallArgs arg : cidArgs) { 19185 synchronized (mInstallLock) { 19186 arg.doPostDeleteLI(false); 19187 } 19188 } 19189 } 19190 19191 /* 19192 * Unload packages mounted on external media. This involves deleting package 19193 * data from internal structures, sending broadcasts about disabled packages, 19194 * gc'ing to free up references, unmounting all secure containers 19195 * corresponding to packages on external media, and posting a 19196 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 19197 * that we always have to post this message if status has been requested no 19198 * matter what. 19199 */ 19200 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 19201 final boolean reportStatus) { 19202 if (DEBUG_SD_INSTALL) 19203 Log.i(TAG, "unloading media packages"); 19204 ArrayList<String> pkgList = new ArrayList<String>(); 19205 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 19206 final Set<AsecInstallArgs> keys = processCids.keySet(); 19207 for (AsecInstallArgs args : keys) { 19208 String pkgName = args.getPackageName(); 19209 if (DEBUG_SD_INSTALL) 19210 Log.i(TAG, "Trying to unload pkg : " + pkgName); 19211 // Delete package internally 19212 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19213 synchronized (mInstallLock) { 19214 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19215 final boolean res; 19216 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 19217 "unloadMediaPackages")) { 19218 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 19219 null); 19220 } 19221 if (res) { 19222 pkgList.add(pkgName); 19223 } else { 19224 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 19225 failedList.add(args); 19226 } 19227 } 19228 } 19229 19230 // reader 19231 synchronized (mPackages) { 19232 // We didn't update the settings after removing each package; 19233 // write them now for all packages. 19234 mSettings.writeLPr(); 19235 } 19236 19237 // We have to absolutely send UPDATED_MEDIA_STATUS only 19238 // after confirming that all the receivers processed the ordered 19239 // broadcast when packages get disabled, force a gc to clean things up. 19240 // and unload all the containers. 19241 if (pkgList.size() > 0) { 19242 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 19243 new IIntentReceiver.Stub() { 19244 public void performReceive(Intent intent, int resultCode, String data, 19245 Bundle extras, boolean ordered, boolean sticky, 19246 int sendingUser) throws RemoteException { 19247 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 19248 reportStatus ? 1 : 0, 1, keys); 19249 mHandler.sendMessage(msg); 19250 } 19251 }); 19252 } else { 19253 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 19254 keys); 19255 mHandler.sendMessage(msg); 19256 } 19257 } 19258 19259 private void loadPrivatePackages(final VolumeInfo vol) { 19260 mHandler.post(new Runnable() { 19261 @Override 19262 public void run() { 19263 loadPrivatePackagesInner(vol); 19264 } 19265 }); 19266 } 19267 19268 private void loadPrivatePackagesInner(VolumeInfo vol) { 19269 final String volumeUuid = vol.fsUuid; 19270 if (TextUtils.isEmpty(volumeUuid)) { 19271 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 19272 return; 19273 } 19274 19275 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 19276 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 19277 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 19278 19279 final VersionInfo ver; 19280 final List<PackageSetting> packages; 19281 synchronized (mPackages) { 19282 ver = mSettings.findOrCreateVersion(volumeUuid); 19283 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19284 } 19285 19286 for (PackageSetting ps : packages) { 19287 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 19288 synchronized (mInstallLock) { 19289 final PackageParser.Package pkg; 19290 try { 19291 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 19292 loaded.add(pkg.applicationInfo); 19293 19294 } catch (PackageManagerException e) { 19295 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 19296 } 19297 19298 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 19299 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 19300 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 19301 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 19302 } 19303 } 19304 } 19305 19306 // Reconcile app data for all started/unlocked users 19307 final StorageManager sm = mContext.getSystemService(StorageManager.class); 19308 final UserManager um = mContext.getSystemService(UserManager.class); 19309 UserManagerInternal umInternal = getUserManagerInternal(); 19310 for (UserInfo user : um.getUsers()) { 19311 final int flags; 19312 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 19313 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19314 } else if (umInternal.isUserRunning(user.id)) { 19315 flags = StorageManager.FLAG_STORAGE_DE; 19316 } else { 19317 continue; 19318 } 19319 19320 try { 19321 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 19322 synchronized (mInstallLock) { 19323 reconcileAppsDataLI(volumeUuid, user.id, flags); 19324 } 19325 } catch (IllegalStateException e) { 19326 // Device was probably ejected, and we'll process that event momentarily 19327 Slog.w(TAG, "Failed to prepare storage: " + e); 19328 } 19329 } 19330 19331 synchronized (mPackages) { 19332 int updateFlags = UPDATE_PERMISSIONS_ALL; 19333 if (ver.sdkVersion != mSdkVersion) { 19334 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19335 + mSdkVersion + "; regranting permissions for " + volumeUuid); 19336 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19337 } 19338 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19339 19340 // Yay, everything is now upgraded 19341 ver.forceCurrent(); 19342 19343 mSettings.writeLPr(); 19344 } 19345 19346 for (PackageFreezer freezer : freezers) { 19347 freezer.close(); 19348 } 19349 19350 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 19351 sendResourcesChangedBroadcast(true, false, loaded, null); 19352 } 19353 19354 private void unloadPrivatePackages(final VolumeInfo vol) { 19355 mHandler.post(new Runnable() { 19356 @Override 19357 public void run() { 19358 unloadPrivatePackagesInner(vol); 19359 } 19360 }); 19361 } 19362 19363 private void unloadPrivatePackagesInner(VolumeInfo vol) { 19364 final String volumeUuid = vol.fsUuid; 19365 if (TextUtils.isEmpty(volumeUuid)) { 19366 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 19367 return; 19368 } 19369 19370 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 19371 synchronized (mInstallLock) { 19372 synchronized (mPackages) { 19373 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 19374 for (PackageSetting ps : packages) { 19375 if (ps.pkg == null) continue; 19376 19377 final ApplicationInfo info = ps.pkg.applicationInfo; 19378 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19379 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19380 19381 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 19382 "unloadPrivatePackagesInner")) { 19383 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 19384 false, null)) { 19385 unloaded.add(info); 19386 } else { 19387 Slog.w(TAG, "Failed to unload " + ps.codePath); 19388 } 19389 } 19390 19391 // Try very hard to release any references to this package 19392 // so we don't risk the system server being killed due to 19393 // open FDs 19394 AttributeCache.instance().removePackage(ps.name); 19395 } 19396 19397 mSettings.writeLPr(); 19398 } 19399 } 19400 19401 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 19402 sendResourcesChangedBroadcast(false, false, unloaded, null); 19403 19404 // Try very hard to release any references to this path so we don't risk 19405 // the system server being killed due to open FDs 19406 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 19407 19408 for (int i = 0; i < 3; i++) { 19409 System.gc(); 19410 System.runFinalization(); 19411 } 19412 } 19413 19414 /** 19415 * Prepare storage areas for given user on all mounted devices. 19416 */ 19417 void prepareUserData(int userId, int userSerial, int flags) { 19418 synchronized (mInstallLock) { 19419 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19420 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19421 final String volumeUuid = vol.getFsUuid(); 19422 prepareUserDataLI(volumeUuid, userId, userSerial, flags, true); 19423 } 19424 } 19425 } 19426 19427 private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags, 19428 boolean allowRecover) { 19429 // Prepare storage and verify that serial numbers are consistent; if 19430 // there's a mismatch we need to destroy to avoid leaking data 19431 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19432 try { 19433 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags); 19434 19435 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) { 19436 UserManagerService.enforceSerialNumber( 19437 Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial); 19438 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19439 UserManagerService.enforceSerialNumber( 19440 Environment.getDataSystemDeDirectory(userId), userSerial); 19441 } 19442 } 19443 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) { 19444 UserManagerService.enforceSerialNumber( 19445 Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial); 19446 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19447 UserManagerService.enforceSerialNumber( 19448 Environment.getDataSystemCeDirectory(userId), userSerial); 19449 } 19450 } 19451 19452 synchronized (mInstallLock) { 19453 mInstaller.createUserData(volumeUuid, userId, userSerial, flags); 19454 } 19455 } catch (Exception e) { 19456 logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid 19457 + " because we failed to prepare: " + e); 19458 destroyUserDataLI(volumeUuid, userId, 19459 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19460 19461 if (allowRecover) { 19462 // Try one last time; if we fail again we're really in trouble 19463 prepareUserDataLI(volumeUuid, userId, userSerial, flags, false); 19464 } 19465 } 19466 } 19467 19468 /** 19469 * Destroy storage areas for given user on all mounted devices. 19470 */ 19471 void destroyUserData(int userId, int flags) { 19472 synchronized (mInstallLock) { 19473 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19474 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19475 final String volumeUuid = vol.getFsUuid(); 19476 destroyUserDataLI(volumeUuid, userId, flags); 19477 } 19478 } 19479 } 19480 19481 private void destroyUserDataLI(String volumeUuid, int userId, int flags) { 19482 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19483 try { 19484 // Clean up app data, profile data, and media data 19485 mInstaller.destroyUserData(volumeUuid, userId, flags); 19486 19487 // Clean up system data 19488 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19489 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19490 FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId)); 19491 FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId)); 19492 } 19493 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19494 FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId)); 19495 } 19496 } 19497 19498 // Data with special labels is now gone, so finish the job 19499 storage.destroyUserStorage(volumeUuid, userId, flags); 19500 19501 } catch (Exception e) { 19502 logCriticalInfo(Log.WARN, 19503 "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e); 19504 } 19505 } 19506 19507 /** 19508 * Examine all users present on given mounted volume, and destroy data 19509 * belonging to users that are no longer valid, or whose user ID has been 19510 * recycled. 19511 */ 19512 private void reconcileUsers(String volumeUuid) { 19513 final List<File> files = new ArrayList<>(); 19514 Collections.addAll(files, FileUtils 19515 .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid))); 19516 Collections.addAll(files, FileUtils 19517 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid))); 19518 Collections.addAll(files, FileUtils 19519 .listFilesOrEmpty(Environment.getDataSystemDeDirectory())); 19520 Collections.addAll(files, FileUtils 19521 .listFilesOrEmpty(Environment.getDataSystemCeDirectory())); 19522 for (File file : files) { 19523 if (!file.isDirectory()) continue; 19524 19525 final int userId; 19526 final UserInfo info; 19527 try { 19528 userId = Integer.parseInt(file.getName()); 19529 info = sUserManager.getUserInfo(userId); 19530 } catch (NumberFormatException e) { 19531 Slog.w(TAG, "Invalid user directory " + file); 19532 continue; 19533 } 19534 19535 boolean destroyUser = false; 19536 if (info == null) { 19537 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19538 + " because no matching user was found"); 19539 destroyUser = true; 19540 } else if (!mOnlyCore) { 19541 try { 19542 UserManagerService.enforceSerialNumber(file, info.serialNumber); 19543 } catch (IOException e) { 19544 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19545 + " because we failed to enforce serial number: " + e); 19546 destroyUser = true; 19547 } 19548 } 19549 19550 if (destroyUser) { 19551 synchronized (mInstallLock) { 19552 destroyUserDataLI(volumeUuid, userId, 19553 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19554 } 19555 } 19556 } 19557 } 19558 19559 private void assertPackageKnown(String volumeUuid, String packageName) 19560 throws PackageManagerException { 19561 synchronized (mPackages) { 19562 final PackageSetting ps = mSettings.mPackages.get(packageName); 19563 if (ps == null) { 19564 throw new PackageManagerException("Package " + packageName + " is unknown"); 19565 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19566 throw new PackageManagerException( 19567 "Package " + packageName + " found on unknown volume " + volumeUuid 19568 + "; expected volume " + ps.volumeUuid); 19569 } 19570 } 19571 } 19572 19573 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 19574 throws PackageManagerException { 19575 synchronized (mPackages) { 19576 final PackageSetting ps = mSettings.mPackages.get(packageName); 19577 if (ps == null) { 19578 throw new PackageManagerException("Package " + packageName + " is unknown"); 19579 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19580 throw new PackageManagerException( 19581 "Package " + packageName + " found on unknown volume " + volumeUuid 19582 + "; expected volume " + ps.volumeUuid); 19583 } else if (!ps.getInstalled(userId)) { 19584 throw new PackageManagerException( 19585 "Package " + packageName + " not installed for user " + userId); 19586 } 19587 } 19588 } 19589 19590 /** 19591 * Examine all apps present on given mounted volume, and destroy apps that 19592 * aren't expected, either due to uninstallation or reinstallation on 19593 * another volume. 19594 */ 19595 private void reconcileApps(String volumeUuid) { 19596 final File[] files = FileUtils 19597 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 19598 for (File file : files) { 19599 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 19600 && !PackageInstallerService.isStageName(file.getName()); 19601 if (!isPackage) { 19602 // Ignore entries which are not packages 19603 continue; 19604 } 19605 19606 try { 19607 final PackageLite pkg = PackageParser.parsePackageLite(file, 19608 PackageParser.PARSE_MUST_BE_APK); 19609 assertPackageKnown(volumeUuid, pkg.packageName); 19610 19611 } catch (PackageParserException | PackageManagerException e) { 19612 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19613 synchronized (mInstallLock) { 19614 removeCodePathLI(file); 19615 } 19616 } 19617 } 19618 } 19619 19620 /** 19621 * Reconcile all app data for the given user. 19622 * <p> 19623 * Verifies that directories exist and that ownership and labeling is 19624 * correct for all installed apps on all mounted volumes. 19625 */ 19626 void reconcileAppsData(int userId, int flags) { 19627 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19628 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19629 final String volumeUuid = vol.getFsUuid(); 19630 synchronized (mInstallLock) { 19631 reconcileAppsDataLI(volumeUuid, userId, flags); 19632 } 19633 } 19634 } 19635 19636 /** 19637 * Reconcile all app data on given mounted volume. 19638 * <p> 19639 * Destroys app data that isn't expected, either due to uninstallation or 19640 * reinstallation on another volume. 19641 * <p> 19642 * Verifies that directories exist and that ownership and labeling is 19643 * correct for all installed apps. 19644 */ 19645 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) { 19646 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 19647 + Integer.toHexString(flags)); 19648 19649 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 19650 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 19651 19652 boolean restoreconNeeded = false; 19653 19654 // First look for stale data that doesn't belong, and check if things 19655 // have changed since we did our last restorecon 19656 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19657 if (StorageManager.isFileEncryptedNativeOrEmulated() 19658 && !StorageManager.isUserKeyUnlocked(userId)) { 19659 throw new RuntimeException( 19660 "Yikes, someone asked us to reconcile CE storage while " + userId 19661 + " was still locked; this would have caused massive data loss!"); 19662 } 19663 19664 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 19665 19666 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 19667 for (File file : files) { 19668 final String packageName = file.getName(); 19669 try { 19670 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19671 } catch (PackageManagerException e) { 19672 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19673 try { 19674 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19675 StorageManager.FLAG_STORAGE_CE, 0); 19676 } catch (InstallerException e2) { 19677 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19678 } 19679 } 19680 } 19681 } 19682 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19683 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 19684 19685 final File[] files = FileUtils.listFilesOrEmpty(deDir); 19686 for (File file : files) { 19687 final String packageName = file.getName(); 19688 try { 19689 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19690 } catch (PackageManagerException e) { 19691 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19692 try { 19693 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19694 StorageManager.FLAG_STORAGE_DE, 0); 19695 } catch (InstallerException e2) { 19696 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19697 } 19698 } 19699 } 19700 } 19701 19702 // Ensure that data directories are ready to roll for all packages 19703 // installed for this volume and user 19704 final List<PackageSetting> packages; 19705 synchronized (mPackages) { 19706 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19707 } 19708 int preparedCount = 0; 19709 for (PackageSetting ps : packages) { 19710 final String packageName = ps.name; 19711 if (ps.pkg == null) { 19712 Slog.w(TAG, "Odd, missing scanned package " + packageName); 19713 // TODO: might be due to legacy ASEC apps; we should circle back 19714 // and reconcile again once they're scanned 19715 continue; 19716 } 19717 19718 if (ps.getInstalled(userId)) { 19719 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19720 19721 if (maybeMigrateAppDataLIF(ps.pkg, userId)) { 19722 // We may have just shuffled around app data directories, so 19723 // prepare them one more time 19724 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19725 } 19726 19727 preparedCount++; 19728 } 19729 } 19730 19731 if (restoreconNeeded) { 19732 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19733 SELinuxMMAC.setRestoreconDone(ceDir); 19734 } 19735 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19736 SELinuxMMAC.setRestoreconDone(deDir); 19737 } 19738 } 19739 19740 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 19741 + " packages; restoreconNeeded was " + restoreconNeeded); 19742 } 19743 19744 /** 19745 * Prepare app data for the given app just after it was installed or 19746 * upgraded. This method carefully only touches users that it's installed 19747 * for, and it forces a restorecon to handle any seinfo changes. 19748 * <p> 19749 * Verifies that directories exist and that ownership and labeling is 19750 * correct for all installed apps. If there is an ownership mismatch, it 19751 * will try recovering system apps by wiping data; third-party app data is 19752 * left intact. 19753 * <p> 19754 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 19755 */ 19756 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 19757 final PackageSetting ps; 19758 synchronized (mPackages) { 19759 ps = mSettings.mPackages.get(pkg.packageName); 19760 mSettings.writeKernelMappingLPr(ps); 19761 } 19762 19763 final UserManager um = mContext.getSystemService(UserManager.class); 19764 UserManagerInternal umInternal = getUserManagerInternal(); 19765 for (UserInfo user : um.getUsers()) { 19766 final int flags; 19767 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 19768 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19769 } else if (umInternal.isUserRunning(user.id)) { 19770 flags = StorageManager.FLAG_STORAGE_DE; 19771 } else { 19772 continue; 19773 } 19774 19775 if (ps.getInstalled(user.id)) { 19776 // Whenever an app changes, force a restorecon of its data 19777 // TODO: when user data is locked, mark that we're still dirty 19778 prepareAppDataLIF(pkg, user.id, flags, true); 19779 } 19780 } 19781 } 19782 19783 /** 19784 * Prepare app data for the given app. 19785 * <p> 19786 * Verifies that directories exist and that ownership and labeling is 19787 * correct for all installed apps. If there is an ownership mismatch, this 19788 * will try recovering system apps by wiping data; third-party app data is 19789 * left intact. 19790 */ 19791 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags, 19792 boolean restoreconNeeded) { 19793 if (pkg == null) { 19794 Slog.wtf(TAG, "Package was null!", new Throwable()); 19795 return; 19796 } 19797 prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded); 19798 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19799 for (int i = 0; i < childCount; i++) { 19800 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded); 19801 } 19802 } 19803 19804 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags, 19805 boolean restoreconNeeded) { 19806 if (DEBUG_APP_DATA) { 19807 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 19808 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 19809 } 19810 19811 final String volumeUuid = pkg.volumeUuid; 19812 final String packageName = pkg.packageName; 19813 final ApplicationInfo app = pkg.applicationInfo; 19814 final int appId = UserHandle.getAppId(app.uid); 19815 19816 Preconditions.checkNotNull(app.seinfo); 19817 19818 try { 19819 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19820 appId, app.seinfo, app.targetSdkVersion); 19821 } catch (InstallerException e) { 19822 if (app.isSystemApp()) { 19823 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 19824 + ", but trying to recover: " + e); 19825 destroyAppDataLeafLIF(pkg, userId, flags); 19826 try { 19827 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19828 appId, app.seinfo, app.targetSdkVersion); 19829 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 19830 } catch (InstallerException e2) { 19831 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 19832 } 19833 } else { 19834 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 19835 } 19836 } 19837 19838 if (restoreconNeeded) { 19839 try { 19840 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, 19841 app.seinfo); 19842 } catch (InstallerException e) { 19843 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 19844 } 19845 } 19846 19847 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19848 try { 19849 // CE storage is unlocked right now, so read out the inode and 19850 // remember for use later when it's locked 19851 // TODO: mark this structure as dirty so we persist it! 19852 final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId, 19853 StorageManager.FLAG_STORAGE_CE); 19854 synchronized (mPackages) { 19855 final PackageSetting ps = mSettings.mPackages.get(packageName); 19856 if (ps != null) { 19857 ps.setCeDataInode(ceDataInode, userId); 19858 } 19859 } 19860 } catch (InstallerException e) { 19861 Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e); 19862 } 19863 } 19864 19865 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19866 } 19867 19868 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 19869 if (pkg == null) { 19870 Slog.wtf(TAG, "Package was null!", new Throwable()); 19871 return; 19872 } 19873 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19874 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19875 for (int i = 0; i < childCount; i++) { 19876 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 19877 } 19878 } 19879 19880 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 19881 final String volumeUuid = pkg.volumeUuid; 19882 final String packageName = pkg.packageName; 19883 final ApplicationInfo app = pkg.applicationInfo; 19884 19885 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19886 // Create a native library symlink only if we have native libraries 19887 // and if the native libraries are 32 bit libraries. We do not provide 19888 // this symlink for 64 bit libraries. 19889 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 19890 final String nativeLibPath = app.nativeLibraryDir; 19891 try { 19892 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 19893 nativeLibPath, userId); 19894 } catch (InstallerException e) { 19895 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 19896 } 19897 } 19898 } 19899 } 19900 19901 /** 19902 * For system apps on non-FBE devices, this method migrates any existing 19903 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 19904 * requested by the app. 19905 */ 19906 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 19907 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 19908 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 19909 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 19910 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 19911 try { 19912 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 19913 storageTarget); 19914 } catch (InstallerException e) { 19915 logCriticalInfo(Log.WARN, 19916 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 19917 } 19918 return true; 19919 } else { 19920 return false; 19921 } 19922 } 19923 19924 public PackageFreezer freezePackage(String packageName, String killReason) { 19925 return freezePackage(packageName, UserHandle.USER_ALL, killReason); 19926 } 19927 19928 public PackageFreezer freezePackage(String packageName, int userId, String killReason) { 19929 return new PackageFreezer(packageName, userId, killReason); 19930 } 19931 19932 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 19933 String killReason) { 19934 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason); 19935 } 19936 19937 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags, 19938 String killReason) { 19939 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 19940 return new PackageFreezer(); 19941 } else { 19942 return freezePackage(packageName, userId, killReason); 19943 } 19944 } 19945 19946 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 19947 String killReason) { 19948 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason); 19949 } 19950 19951 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags, 19952 String killReason) { 19953 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 19954 return new PackageFreezer(); 19955 } else { 19956 return freezePackage(packageName, userId, killReason); 19957 } 19958 } 19959 19960 /** 19961 * Class that freezes and kills the given package upon creation, and 19962 * unfreezes it upon closing. This is typically used when doing surgery on 19963 * app code/data to prevent the app from running while you're working. 19964 */ 19965 private class PackageFreezer implements AutoCloseable { 19966 private final String mPackageName; 19967 private final PackageFreezer[] mChildren; 19968 19969 private final boolean mWeFroze; 19970 19971 private final AtomicBoolean mClosed = new AtomicBoolean(); 19972 private final CloseGuard mCloseGuard = CloseGuard.get(); 19973 19974 /** 19975 * Create and return a stub freezer that doesn't actually do anything, 19976 * typically used when someone requested 19977 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 19978 * {@link PackageManager#DELETE_DONT_KILL_APP}. 19979 */ 19980 public PackageFreezer() { 19981 mPackageName = null; 19982 mChildren = null; 19983 mWeFroze = false; 19984 mCloseGuard.open("close"); 19985 } 19986 19987 public PackageFreezer(String packageName, int userId, String killReason) { 19988 synchronized (mPackages) { 19989 mPackageName = packageName; 19990 mWeFroze = mFrozenPackages.add(mPackageName); 19991 19992 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 19993 if (ps != null) { 19994 killApplication(ps.name, ps.appId, userId, killReason); 19995 } 19996 19997 final PackageParser.Package p = mPackages.get(packageName); 19998 if (p != null && p.childPackages != null) { 19999 final int N = p.childPackages.size(); 20000 mChildren = new PackageFreezer[N]; 20001 for (int i = 0; i < N; i++) { 20002 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 20003 userId, killReason); 20004 } 20005 } else { 20006 mChildren = null; 20007 } 20008 } 20009 mCloseGuard.open("close"); 20010 } 20011 20012 @Override 20013 protected void finalize() throws Throwable { 20014 try { 20015 mCloseGuard.warnIfOpen(); 20016 close(); 20017 } finally { 20018 super.finalize(); 20019 } 20020 } 20021 20022 @Override 20023 public void close() { 20024 mCloseGuard.close(); 20025 if (mClosed.compareAndSet(false, true)) { 20026 synchronized (mPackages) { 20027 if (mWeFroze) { 20028 mFrozenPackages.remove(mPackageName); 20029 } 20030 20031 if (mChildren != null) { 20032 for (PackageFreezer freezer : mChildren) { 20033 freezer.close(); 20034 } 20035 } 20036 } 20037 } 20038 } 20039 } 20040 20041 /** 20042 * Verify that given package is currently frozen. 20043 */ 20044 private void checkPackageFrozen(String packageName) { 20045 synchronized (mPackages) { 20046 if (!mFrozenPackages.contains(packageName)) { 20047 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 20048 } 20049 } 20050 } 20051 20052 @Override 20053 public int movePackage(final String packageName, final String volumeUuid) { 20054 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 20055 20056 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 20057 final int moveId = mNextMoveId.getAndIncrement(); 20058 mHandler.post(new Runnable() { 20059 @Override 20060 public void run() { 20061 try { 20062 movePackageInternal(packageName, volumeUuid, moveId, user); 20063 } catch (PackageManagerException e) { 20064 Slog.w(TAG, "Failed to move " + packageName, e); 20065 mMoveCallbacks.notifyStatusChanged(moveId, 20066 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 20067 } 20068 } 20069 }); 20070 return moveId; 20071 } 20072 20073 private void movePackageInternal(final String packageName, final String volumeUuid, 20074 final int moveId, UserHandle user) throws PackageManagerException { 20075 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20076 final PackageManager pm = mContext.getPackageManager(); 20077 20078 final boolean currentAsec; 20079 final String currentVolumeUuid; 20080 final File codeFile; 20081 final String installerPackageName; 20082 final String packageAbiOverride; 20083 final int appId; 20084 final String seinfo; 20085 final String label; 20086 final int targetSdkVersion; 20087 final PackageFreezer freezer; 20088 final int[] installedUserIds; 20089 20090 // reader 20091 synchronized (mPackages) { 20092 final PackageParser.Package pkg = mPackages.get(packageName); 20093 final PackageSetting ps = mSettings.mPackages.get(packageName); 20094 if (pkg == null || ps == null) { 20095 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 20096 } 20097 20098 if (pkg.applicationInfo.isSystemApp()) { 20099 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 20100 "Cannot move system application"); 20101 } 20102 20103 if (pkg.applicationInfo.isExternalAsec()) { 20104 currentAsec = true; 20105 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 20106 } else if (pkg.applicationInfo.isForwardLocked()) { 20107 currentAsec = true; 20108 currentVolumeUuid = "forward_locked"; 20109 } else { 20110 currentAsec = false; 20111 currentVolumeUuid = ps.volumeUuid; 20112 20113 final File probe = new File(pkg.codePath); 20114 final File probeOat = new File(probe, "oat"); 20115 if (!probe.isDirectory() || !probeOat.isDirectory()) { 20116 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20117 "Move only supported for modern cluster style installs"); 20118 } 20119 } 20120 20121 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 20122 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20123 "Package already moved to " + volumeUuid); 20124 } 20125 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 20126 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 20127 "Device admin cannot be moved"); 20128 } 20129 20130 if (mFrozenPackages.contains(packageName)) { 20131 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 20132 "Failed to move already frozen package"); 20133 } 20134 20135 codeFile = new File(pkg.codePath); 20136 installerPackageName = ps.installerPackageName; 20137 packageAbiOverride = ps.cpuAbiOverrideString; 20138 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 20139 seinfo = pkg.applicationInfo.seinfo; 20140 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 20141 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 20142 freezer = freezePackage(packageName, "movePackageInternal"); 20143 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 20144 } 20145 20146 final Bundle extras = new Bundle(); 20147 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 20148 extras.putString(Intent.EXTRA_TITLE, label); 20149 mMoveCallbacks.notifyCreated(moveId, extras); 20150 20151 int installFlags; 20152 final boolean moveCompleteApp; 20153 final File measurePath; 20154 20155 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 20156 installFlags = INSTALL_INTERNAL; 20157 moveCompleteApp = !currentAsec; 20158 measurePath = Environment.getDataAppDirectory(volumeUuid); 20159 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 20160 installFlags = INSTALL_EXTERNAL; 20161 moveCompleteApp = false; 20162 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 20163 } else { 20164 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 20165 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 20166 || !volume.isMountedWritable()) { 20167 freezer.close(); 20168 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20169 "Move location not mounted private volume"); 20170 } 20171 20172 Preconditions.checkState(!currentAsec); 20173 20174 installFlags = INSTALL_INTERNAL; 20175 moveCompleteApp = true; 20176 measurePath = Environment.getDataAppDirectory(volumeUuid); 20177 } 20178 20179 final PackageStats stats = new PackageStats(null, -1); 20180 synchronized (mInstaller) { 20181 for (int userId : installedUserIds) { 20182 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 20183 freezer.close(); 20184 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20185 "Failed to measure package size"); 20186 } 20187 } 20188 } 20189 20190 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 20191 + stats.dataSize); 20192 20193 final long startFreeBytes = measurePath.getFreeSpace(); 20194 final long sizeBytes; 20195 if (moveCompleteApp) { 20196 sizeBytes = stats.codeSize + stats.dataSize; 20197 } else { 20198 sizeBytes = stats.codeSize; 20199 } 20200 20201 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 20202 freezer.close(); 20203 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20204 "Not enough free space to move"); 20205 } 20206 20207 mMoveCallbacks.notifyStatusChanged(moveId, 10); 20208 20209 final CountDownLatch installedLatch = new CountDownLatch(1); 20210 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 20211 @Override 20212 public void onUserActionRequired(Intent intent) throws RemoteException { 20213 throw new IllegalStateException(); 20214 } 20215 20216 @Override 20217 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 20218 Bundle extras) throws RemoteException { 20219 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 20220 + PackageManager.installStatusToString(returnCode, msg)); 20221 20222 installedLatch.countDown(); 20223 freezer.close(); 20224 20225 final int status = PackageManager.installStatusToPublicStatus(returnCode); 20226 switch (status) { 20227 case PackageInstaller.STATUS_SUCCESS: 20228 mMoveCallbacks.notifyStatusChanged(moveId, 20229 PackageManager.MOVE_SUCCEEDED); 20230 break; 20231 case PackageInstaller.STATUS_FAILURE_STORAGE: 20232 mMoveCallbacks.notifyStatusChanged(moveId, 20233 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 20234 break; 20235 default: 20236 mMoveCallbacks.notifyStatusChanged(moveId, 20237 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 20238 break; 20239 } 20240 } 20241 }; 20242 20243 final MoveInfo move; 20244 if (moveCompleteApp) { 20245 // Kick off a thread to report progress estimates 20246 new Thread() { 20247 @Override 20248 public void run() { 20249 while (true) { 20250 try { 20251 if (installedLatch.await(1, TimeUnit.SECONDS)) { 20252 break; 20253 } 20254 } catch (InterruptedException ignored) { 20255 } 20256 20257 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 20258 final int progress = 10 + (int) MathUtils.constrain( 20259 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 20260 mMoveCallbacks.notifyStatusChanged(moveId, progress); 20261 } 20262 } 20263 }.start(); 20264 20265 final String dataAppName = codeFile.getName(); 20266 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 20267 dataAppName, appId, seinfo, targetSdkVersion); 20268 } else { 20269 move = null; 20270 } 20271 20272 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 20273 20274 final Message msg = mHandler.obtainMessage(INIT_COPY); 20275 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 20276 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 20277 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 20278 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/); 20279 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 20280 msg.obj = params; 20281 20282 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 20283 System.identityHashCode(msg.obj)); 20284 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 20285 System.identityHashCode(msg.obj)); 20286 20287 mHandler.sendMessage(msg); 20288 } 20289 20290 @Override 20291 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 20292 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 20293 20294 final int realMoveId = mNextMoveId.getAndIncrement(); 20295 final Bundle extras = new Bundle(); 20296 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 20297 mMoveCallbacks.notifyCreated(realMoveId, extras); 20298 20299 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 20300 @Override 20301 public void onCreated(int moveId, Bundle extras) { 20302 // Ignored 20303 } 20304 20305 @Override 20306 public void onStatusChanged(int moveId, int status, long estMillis) { 20307 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 20308 } 20309 }; 20310 20311 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20312 storage.setPrimaryStorageUuid(volumeUuid, callback); 20313 return realMoveId; 20314 } 20315 20316 @Override 20317 public int getMoveStatus(int moveId) { 20318 mContext.enforceCallingOrSelfPermission( 20319 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20320 return mMoveCallbacks.mLastStatus.get(moveId); 20321 } 20322 20323 @Override 20324 public void registerMoveCallback(IPackageMoveObserver callback) { 20325 mContext.enforceCallingOrSelfPermission( 20326 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20327 mMoveCallbacks.register(callback); 20328 } 20329 20330 @Override 20331 public void unregisterMoveCallback(IPackageMoveObserver callback) { 20332 mContext.enforceCallingOrSelfPermission( 20333 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20334 mMoveCallbacks.unregister(callback); 20335 } 20336 20337 @Override 20338 public boolean setInstallLocation(int loc) { 20339 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 20340 null); 20341 if (getInstallLocation() == loc) { 20342 return true; 20343 } 20344 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 20345 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 20346 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 20347 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 20348 return true; 20349 } 20350 return false; 20351 } 20352 20353 @Override 20354 public int getInstallLocation() { 20355 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 20356 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 20357 PackageHelper.APP_INSTALL_AUTO); 20358 } 20359 20360 /** Called by UserManagerService */ 20361 void cleanUpUser(UserManagerService userManager, int userHandle) { 20362 synchronized (mPackages) { 20363 mDirtyUsers.remove(userHandle); 20364 mUserNeedsBadging.delete(userHandle); 20365 mSettings.removeUserLPw(userHandle); 20366 mPendingBroadcasts.remove(userHandle); 20367 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 20368 removeUnusedPackagesLPw(userManager, userHandle); 20369 } 20370 } 20371 20372 /** 20373 * We're removing userHandle and would like to remove any downloaded packages 20374 * that are no longer in use by any other user. 20375 * @param userHandle the user being removed 20376 */ 20377 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 20378 final boolean DEBUG_CLEAN_APKS = false; 20379 int [] users = userManager.getUserIds(); 20380 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 20381 while (psit.hasNext()) { 20382 PackageSetting ps = psit.next(); 20383 if (ps.pkg == null) { 20384 continue; 20385 } 20386 final String packageName = ps.pkg.packageName; 20387 // Skip over if system app 20388 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 20389 continue; 20390 } 20391 if (DEBUG_CLEAN_APKS) { 20392 Slog.i(TAG, "Checking package " + packageName); 20393 } 20394 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 20395 if (keep) { 20396 if (DEBUG_CLEAN_APKS) { 20397 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 20398 } 20399 } else { 20400 for (int i = 0; i < users.length; i++) { 20401 if (users[i] != userHandle && ps.getInstalled(users[i])) { 20402 keep = true; 20403 if (DEBUG_CLEAN_APKS) { 20404 Slog.i(TAG, " Keeping package " + packageName + " for user " 20405 + users[i]); 20406 } 20407 break; 20408 } 20409 } 20410 } 20411 if (!keep) { 20412 if (DEBUG_CLEAN_APKS) { 20413 Slog.i(TAG, " Removing package " + packageName); 20414 } 20415 mHandler.post(new Runnable() { 20416 public void run() { 20417 deletePackageX(packageName, userHandle, 0); 20418 } //end run 20419 }); 20420 } 20421 } 20422 } 20423 20424 /** Called by UserManagerService */ 20425 void createNewUser(int userId) { 20426 synchronized (mInstallLock) { 20427 mSettings.createNewUserLI(this, mInstaller, userId); 20428 } 20429 synchronized (mPackages) { 20430 scheduleWritePackageRestrictionsLocked(userId); 20431 scheduleWritePackageListLocked(userId); 20432 applyFactoryDefaultBrowserLPw(userId); 20433 primeDomainVerificationsLPw(userId); 20434 } 20435 } 20436 20437 void onBeforeUserStartUninitialized(final int userId) { 20438 synchronized (mPackages) { 20439 if (mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 20440 return; 20441 } 20442 } 20443 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 20444 // If permission review for legacy apps is required, we represent 20445 // dagerous permissions for such apps as always granted runtime 20446 // permissions to keep per user flag state whether review is needed. 20447 // Hence, if a new user is added we have to propagate dangerous 20448 // permission grants for these legacy apps. 20449 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 20450 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 20451 | UPDATE_PERMISSIONS_REPLACE_ALL); 20452 } 20453 } 20454 20455 @Override 20456 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 20457 mContext.enforceCallingOrSelfPermission( 20458 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 20459 "Only package verification agents can read the verifier device identity"); 20460 20461 synchronized (mPackages) { 20462 return mSettings.getVerifierDeviceIdentityLPw(); 20463 } 20464 } 20465 20466 @Override 20467 public void setPermissionEnforced(String permission, boolean enforced) { 20468 // TODO: Now that we no longer change GID for storage, this should to away. 20469 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 20470 "setPermissionEnforced"); 20471 if (READ_EXTERNAL_STORAGE.equals(permission)) { 20472 synchronized (mPackages) { 20473 if (mSettings.mReadExternalStorageEnforced == null 20474 || mSettings.mReadExternalStorageEnforced != enforced) { 20475 mSettings.mReadExternalStorageEnforced = enforced; 20476 mSettings.writeLPr(); 20477 } 20478 } 20479 // kill any non-foreground processes so we restart them and 20480 // grant/revoke the GID. 20481 final IActivityManager am = ActivityManagerNative.getDefault(); 20482 if (am != null) { 20483 final long token = Binder.clearCallingIdentity(); 20484 try { 20485 am.killProcessesBelowForeground("setPermissionEnforcement"); 20486 } catch (RemoteException e) { 20487 } finally { 20488 Binder.restoreCallingIdentity(token); 20489 } 20490 } 20491 } else { 20492 throw new IllegalArgumentException("No selective enforcement for " + permission); 20493 } 20494 } 20495 20496 @Override 20497 @Deprecated 20498 public boolean isPermissionEnforced(String permission) { 20499 return true; 20500 } 20501 20502 @Override 20503 public boolean isStorageLow() { 20504 final long token = Binder.clearCallingIdentity(); 20505 try { 20506 final DeviceStorageMonitorInternal 20507 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 20508 if (dsm != null) { 20509 return dsm.isMemoryLow(); 20510 } else { 20511 return false; 20512 } 20513 } finally { 20514 Binder.restoreCallingIdentity(token); 20515 } 20516 } 20517 20518 @Override 20519 public IPackageInstaller getPackageInstaller() { 20520 return mInstallerService; 20521 } 20522 20523 private boolean userNeedsBadging(int userId) { 20524 int index = mUserNeedsBadging.indexOfKey(userId); 20525 if (index < 0) { 20526 final UserInfo userInfo; 20527 final long token = Binder.clearCallingIdentity(); 20528 try { 20529 userInfo = sUserManager.getUserInfo(userId); 20530 } finally { 20531 Binder.restoreCallingIdentity(token); 20532 } 20533 final boolean b; 20534 if (userInfo != null && userInfo.isManagedProfile()) { 20535 b = true; 20536 } else { 20537 b = false; 20538 } 20539 mUserNeedsBadging.put(userId, b); 20540 return b; 20541 } 20542 return mUserNeedsBadging.valueAt(index); 20543 } 20544 20545 @Override 20546 public KeySet getKeySetByAlias(String packageName, String alias) { 20547 if (packageName == null || alias == null) { 20548 return null; 20549 } 20550 synchronized(mPackages) { 20551 final PackageParser.Package pkg = mPackages.get(packageName); 20552 if (pkg == null) { 20553 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20554 throw new IllegalArgumentException("Unknown package: " + packageName); 20555 } 20556 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20557 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 20558 } 20559 } 20560 20561 @Override 20562 public KeySet getSigningKeySet(String packageName) { 20563 if (packageName == null) { 20564 return null; 20565 } 20566 synchronized(mPackages) { 20567 final PackageParser.Package pkg = mPackages.get(packageName); 20568 if (pkg == null) { 20569 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20570 throw new IllegalArgumentException("Unknown package: " + packageName); 20571 } 20572 if (pkg.applicationInfo.uid != Binder.getCallingUid() 20573 && Process.SYSTEM_UID != Binder.getCallingUid()) { 20574 throw new SecurityException("May not access signing KeySet of other apps."); 20575 } 20576 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20577 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 20578 } 20579 } 20580 20581 @Override 20582 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 20583 if (packageName == null || ks == null) { 20584 return false; 20585 } 20586 synchronized(mPackages) { 20587 final PackageParser.Package pkg = mPackages.get(packageName); 20588 if (pkg == null) { 20589 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20590 throw new IllegalArgumentException("Unknown package: " + packageName); 20591 } 20592 IBinder ksh = ks.getToken(); 20593 if (ksh instanceof KeySetHandle) { 20594 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20595 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 20596 } 20597 return false; 20598 } 20599 } 20600 20601 @Override 20602 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 20603 if (packageName == null || ks == null) { 20604 return false; 20605 } 20606 synchronized(mPackages) { 20607 final PackageParser.Package pkg = mPackages.get(packageName); 20608 if (pkg == null) { 20609 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20610 throw new IllegalArgumentException("Unknown package: " + packageName); 20611 } 20612 IBinder ksh = ks.getToken(); 20613 if (ksh instanceof KeySetHandle) { 20614 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20615 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 20616 } 20617 return false; 20618 } 20619 } 20620 20621 private void deletePackageIfUnusedLPr(final String packageName) { 20622 PackageSetting ps = mSettings.mPackages.get(packageName); 20623 if (ps == null) { 20624 return; 20625 } 20626 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 20627 // TODO Implement atomic delete if package is unused 20628 // It is currently possible that the package will be deleted even if it is installed 20629 // after this method returns. 20630 mHandler.post(new Runnable() { 20631 public void run() { 20632 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 20633 } 20634 }); 20635 } 20636 } 20637 20638 /** 20639 * Check and throw if the given before/after packages would be considered a 20640 * downgrade. 20641 */ 20642 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 20643 throws PackageManagerException { 20644 if (after.versionCode < before.mVersionCode) { 20645 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20646 "Update version code " + after.versionCode + " is older than current " 20647 + before.mVersionCode); 20648 } else if (after.versionCode == before.mVersionCode) { 20649 if (after.baseRevisionCode < before.baseRevisionCode) { 20650 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20651 "Update base revision code " + after.baseRevisionCode 20652 + " is older than current " + before.baseRevisionCode); 20653 } 20654 20655 if (!ArrayUtils.isEmpty(after.splitNames)) { 20656 for (int i = 0; i < after.splitNames.length; i++) { 20657 final String splitName = after.splitNames[i]; 20658 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 20659 if (j != -1) { 20660 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 20661 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20662 "Update split " + splitName + " revision code " 20663 + after.splitRevisionCodes[i] + " is older than current " 20664 + before.splitRevisionCodes[j]); 20665 } 20666 } 20667 } 20668 } 20669 } 20670 } 20671 20672 private static class MoveCallbacks extends Handler { 20673 private static final int MSG_CREATED = 1; 20674 private static final int MSG_STATUS_CHANGED = 2; 20675 20676 private final RemoteCallbackList<IPackageMoveObserver> 20677 mCallbacks = new RemoteCallbackList<>(); 20678 20679 private final SparseIntArray mLastStatus = new SparseIntArray(); 20680 20681 public MoveCallbacks(Looper looper) { 20682 super(looper); 20683 } 20684 20685 public void register(IPackageMoveObserver callback) { 20686 mCallbacks.register(callback); 20687 } 20688 20689 public void unregister(IPackageMoveObserver callback) { 20690 mCallbacks.unregister(callback); 20691 } 20692 20693 @Override 20694 public void handleMessage(Message msg) { 20695 final SomeArgs args = (SomeArgs) msg.obj; 20696 final int n = mCallbacks.beginBroadcast(); 20697 for (int i = 0; i < n; i++) { 20698 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 20699 try { 20700 invokeCallback(callback, msg.what, args); 20701 } catch (RemoteException ignored) { 20702 } 20703 } 20704 mCallbacks.finishBroadcast(); 20705 args.recycle(); 20706 } 20707 20708 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 20709 throws RemoteException { 20710 switch (what) { 20711 case MSG_CREATED: { 20712 callback.onCreated(args.argi1, (Bundle) args.arg2); 20713 break; 20714 } 20715 case MSG_STATUS_CHANGED: { 20716 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 20717 break; 20718 } 20719 } 20720 } 20721 20722 private void notifyCreated(int moveId, Bundle extras) { 20723 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 20724 20725 final SomeArgs args = SomeArgs.obtain(); 20726 args.argi1 = moveId; 20727 args.arg2 = extras; 20728 obtainMessage(MSG_CREATED, args).sendToTarget(); 20729 } 20730 20731 private void notifyStatusChanged(int moveId, int status) { 20732 notifyStatusChanged(moveId, status, -1); 20733 } 20734 20735 private void notifyStatusChanged(int moveId, int status, long estMillis) { 20736 Slog.v(TAG, "Move " + moveId + " status " + status); 20737 20738 final SomeArgs args = SomeArgs.obtain(); 20739 args.argi1 = moveId; 20740 args.argi2 = status; 20741 args.arg3 = estMillis; 20742 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 20743 20744 synchronized (mLastStatus) { 20745 mLastStatus.put(moveId, status); 20746 } 20747 } 20748 } 20749 20750 private final static class OnPermissionChangeListeners extends Handler { 20751 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 20752 20753 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 20754 new RemoteCallbackList<>(); 20755 20756 public OnPermissionChangeListeners(Looper looper) { 20757 super(looper); 20758 } 20759 20760 @Override 20761 public void handleMessage(Message msg) { 20762 switch (msg.what) { 20763 case MSG_ON_PERMISSIONS_CHANGED: { 20764 final int uid = msg.arg1; 20765 handleOnPermissionsChanged(uid); 20766 } break; 20767 } 20768 } 20769 20770 public void addListenerLocked(IOnPermissionsChangeListener listener) { 20771 mPermissionListeners.register(listener); 20772 20773 } 20774 20775 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 20776 mPermissionListeners.unregister(listener); 20777 } 20778 20779 public void onPermissionsChanged(int uid) { 20780 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 20781 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 20782 } 20783 } 20784 20785 private void handleOnPermissionsChanged(int uid) { 20786 final int count = mPermissionListeners.beginBroadcast(); 20787 try { 20788 for (int i = 0; i < count; i++) { 20789 IOnPermissionsChangeListener callback = mPermissionListeners 20790 .getBroadcastItem(i); 20791 try { 20792 callback.onPermissionsChanged(uid); 20793 } catch (RemoteException e) { 20794 Log.e(TAG, "Permission listener is dead", e); 20795 } 20796 } 20797 } finally { 20798 mPermissionListeners.finishBroadcast(); 20799 } 20800 } 20801 } 20802 20803 private class PackageManagerInternalImpl extends PackageManagerInternal { 20804 @Override 20805 public void setLocationPackagesProvider(PackagesProvider provider) { 20806 synchronized (mPackages) { 20807 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 20808 } 20809 } 20810 20811 @Override 20812 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 20813 synchronized (mPackages) { 20814 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 20815 } 20816 } 20817 20818 @Override 20819 public void setSmsAppPackagesProvider(PackagesProvider provider) { 20820 synchronized (mPackages) { 20821 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 20822 } 20823 } 20824 20825 @Override 20826 public void setDialerAppPackagesProvider(PackagesProvider provider) { 20827 synchronized (mPackages) { 20828 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 20829 } 20830 } 20831 20832 @Override 20833 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 20834 synchronized (mPackages) { 20835 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 20836 } 20837 } 20838 20839 @Override 20840 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 20841 synchronized (mPackages) { 20842 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 20843 } 20844 } 20845 20846 @Override 20847 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 20848 synchronized (mPackages) { 20849 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 20850 packageName, userId); 20851 } 20852 } 20853 20854 @Override 20855 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 20856 synchronized (mPackages) { 20857 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 20858 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 20859 packageName, userId); 20860 } 20861 } 20862 20863 @Override 20864 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 20865 synchronized (mPackages) { 20866 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 20867 packageName, userId); 20868 } 20869 } 20870 20871 @Override 20872 public void setKeepUninstalledPackages(final List<String> packageList) { 20873 Preconditions.checkNotNull(packageList); 20874 List<String> removedFromList = null; 20875 synchronized (mPackages) { 20876 if (mKeepUninstalledPackages != null) { 20877 final int packagesCount = mKeepUninstalledPackages.size(); 20878 for (int i = 0; i < packagesCount; i++) { 20879 String oldPackage = mKeepUninstalledPackages.get(i); 20880 if (packageList != null && packageList.contains(oldPackage)) { 20881 continue; 20882 } 20883 if (removedFromList == null) { 20884 removedFromList = new ArrayList<>(); 20885 } 20886 removedFromList.add(oldPackage); 20887 } 20888 } 20889 mKeepUninstalledPackages = new ArrayList<>(packageList); 20890 if (removedFromList != null) { 20891 final int removedCount = removedFromList.size(); 20892 for (int i = 0; i < removedCount; i++) { 20893 deletePackageIfUnusedLPr(removedFromList.get(i)); 20894 } 20895 } 20896 } 20897 } 20898 20899 @Override 20900 public boolean isPermissionsReviewRequired(String packageName, int userId) { 20901 synchronized (mPackages) { 20902 // If we do not support permission review, done. 20903 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 20904 return false; 20905 } 20906 20907 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 20908 if (packageSetting == null) { 20909 return false; 20910 } 20911 20912 // Permission review applies only to apps not supporting the new permission model. 20913 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 20914 return false; 20915 } 20916 20917 // Legacy apps have the permission and get user consent on launch. 20918 PermissionsState permissionsState = packageSetting.getPermissionsState(); 20919 return permissionsState.isPermissionReviewRequired(userId); 20920 } 20921 } 20922 20923 @Override 20924 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 20925 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 20926 } 20927 20928 @Override 20929 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 20930 int userId) { 20931 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 20932 } 20933 20934 @Override 20935 public void setDeviceAndProfileOwnerPackages( 20936 int deviceOwnerUserId, String deviceOwnerPackage, 20937 SparseArray<String> profileOwnerPackages) { 20938 mProtectedPackages.setDeviceAndProfileOwnerPackages( 20939 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 20940 } 20941 20942 @Override 20943 public boolean isPackageDataProtected(int userId, String packageName) { 20944 return mProtectedPackages.isPackageDataProtected(userId, packageName); 20945 } 20946 } 20947 20948 @Override 20949 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 20950 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 20951 synchronized (mPackages) { 20952 final long identity = Binder.clearCallingIdentity(); 20953 try { 20954 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 20955 packageNames, userId); 20956 } finally { 20957 Binder.restoreCallingIdentity(identity); 20958 } 20959 } 20960 } 20961 20962 private static void enforceSystemOrPhoneCaller(String tag) { 20963 int callingUid = Binder.getCallingUid(); 20964 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 20965 throw new SecurityException( 20966 "Cannot call " + tag + " from UID " + callingUid); 20967 } 20968 } 20969 20970 boolean isHistoricalPackageUsageAvailable() { 20971 return mPackageUsage.isHistoricalPackageUsageAvailable(); 20972 } 20973 20974 /** 20975 * Return a <b>copy</b> of the collection of packages known to the package manager. 20976 * @return A copy of the values of mPackages. 20977 */ 20978 Collection<PackageParser.Package> getPackages() { 20979 synchronized (mPackages) { 20980 return new ArrayList<>(mPackages.values()); 20981 } 20982 } 20983 20984 /** 20985 * Logs process start information (including base APK hash) to the security log. 20986 * @hide 20987 */ 20988 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 20989 String apkFile, int pid) { 20990 if (!SecurityLog.isLoggingEnabled()) { 20991 return; 20992 } 20993 Bundle data = new Bundle(); 20994 data.putLong("startTimestamp", System.currentTimeMillis()); 20995 data.putString("processName", processName); 20996 data.putInt("uid", uid); 20997 data.putString("seinfo", seinfo); 20998 data.putString("apkFile", apkFile); 20999 data.putInt("pid", pid); 21000 Message msg = mProcessLoggingHandler.obtainMessage( 21001 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 21002 msg.setData(data); 21003 mProcessLoggingHandler.sendMessage(msg); 21004 } 21005} 21006